text
stringlengths
14
6.51M
//------------------------------------------------------------------------------ // 网页管理器 //------------------------------------------------------------------------------ unit UrlManager; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TUrlManager = class(TObject) private new_urls : TStringList; //已爬取列表 old_urls : TStringList; //待爬取列表 protected procedure add_new_url(url : string); //添加URL procedure add_new_urls(urls : TStringList); //添加多个URL function has_new_url:Boolean; //是否存在待爬取URL function get_new_url:string; //获取新的URL public constructor Create; destructor Destroy; override; published end; implementation { TUrlManager } procedure TUrlManager.add_new_url(url: string); var i : integer; begin if Trim(url) = '' then Exit; //不在待爬取队列,及已爬取队列中 for i := 0 to old_urls.Count - 1 do begin if url = old_urls[i] then Exit; end; for i := 0 to new_urls.Count - 1 do begin if url = new_urls[i] then Exit; end; //将新页面放入待爬取中 new_urls.Add(url); end; procedure TUrlManager.add_new_urls(urls: TStringList); var i : integer; begin if (Trim(urls.Text) = '') or (urls.Count = 0) then begin Exit; end; for i := 0 to urls.Count -1 do begin add_new_url(urls[i]); end; end; constructor TUrlManager.Create; begin //初始化两列表 new_urls := TStringList.Create; old_urls := TStringList.Create; end; destructor TUrlManager.Destroy; begin new_urls.Free; old_urls.Free; inherited; end; function TUrlManager.get_new_url: string; var new_url : string; begin Result := ''; if new_urls.Count > 0 then begin new_url := new_urls[0]; new_urls.Delete(0); old_urls.Add(new_url); Result := new_url; end; end; function TUrlManager.has_new_url: Boolean; begin Result := False; if new_urls.Count > 0 then Result := True; end; end.
unit LuaDotNetPipe; {$mode delphi} interface uses Classes, SysUtils; procedure initializeLuaDotNetPipe; implementation uses luahandler, lua, lauxlib, lualib, luaclass, LuaObject, symbolhandler, dotnetpipe, Maps; function dotnetpipe_enumDomains(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; domains: TDotNetDomainArray; i: integer; arraytable: integer; begin dnp:=luaclass_getClassObject(L); setlength(domains,0); dnp.EnumDomains(domains); lua_createtable(L,length(domains),0); for i:=0 to length(domains)-1 do begin lua_pushinteger(L,i+1); lua_createtable(L,0,2); lua_pushstring(L, 'DomainHandle'); lua_pushinteger(L, domains[i].hDomain); lua_settable(L,-3); //entry lua_pushstring(L, 'Name'); lua_pushstring(L, domains[i].Name); lua_settable(L,-3); //entry lua_settable(L,-3); //array end; result:=1; end; function dotnetpipe_enumModuleList(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; domain: uint64; modules: TDotNetModuleArray; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin domain:=lua_tointeger(L,1); setlength(modules,0); dnp.EnumModuleList(domain, modules); lua_createtable(L,length(modules),0); for i:=0 to length(modules)-1 do begin lua_pushinteger(L,i+1); lua_createtable(L,0,3); lua_pushstring(L, 'ModuleHandle'); lua_pushinteger(L, modules[i].hModule); lua_settable(L,-3); lua_pushstring(L, 'BaseAddress'); lua_pushinteger(L, modules[i].baseaddress); lua_settable(L,-3); lua_pushstring(L, 'Name'); lua_pushstring(L, modules[i].Name); lua_settable(L,-3); lua_settable(L,-3); end; result:=1; end; end; function dotnetpipe_enumTypeDefs(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; modulehandle: uint64; typedefs: TDotNetTypeDefArray; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin modulehandle:=lua_tointeger(L,1); setlength(typedefs,0); dnp.EnumTypeDefs(modulehandle, typedefs); lua_createtable(L,length(typedefs),0); for i:=0 to length(typedefs)-1 do begin lua_pushinteger(L,i+1); lua_createtable(L,0,4); lua_pushstring(L, 'TypeDefToken'); lua_pushinteger(L, typedefs[i].token); lua_settable(L,-3); lua_pushstring(L, 'Name'); lua_pushstring(L, typedefs[i].Name); lua_settable(L,-3); lua_pushstring(L, 'Flags'); lua_pushinteger(L, typedefs[i].flags); lua_settable(L,-3); lua_pushstring(L, 'Extends'); lua_pushinteger(L, typedefs[i].extends); lua_settable(L,-3); lua_settable(L,-3); end; result:=1; end; end; function dotnetpipe_getTypeDefMethods(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; modulehandle: uint64; typedeftoken: uint64; methods: TDotNetMethodArray; i,j: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin modulehandle:=lua_tointeger(L,1); typedeftoken:=lua_tointeger(L,2); lua_pop(L,lua_gettop(L)); setlength(methods,0); dnp.GetTypeDefMethods(modulehandle, typedeftoken, methods); lua_createtable(L,length(methods),0); for i:=0 to length(methods)-1 do begin //MethodToken, Name, Attributes, ImplementationFlags, ILCode, NativeCode, SecondaryNativeCode[] lua_pushinteger(L,i+1); lua_createtable(L,0,7); lua_pushstring(L, 'MethodToken'); lua_pushinteger(L, methods[i].token); lua_settable(L,-3); lua_pushstring(L, 'Name'); lua_pushstring(L, methods[i].Name); lua_settable(L,-3); lua_pushstring(L, 'Attributes'); lua_pushinteger(L, methods[i].Attributes); lua_settable(L,-3); lua_pushstring(L, 'ImplementationFlags'); lua_pushinteger(L, methods[i].implflags); lua_settable(L,-3); lua_pushstring(L, 'ILCode'); lua_pushinteger(L, methods[i].ILCode); lua_settable(L,-3); lua_pushstring(L, 'NativeCode'); lua_pushinteger(L, methods[i].NativeCode); lua_settable(L,-3); lua_pushstring(L, 'SecondaryNativeCode'); lua_createtable(L, length(methods[i].SecondaryNativeCode),0); for j:=0 to length(methods[i].SecondaryNativeCode)-1 do begin lua_pushinteger(L,j+1); lua_pushinteger(L,methods[i].SecondaryNativeCode[j].address); lua_settable(L,-3); //methods[i].SecondaryNativeCode[j+1]=address end; lua_settable(L,-3); //methods[i].SecondaryNativeCode={} lua_settable(L,-3); //methods[i]={} end; result:=1; end; end; function dotnetpipe_getMethodParameters(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; modulehandle: uint64; methoddef: dword; methodparameters: TDotNetMethodParameters; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin modulehandle:=lua_tointeger(L,1); methoddef:=lua_tointeger(L,2); dnp.getmethodparameters(modulehandle, methoddef,methodparameters); lua_createtable(L, length(methodparameters), 0); for i:=0 to length(methodparameters)-1 do begin lua_pushinteger(L,i+1); lua_createtable(L,0,2); lua_pushString(L,'Name'); lua_pushString(L,methodparameters[i].name); lua_settable(L,-3); lua_pushString(L,'CType'); lua_pushinteger(L,methodparameters[i].ctype); lua_settable(L,-3); lua_settable(L,-3); end; result:=1; end; end; function dotnetpipe_getTypeDefParent(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; module: QWORD; typedef: dword; tdpi: TTypeDefInfo; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin module:=lua_tointeger(L,1); typedef:=lua_tointeger(L,2); dnp.GetTypeDefParent(module, typedef, tdpi); if tdpi.module=0 then exit(0); lua_pop(L,lua_gettop(L)); lua_createtable(L,0,2); lua_pushstring(L,'ModuleHandle'); lua_pushinteger(L, tdpi.module); lua_settable(L,-3); lua_pushstring(L,'TypedefToken'); lua_pushinteger(L, tdpi.token); lua_settable(L,-3); exit(1); end; end; function dotnetpipe_getTypeDefData(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; module: QWORD; typedef: dword; typedata: TTypeData; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin module:=lua_tointeger(L,1); typedef:=lua_tointeger(L,2); FillByte(typedata, sizeof(typedata),0); dnp.getTypeDefData(module,typedef, typedata); if typedata.classname='' then exit(0); lua_createtable(L,0,7); lua_pushstring(L,'ObjectType'); lua_pushinteger(L, typedata.ObjectType); lua_settable(L,-3); lua_pushstring(L,'ElementType'); lua_pushinteger(L, typedata.ElementType); lua_settable(L,-3); lua_pushstring(L,'CountOffset'); lua_pushinteger(L, typedata.CountOffset); lua_settable(L,-3); lua_pushstring(L,'ElementSize'); lua_pushinteger(L, typedata.ElementSize); lua_settable(L,-3); lua_pushstring(L,'FirstElementOffset'); lua_pushinteger(L, typedata.FirstElementOffset); lua_settable(L,-3); lua_pushstring(L,'ClassName'); lua_pushstring(L, typedata.ClassName); lua_settable(L,-3); lua_pushstring(L,'Fields'); lua_createtable(L, length(typedata.fields),0); for i:=0 to length(typedata.Fields)-1 do begin lua_pushinteger(L, i+1); lua_createtable(L,0,7 ); lua_pushstring(L,'Token'); lua_pushinteger(L, typedata.fields[i].Token); lua_settable(L,-3); lua_pushstring(L,'Offset'); lua_pushinteger(L, typedata.fields[i].offset); lua_settable(L,-3); lua_pushstring(L,'FieldType'); lua_pushinteger(L, typedata.fields[i].fieldtype); lua_settable(L,-3); lua_pushstring(L,'Name'); lua_pushstring(L, typedata.fields[i].name); lua_settable(L,-3); lua_pushstring(L,'FieldTypeClassName'); lua_pushstring(L, typedata.fields[i].fieldTypeClassName); lua_settable(L,-3); lua_pushstring(L,'IsStatic'); lua_pushboolean(L, typedata.fields[i].IsStatic); lua_settable(L,-3); lua_pushstring(L,'Attribs'); lua_pushinteger(L, typedata.fields[i].attribs); lua_settable(L,-3); lua_settable(L,-3); end; lua_settable(L,-3); result:=1; end; end; function dotnetpipe_getAddressData(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; address: uint64; addressData: TAddressData; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin address:=lua_tointeger(L,1); FillByte(addressData, sizeof(addressData),0); dnp.GetAddressData(address, addressData); if addressdata.startaddress=0 then exit(0); lua_createtable(L,0,8); lua_pushstring(L,'StartAddress'); lua_pushinteger(L, addressData.startaddress); lua_settable(L,-3); lua_pushstring(L,'ObjectType'); lua_pushinteger(L, addressData.typedata.ObjectType); lua_settable(L,-3); lua_pushstring(L,'ElementType'); lua_pushinteger(L, addressData.typedata.ElementType); lua_settable(L,-3); lua_pushstring(L,'CountOffset'); lua_pushinteger(L, addressData.typedata.CountOffset); lua_settable(L,-3); lua_pushstring(L,'ElementSize'); lua_pushinteger(L, addressData.typedata.ElementSize); lua_settable(L,-3); lua_pushstring(L,'FirstElementOffset'); lua_pushinteger(L, addressData.typedata.FirstElementOffset); lua_settable(L,-3); lua_pushstring(L,'ClassName'); lua_pushstring(L, addressData.typedata.ClassName); lua_settable(L,-3); lua_pushstring(L,'Fields'); lua_createtable(L, length(addressData.typedata.fields),0); for i:=0 to length(addressData.typedata.Fields)-1 do begin lua_pushinteger(L, i+1); lua_createtable(L,0,4); lua_pushstring(L,'Token'); lua_pushinteger(L, addressData.typedata.fields[i].token); lua_settable(L,-3); lua_pushstring(L,'Offset'); lua_pushinteger(L, addressData.typedata.fields[i].offset); lua_settable(L,-3); lua_pushstring(L,'FieldType'); lua_pushinteger(L, addressData.typedata.fields[i].fieldtype); lua_settable(L,-3); lua_pushstring(L,'Name'); lua_pushstring(L, addressData.typedata.fields[i].name); lua_settable(L,-3); lua_pushstring(L,'FieldTypeClassName'); lua_pushstring(L, addressData.typedata.fields[i].fieldTypeClassName); lua_settable(L,-3); lua_pushstring(L,'IsStatic'); lua_pushboolean(L, addressData.typedata.fields[i].IsStatic); lua_settable(L,-3); lua_settable(L,-3); end; lua_settable(L,-3); result:=1; end; end; function dotnetpipe_enumAllObjectsOfType(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; module: QWORD; typedef: dword; list: TList; i: integer; begin result:=0; dnp:=luaclass_getClassObject(L); if lua_gettop(L)>=2 then begin module:=lua_tointeger(L,1); typedef:=lua_tointeger(L,2); list:=tlist.create; dnp.EnumAllObjectsOfType(module, typedef, list); lua_createtable(L,list.count,0); for i:=0 to list.count-1 do begin lua_pushinteger(L,i+1); lua_pushinteger(L,qword(list[i])); lua_settable(L,-3); end; list.free; result:=1; end; end; function dotnetpipe_enumAllObjects(L: PLua_state): integer; cdecl; var dnp: TDotNetPipe; address: uint64; addressData: TAddressData; i: integer; map: TDOTNETObjectList; mi: TMapIterator=nil; dno: PDotNetObject; begin result:=0; dnp:=luaclass_getClassObject(L); map:=dnp.EnumAllObjects; mi:=TMapIterator.Create(map); try lua_createtable(L,map.Count,0); i:=1; mi.First; while not mi.EOM do begin dno:=mi.DataPtr; lua_pushinteger(L,i); lua_createtable(L,4,0); //entry table lua_pushstring(L,'StartAddress'); lua_pushinteger(L,dno^.startaddress); lua_settable(L,-3); lua_pushstring(L,'Size'); lua_pushinteger(L,dno^.size); lua_settable(L,-3); lua_pushstring(L,'TypeID'); lua_createtable(L,0,2); //-1=typeid table lua_pushstring(L,'token1'); lua_pushinteger(L,dno^.typeid.token1); lua_settable(L,-3); lua_pushstring(L,'token2'); lua_pushinteger(L,dno^.typeid.token2); lua_settable(L,-3); lua_settable(L,-3); //typeid table lua_pushstring(L,'ClassName'); lua_pushstring(L,dno^.classname); lua_settable(L,-3); lua_settable(L,-3); //set entry to index mi.Next; inc(i); end; result:=1; //return the table finally mi.free; dnp.freeNETObjectList(map); end; end; function lua_getDotNetDataCollector(L: PLua_state): integer; cdecl; begin luaclass_newClass(L, symhandler.getDotNetDataCollector); result:=1; end; procedure dotnetpipe_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'enumDomains', dotnetpipe_enumDomains); luaclass_addClassFunctionToTable(L, metatable, userdata, 'enumModuleList', dotnetpipe_enumModuleList); luaclass_addClassFunctionToTable(L, metatable, userdata, 'enumTypeDefs', dotnetpipe_enumTypeDefs); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getTypeDefMethods', dotnetpipe_getTypeDefMethods); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getTypeDefData', dotnetpipe_getTypeDefData); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getTypeDefParent', dotnetpipe_getTypeDefParent); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getMethodParameters', dotnetpipe_getMethodParameters); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getAddressData', dotnetpipe_getAddressData); luaclass_addClassFunctionToTable(L, metatable, userdata, 'enumAllObjects', dotnetpipe_enumAllObjects); luaclass_addClassFunctionToTable(L, metatable, userdata, 'enumAllObjectsOfType', dotnetpipe_enumAllObjectsOfType); end; procedure initializeLuaDotNetPipe; begin lua_register(LuaVM, 'getDotNetDataCollector', lua_getDotNetDataCollector); end; initialization luaclass_register(TDotNetPipe, dotnetpipe_addMetaData); end.
unit PtGenericWorker; interface uses TestFramework, System.SysUtils, System.Types, System.Classes, Generics.Collections, System.Rtti, PtTypes, PtWorker, PtObjectClone; type TGenParameterizedTest<T: class> = class(TParameterizedTest) strict private FClonedObj: T; constructor Create(TestMethodName: string; AObjectToTest: T; AMethodName: string; ATestCase: TPtTestCase); overload; public procedure SetUp; override; procedure TearDown; override; // class function CreateTest(AObjectToTest: T; AMethodName: string; ATestCase: TPtTestCase) : ITestSuite; end; implementation constructor TGenParameterizedTest<T>.Create(TestMethodName: string; AObjectToTest: T; AMethodName: string; ATestCase: TPtTestCase); begin inherited Create(TestMethodName); // FClonedObj := TObjectClone.FromMarshal<T>(AObjectToTest); PtClassToTest := FClonedObj.ClassType; PtMethodName := AMethodName; PtTestCase := ATestCase; PtObjectForTesting := FClonedObj; end; class function TGenParameterizedTest<T>.CreateTest(AObjectToTest: T; AMethodName: string; ATestCase: TPtTestCase): ITestSuite; var LParameterizedTest: TGenParameterizedTest<T>; LTestParamsString: string; LConstructorParamsString: string; LTestParamsItem: TValue; LMethodEnumerator: TMethodEnumerator; LParamTestFuncName: string; TmpVal: TValue; i: Integer; begin // Reconstruct the function call string LTestParamsString := string.Empty; for LTestParamsItem in ATestCase.FTestParams do LTestParamsString := SmartJoin(', ', [LTestParamsString, LTestParamsItem.ToString]); // LConstructorParamsString := string.Empty; // Create the ITestSuite interface for DUnit Result := TTestSuite.Create(AMethodName + '(' + LTestParamsString + ') = ' + ATestCase.FExpectedResult.ToString + LConstructorParamsString); // Create one parameterized test (from TestMethod function) LMethodEnumerator := TMethodEnumerator.Create(Self); try for i := 0 to LMethodEnumerator.MethodCount - 1 do begin LParamTestFuncName := LMethodEnumerator.NameOfMethod[i]; LParameterizedTest := TGenParameterizedTest<T>.Create(LParamTestFuncName, AObjectToTest, AMethodName, ATestCase); Result.addTest(LParameterizedTest as ITest); end; finally FreeAndNil(LMethodEnumerator); end; end; procedure TGenParameterizedTest<T>.SetUp; begin end; procedure TGenParameterizedTest<T>.TearDown; begin end; end.
{ *************************************************************************** Dannyrooh Fernandes | https://github.com/dannyrooh | Licenša MIT converte string para TDateTime e TDateTime para string 08/2021 - created *************************************************************************** } unit Json.Util.DateTime; interface uses System.SysUtils, System.Math; type TClassJsonUtilDateTime = class of TJsonUtilDateTime; TJsonUtilDateTime = class private class function FormatSettingsData: TFormatSettings; public class function Decode(value: string; const dataDefault: TDateTime = 0): TDateTime; class function Encode(value: TDateTime; const dataDefault: TDateTime = 0): string; end; implementation { TJsonAsDatetime } class function TJsonUtilDateTime.Decode(value: string; const dataDefault: TDateTime): TDateTime; begin result := StrToDateTimeDef(value,dataDefault, self.FormatSettingsData); end; class function TJsonUtilDateTime.Encode(value: TDateTime; const dataDefault: TDateTime): string; begin result := DateTimeToStr(ifthen(value = 0, dataDefault,value),self.FormatSettingsData); end; class function TJsonUtilDateTime.FormatSettingsData: TFormatSettings; begin result := TFormatSettings.Create; result.DateSeparator := '-'; result.ShortDateFormat := 'yyyy-MM-dd'; result.TimeSeparator := ':'; result.ShortTimeFormat := 'hh:mm'; result.LongTimeFormat := 'hh:mm:ss'; end; end.
unit newListView; {$mode objfpc}{$H+} { For people wondering WHY the first subitem has a black background when highlighted and not the CE version released on the website: lazarus 2.0.6(and 2.2.2): win32wscustomlistview.inc subfunction HandleListViewCustomDraw of ListViewParentMsgHandler originalcode: if DrawInfo^.iSubItem = 0 then Exit; DrawResult := ALV.IntfCustomDraw(dtSubItem, Stage, DrawInfo^.nmcd.dwItemSpec, DrawInfo^.iSubItem, ConvState(DrawInfo^.nmcd.uItemState), nil); new code: DrawResult := ALV.IntfCustomDraw(dtSubItem, Stage, DrawInfo^.nmcd.dwItemSpec, DrawInfo^.iSubItem, ConvState(DrawInfo^.nmcd.uItemState), nil); if DrawInfo^.iSubItem = 0 then Exit; } interface uses jwawindows, windows, Classes, SysUtils, ComCtrls, Controls, messages, lmessages, graphics, CommCtrl; type TNewListView=class(ComCtrls.TListView) private fDefaultBackgroundColor: COLORREF; fDefaultTextColor: COLORREF; procedure setViewStyle(style: TViewStyle); function getViewStyle: TViewStyle; procedure pp(var msg: TMessage); message WM_NOTIFY; protected procedure ChildHandlesCreated; override; function CustomDraw(const ARect: TRect; AStage: TCustomDrawStage): Boolean; override; function CustomDrawItem(AItem: TListItem; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean; override; function CustomDrawSubItem(AItem: TListItem; ASubItem: Integer; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean; override; procedure SetParent(NewParent: TWinControl); override; public published property ViewStyle: TViewStyle read getViewStyle write setViewStyle; end; implementation uses betterControls; procedure TNewListView.SetParent(NewParent: TWinControl); var h: tHandle; begin inherited SetParent(newparent); if (parent<>nil) and (viewstyle=vsReport) and (not (csReadingState in ControlState)) then begin h:=ListView_GetHeader(handle); if (h<>0) and (h<>INVALID_HANDLE_VALUE) then begin AllowDarkModeForWindow(h, 1); SetWindowTheme(h, 'ItemsView',nil); end; end; end; procedure TNewListView.setViewStyle(style: TViewStyle); var h: THandle; olds: TViewstyle; cs: Tcontrolstate; begin olds:=viewstyle; inherited ViewStyle:=style; if ShouldAppsUseDarkMode() then begin cs:=ControlState; if (parent<>nil) and (olds<>style) and (style=vsReport) and (not (csReadingState in cs)) then begin h:=ListView_GetHeader(handle); if (h<>0) and (h<>INVALID_HANDLE_VALUE) then begin AllowDarkModeForWindow(h, 1); SetWindowTheme(h, 'ItemsView',nil); end; end; end; end; function TNewListView.getViewStyle: TViewStyle; begin result:=inherited ViewStyle; end; function TNewListView.CustomDraw(const ARect: TRect; AStage: TCustomDrawStage): Boolean; begin if ShouldAppsUseDarkMode then Canvas.Brush.style:=bsClear; result:=inherited customdraw(ARect, AStage); end; function TNewListView.CustomDrawItem(AItem: TListItem; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean; begin if ShouldAppsUseDarkMode then Canvas.Brush.style:=bsClear; result:=inherited CustomDrawItem(AItem, AState, AStage); end; function TNewListView.CustomDrawSubItem(AItem: TListItem; ASubItem: Integer; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean; begin if ShouldAppsUseDarkMode then Canvas.Brush.style:=bsClear; result:=inherited CustomDrawSubItem(AItem, ASubItem, AState, AStage); end; procedure TNewListView.ChildHandlesCreated; var theme: THandle; h: thandle; begin inherited ChildHandlesCreated; if ShouldAppsUseDarkMode then begin if parent<>nil then begin AllowDarkModeForWindow(handle, 1); SetWindowTheme(handle, 'Explorer', nil); theme:=OpenThemeData(0,'ItemsView'); //yeah....why make it obvious if you can make it obscure right ? (This is a microsoft thing, not because i'm an asshole ) if theme<>0 then begin GetThemeColor(theme, 0,0,TMT_TEXTCOLOR,fDefaultTextColor); GetThemeColor(theme, 0,0,TMT_FILLCOLOR,fDefaultBackgroundColor); CloseThemeData(theme); end else fDefaultTextColor:=font.color; Font.color:=fDefaultTextColor; Color:=fDefaultBackgroundColor; h:=ListView_GetHeader(handle); if (h<>0) and (h<>INVALID_HANDLE_VALUE) then begin AllowDarkModeForWindow(h, 1); SetWindowTheme(h, 'ItemsView',nil); end; end; end; end; procedure TNewListView.pp(var msg: TMessage); var p1: LPNMHDR; p2: LPNMCUSTOMDRAW; columnid: integer; c: tcolor; begin p1:=LPNMHDR(msg.lparam); if p1^.code=UINT(NM_CUSTOMDRAW) then begin p2:=LPNMCUSTOMDRAW(msg.lParam); case p2^.dwDrawStage of CDDS_PREPAINT: msg.Result:=CDRF_NOTIFYITEMDRAW; CDDS_ITEMPREPAINT: begin msg.result:=CDRF_DODEFAULT; columnid:=p2^.dwItemSpec; if (columnid>=0) and (columnid<columncount) and (column[columnid].tag<>0) then c:=column[columnid].tag else c:=clWindowtext; SetTextColor(p2^.hdc, c); end; end; end; end; end.
unit UFuncionario; interface uses UDependente, System.Generics.Collections; type TProcForInDependente = reference to procedure (dep: TDependente); type TFuncionario = class private FNome: String; FCPF: String; FSalario: Currency; FDependentes : TList<TDependente>; FId: Integer; private function getNome: String; procedure SetNome(const Value: String); function getCPF: String; procedure setCPF(const Value: String); function getSalario: Currency; procedure SetSalario(const Value: Currency); function getId: Integer; procedure SetId(const Value: Integer); public constructor Create(id: integer; Nome: String; CPF: String; Salario: Currency); destructor Destroy();override; function ValorINSS(): Currency; function ValorIR(): Currency; function AddDependente(dep: TDependente): TFuncionario; procedure ForInDependentes(proc: TProcForInDependente); property Id: Integer read getId write SetId; property Nome: String read getNome write SetNome; property CPF: String read getCPF write setCPF; property Salario: Currency read getSalario write SetSalario; end; implementation uses System.SysUtils; { TFuncionario } function TFuncionario.AddDependente(dep: TDependente): TFuncionario; begin FDependentes.Add(dep); result :=self; end; constructor TFuncionario.Create(id: integer; Nome: String; CPF: String; Salario: Currency); begin self.FId := id; self.FNome := Nome; self.CPF := CPF; self.Salario := Salario; FDependentes := TList<TDependente>.Create(); end; destructor TFuncionario.Destroy; begin ForInDependentes(procedure(dep: Tdependente) begin dep.free; end ); FDependentes.Free; inherited; end; procedure TFuncionario.ForInDependentes(proc: TProcForInDependente); var dep: TDependente; begin for dep in FDependentes do begin proc(dep); end; end; function TFuncionario.getCPF: String; begin result := FCPF; end; function TFuncionario.getId: Integer; begin result := FId; end; function TFuncionario.getNome: String; begin result := FNome; end; function TFuncionario.getSalario: Currency; begin result:=FSalario; end; procedure TFuncionario.setCPF(const Value: String); begin FCPF := value; end; procedure TFuncionario.SetId(const Value: Integer); begin FId := value; end; procedure TFuncionario.SetNome(const Value: String); begin Fnome:=value; end; procedure TFuncionario.SetSalario(const Value: Currency); begin FSalario := value; end; function TFuncionario.ValorINSS: Currency; var dep: TDependente; calculaINSS: boolean; countCalculoIR : integer; begin calculaINSS := false; countCalculoIR := 0; for dep in fdependentes do begin if dep.isCalculaINSS then calculaINSS := true; end; if calculaINSS then result := Salario * 0.08 else result := 0; end; function TFuncionario.ValorIR: Currency; var dep: TDependente; countCalculoIR : integer; begin countCalculoIR := 0; for dep in fdependentes do begin if dep.IsCalculaIR then Inc(countCalculoIR); end; if countCalculoIR > 0 then result := (Salario - (countCalculoIR * 100)) * 0.15 else result := 0; end; end.
// creates COBJ record for item function createRecipe(item: IInterface): IInterface; var recipe: IInterface; begin // create COBJ record recipe := createRecord(GetFile(item), 'COBJ'); // add reference to the created object SetElementEditValues(recipe, 'CNAM', Name(item)); // set Created Object Count SetElementEditValues(recipe, 'NAM1', '1'); Result := recipe; end;
unit UnitStringHashMap; // Copyright (C) 2006-2017, Benjamin Rosseaux - License: zlib {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpu386} {$asmmode intel} {$endif} {$ifdef cpuamd64} {$asmmode intel} {$endif} {$ifdef fpc_little_endian} {$define little_endian} {$else} {$ifdef fpc_big_endian} {$define big_endian} {$endif} {$endif} {$ifdef fpc_has_internal_sar} {$define HasSAR} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$else} {$realcompatibility off} {$localsymbols on} {$define little_endian} {$ifndef cpu64} {$define cpu32} {$endif} {$define delphi} {$undef HasSAR} {$define UseDIV} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$define HAS_TYPE_SINGLE} {$endif} {$ifdef cpu386} {$define cpux86} {$endif} {$ifdef cpuamd64} {$define cpux86} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$ifdef windows} {$define win} {$endif} {$ifdef sdl20} {$define sdl} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} {$ifndef HAS_TYPE_DOUBLE} {$error No double floating point precision} {$endif} {$ifdef fpc} {$define caninline} {$else} {$undef caninline} {$ifdef ver180} {$define caninline} {$else} {$ifdef conditionalexpressions} {$if compilerversion>=18} {$define caninline} {$ifend} {$endif} {$endif} {$endif} interface type TStringHashMapData=pointer; PStringHashMapEntity=^TStringHashMapEntity; TStringHashMapEntity=record Key:ansistring; Value:TStringHashMapData; end; TStringHashMapEntities=array of TStringHashMapEntity; TStringHashMapEntityIndices=array of longint; TStringHashMap=class private function FindCell(const Key:ansistring):longword; procedure Resize; protected function GetValue(const Key:ansistring):TStringHashMapData; procedure SetValue(const Key:ansistring;const Value:TStringHashMapData); public RealSize:longint; LogSize:longint; Size:longint; Entities:TStringHashMapEntities; EntityToCellIndex:TStringHashMapEntityIndices; CellToEntityIndex:TStringHashMapEntityIndices; constructor Create; destructor Destroy; override; procedure Clear; function Add(const Key:ansistring;Value:TStringHashMapData):PStringHashMapEntity; function Get(const Key:ansistring;CreateIfNotExist:boolean=false):PStringHashMapEntity; function Delete(const Key:ansistring):boolean; property Values[const Key:ansistring]:TStringHashMapData read GetValue write SetValue; default; end; implementation const CELL_EMPTY=-1; CELL_DELETED=-2; ENT_EMPTY=-1; ENT_DELETED=-2; function HashString(const Str:ansistring):longword; {$ifdef cpuarm} var b:pansichar; len,h,i:longword; begin result:=2166136261; len:=length(Str); h:=len; if len>0 then begin b:=pansichar(Str); while len>3 do begin i:=longword(pointer(b)^); h:=(h xor i) xor $2e63823a; inc(h,(h shl 15) or (h shr (32-15))); dec(h,(h shl 9) or (h shr (32-9))); inc(h,(h shl 4) or (h shr (32-4))); dec(h,(h shl 1) or (h shr (32-1))); h:=h xor (h shl 2) or (h shr (32-2)); result:=result xor i; inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24)); inc(b,4); dec(len,4); end; if len>1 then begin i:=word(pointer(b)^); h:=(h xor i) xor $2e63823a; inc(h,(h shl 15) or (h shr (32-15))); dec(h,(h shl 9) or (h shr (32-9))); inc(h,(h shl 4) or (h shr (32-4))); dec(h,(h shl 1) or (h shr (32-1))); h:=h xor (h shl 2) or (h shr (32-2)); result:=result xor i; inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24)); inc(b,2); dec(len,2); end; if len>0 then begin i:=byte(b^); h:=(h xor i) xor $2e63823a; inc(h,(h shl 15) or (h shr (32-15))); dec(h,(h shl 9) or (h shr (32-9))); inc(h,(h shl 4) or (h shr (32-4))); dec(h,(h shl 1) or (h shr (32-1))); h:=h xor (h shl 2) or (h shr (32-2)); result:=result xor i; inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24)); end; end; result:=result xor h; if result=0 then begin result:=$ffffffff; end; end; {$else} const m=longword($57559429); n=longword($5052acdb); var b:pansichar; h,k,len:longword; p:{$ifdef fpc}qword{$else}int64{$endif}; begin len:=length(Str); h:=len; k:=h+n+1; if len>0 then begin b:=pansichar(Str); while len>7 do begin begin p:=longword(pointer(b)^)*{$ifdef fpc}qword{$else}int64{$endif}(n); h:=h xor longword(p and $ffffffff); k:=k xor longword(p shr 32); inc(b,4); end; begin p:=longword(pointer(b)^)*{$ifdef fpc}qword{$else}int64{$endif}(m); k:=k xor longword(p and $ffffffff); h:=h xor longword(p shr 32); inc(b,4); end; dec(len,8); end; if len>3 then begin p:=longword(pointer(b)^)*{$ifdef fpc}qword{$else}int64{$endif}(n); h:=h xor longword(p and $ffffffff); k:=k xor longword(p shr 32); inc(b,4); dec(len,4); end; if len>0 then begin if len>1 then begin p:=word(pointer(b)^); inc(b,2); dec(len,2); end else begin p:=0; end; if len>0 then begin p:=p or (byte(b^) shl 16); end; p:=p*{$ifdef fpc}qword{$else}int64{$endif}(m); k:=k xor longword(p and $ffffffff); h:=h xor longword(p shr 32); end; end; begin p:=(h xor (k+n))*{$ifdef fpc}qword{$else}int64{$endif}(n); h:=h xor longword(p and $ffffffff); k:=k xor longword(p shr 32); end; result:=k xor h; if result=0 then begin result:=$ffffffff; end; end; {$endif} constructor TStringHashMap.Create; begin inherited Create; RealSize:=0; LogSize:=0; Size:=0; Entities:=nil; EntityToCellIndex:=nil; CellToEntityIndex:=nil; Resize; end; destructor TStringHashMap.Destroy; var Counter:longint; begin Clear; for Counter:=0 to length(Entities)-1 do begin Entities[Counter].Key:=''; end; SetLength(Entities,0); SetLength(EntityToCellIndex,0); SetLength(CellToEntityIndex,0); inherited Destroy; end; procedure TStringHashMap.Clear; var Counter:longint; begin for Counter:=0 to length(Entities)-1 do begin Entities[Counter].Key:=''; end; RealSize:=0; LogSize:=0; Size:=0; SetLength(Entities,0); SetLength(EntityToCellIndex,0); SetLength(CellToEntityIndex,0); Resize; end; function TStringHashMap.FindCell(const Key:ansistring):longword; var HashCode,Mask,Step:longword; Entity:longint; begin HashCode:=HashString(Key); Mask:=(2 shl LogSize)-1; Step:=((HashCode shl 1)+1) and Mask; if LogSize<>0 then begin result:=HashCode shr (32-LogSize); end else begin result:=0; end; repeat Entity:=CellToEntityIndex[result]; if (Entity=ENT_EMPTY) or ((Entity<>ENT_DELETED) and (Entities[Entity].Key=Key)) then begin exit; end; result:=(result+Step) and Mask; until false; end; procedure TStringHashMap.Resize; var NewLogSize,NewSize,Cell,Entity,Counter:longint; OldEntities:TStringHashMapEntities; OldCellToEntityIndex:TStringHashMapEntityIndices; OldEntityToCellIndex:TStringHashMapEntityIndices; begin NewLogSize:=0; NewSize:=RealSize; while NewSize<>0 do begin NewSize:=NewSize shr 1; inc(NewLogSize); end; if NewLogSize<1 then begin NewLogSize:=1; end; Size:=0; RealSize:=0; LogSize:=NewLogSize; OldEntities:=Entities; OldCellToEntityIndex:=CellToEntityIndex; OldEntityToCellIndex:=EntityToCellIndex; Entities:=nil; CellToEntityIndex:=nil; EntityToCellIndex:=nil; SetLength(Entities,2 shl LogSize); SetLength(CellToEntityIndex,2 shl LogSize); SetLength(EntityToCellIndex,2 shl LogSize); for Counter:=0 to length(CellToEntityIndex)-1 do begin CellToEntityIndex[Counter]:=ENT_EMPTY; end; for Counter:=0 to length(EntityToCellIndex)-1 do begin EntityToCellIndex[Counter]:=CELL_EMPTY; end; for Counter:=0 to length(OldEntityToCellIndex)-1 do begin Cell:=OldEntityToCellIndex[Counter]; if Cell>=0 then begin Entity:=OldCellToEntityIndex[Cell]; if Entity>=0 then begin Add(OldEntities[Counter].Key,OldEntities[Counter].Value); end; end; end; for Counter:=0 to length(OldEntities)-1 do begin OldEntities[Counter].Key:=''; end; SetLength(OldEntities,0); SetLength(OldCellToEntityIndex,0); SetLength(OldEntityToCellIndex,0); end; function TStringHashMap.Add(const Key:ansistring;Value:TStringHashMapData):PStringHashMapEntity; var Entity:longint; Cell:longword; begin result:=nil; while RealSize>=(1 shl LogSize) do begin Resize; end; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=@Entities[Entity]; result^.Key:=Key; result^.Value:=Value; exit; end; Entity:=Size; inc(Size); if Entity<(2 shl LogSize) then begin CellToEntityIndex[Cell]:=Entity; EntityToCellIndex[Entity]:=Cell; inc(RealSize); result:=@Entities[Entity]; result^.Key:=Key; result^.Value:=Value; end; end; function TStringHashMap.Get(const Key:ansistring;CreateIfNotExist:boolean=false):PStringHashMapEntity; var Entity:longint; Cell:longword; begin result:=nil; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=@Entities[Entity]; end else if CreateIfNotExist then begin result:=Add(Key,nil); end; end; function TStringHashMap.Delete(const Key:ansistring):boolean; var Entity:longint; Cell:longword; begin result:=false; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin Entities[Entity].Key:=''; Entities[Entity].Value:=nil; EntityToCellIndex[Entity]:=CELL_DELETED; CellToEntityIndex[Cell]:=ENT_DELETED; result:=true; end; end; function TStringHashMap.GetValue(const Key:ansistring):TStringHashMapData; var Entity:longint; Cell:longword; begin Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=Entities[Entity].Value; end else begin result:=nil; end; end; procedure TStringHashMap.SetValue(const Key:ansistring;const Value:TStringHashMapData); begin Add(Key,Value); end; end.
unit BaseTable; interface uses Contnrs; type TBaseTableCell = class private FObject: TObject; FValue: variant; public property Value: variant read FValue write FValue; property Data: TObject read FObject write FObject; function IsEmpty: boolean; function AsString: string; function AsFloat: double; function AsDateTime: TDateTime; end; TBaseTableCells = class(TObjectList) private FEmpty: boolean; function GetItems(const Index: integer): TBaseTableCell; public function Add: TBaseTableCell; overload; procedure AddToIndex(AIndex: integer); procedure Add(ACell: TBaseTableCell); overload; property Items[const Index: integer]: TBaseTableCell read GetItems; default; property Empty: boolean read FEmpty write FEmpty; constructor Create; end; TBaseTableCellsGroup = class(TObjectList) private function GetItems(const Index: integer): TBaseTableCells; public function AddToIndex(AIndex: Integer; const OwnsObjects: Boolean = true): TBaseTableCells; function Add(const OwnsObjects: Boolean = true): TBaseTableCells; property Items[const Index: integer]: TBaseTableCells read GetItems; default; constructor Create; end; TBaseTable = class private FColumns: TBaseTableCellsGroup; FRows: TBaseTableCellsGroup; function GetColumns: TBaseTableCellsGroup; function GetFirstColumn: TBaseTableCells; function GetFooter: TBaseTableCells; function GetHeader: TBaseTableCells; function GetRows: TBaseTableCellsGroup; function GetColumnCount: integer; function GetRowCount: integer; protected function CheckPreconditions: boolean; virtual; procedure OpenFile(AFileName: string); virtual; procedure LoadRows; virtual; function CheckCellsEmpty(ACells: TBaseTableCells): boolean; virtual; public property Rows: TBaseTableCellsGroup read GetRows; property Columns: TBaseTableCellsGroup read GetColumns; property RowCount: integer read GetRowCount; property ColumnCount: integer read GetColumnCount; property Header: TBaseTableCells read GetHeader; property Footer: TBaseTableCells read GetFooter; property FirstColumn: TBaseTableCells read GetFirstColumn; procedure LoadFromFile(AFileName: string); constructor Create; destructor Destroy; override; end; implementation uses SysUtils, Dialogs, Variants; { TBaseTableRow } function TBaseTableCells.Add: TBaseTableCell; begin Result := TBaseTableCell.Create; inherited Add(Result); end; procedure TBaseTableCells.Add(ACell: TBaseTableCell); begin inherited Add(ACell); end; procedure TBaseTableCells.AddToIndex(AIndex: integer); begin While AIndex > Count - 1 do Add; end; constructor TBaseTableCells.Create; begin inherited Create(true); FEmpty := false; end; function TBaseTableCells.GetItems(const Index: integer): TBaseTableCell; begin Result := inherited Items[Index] as TBaseTableCell; end; { TBaseTableCell } function TBaseTableCell.AsDateTime: TDateTime; begin try Result := VarAsType(Value, varDate) except Result := NULL; end; end; function TBaseTableCell.AsFloat: double; begin try result := VarAsType(Value, varDouble) except Result := -2; end; end; function TBaseTableCell.AsString: string; begin Result := trim(VarAsType(Value, varOleStr)); end; function TBaseTableCell.IsEmpty: boolean; begin Result := VarIsEmpty(Value) or VarIsNull(Value) or VarIsClear(Value) or (AsString = ''); end; { TBaseTableCellsGroup } function TBaseTableCellsGroup.Add(const OwnsObjects: Boolean = true): TBaseTableCells; begin Result := TBaseTableCells.Create; Result.OwnsObjects := OwnsObjects; inherited Add(Result); end; function TBaseTableCellsGroup.AddToIndex(AIndex: Integer; const OwnsObjects: Boolean): TBaseTableCells; begin Result := nil; While AIndex > Count - 1 do Result := Add(OwnsObjects); end; constructor TBaseTableCellsGroup.Create; begin inherited Create(true); end; function TBaseTableCellsGroup.GetItems( const Index: integer): TBaseTableCells; begin Result := inherited Items[Index] as TBaseTableCells; end; { TBaseTable } function TBaseTable.CheckCellsEmpty(ACells: TBaseTableCells): boolean; begin ACells.Empty := false; Result := ACells.Empty; end; function TBaseTable.CheckPreconditions: boolean; begin Result := false; if not Result then MessageDlg('Не заданы параметны загрузки файла', mtError, [mbOK], 0); end; constructor TBaseTable.Create; begin inherited; end; destructor TBaseTable.Destroy; begin FreeAndNil(FColumns); FreeAndNil(FRows); inherited; end; function TBaseTable.GetColumnCount: integer; begin Result := Columns.Count; end; function TBaseTable.GetColumns: TBaseTableCellsGroup; begin if not Assigned(FColumns) then begin FColumns := TBaseTableCellsGroup.Create; FColumns.OwnsObjects := false; end; Result := FColumns; end; function TBaseTable.GetFirstColumn: TBaseTableCells; begin Result := Columns[0]; end; function TBaseTable.GetFooter: TBaseTableCells; begin Result := Rows[RowCount - 1]; end; function TBaseTable.GetHeader: TBaseTableCells; begin Result := Rows[0]; end; function TBaseTable.GetRowCount: integer; begin Result := Rows.Count; end; function TBaseTable.GetRows: TBaseTableCellsGroup; begin if not Assigned(FRows) then FRows := TBaseTableCellsGroup.Create; Result := FRows; end; procedure TBaseTable.LoadFromFile(AFileName: string); begin if CheckPreconditions then begin OpenFile(AFileName); LoadRows; end; end; procedure TBaseTable.LoadRows; var i: integer; begin for i := 0 to Rows.Count - 1 do CheckCellsEmpty(Rows[i]); for i := 0 to Columns.Count - 1 do CheckCellsEmpty(Columns[i]); end; procedure TBaseTable.OpenFile(AFileName: string); begin end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, IniFiles; type TMainForm = class(TForm) bbtProjects: TBitBtn; bbtSource: TBitBtn; bbtExit: TBitBtn; procedure bbtExitClick(Sender: TObject); procedure bbtProjectsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure bbtSourceClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses projects, login, sourcelist, glbVar; procedure TMainForm.bbtExitClick(Sender: TObject); begin Self.Close; end; procedure TMainForm.bbtProjectsClick(Sender: TObject); begin frmProjects.Show; end; procedure TMainForm.bbtSourceClick(Sender: TObject); begin frmSourceList.Show; frmSourceList.btnInclude.Enabled := false; end; procedure TMainForm.FormCreate(Sender: TObject); var ini: TIniFile; pathIni : string; begin // Загрузать все настройки при создании pathIni := GetCurrentDir + '\Settigns.ini'; ini := TIniFile.Create(pathIni); rootDir := ini.ReadString('Common', 'rootDir', 'E:'); blDeleteFileAfterCopy := ini.ReadBool('Common', 'delAfterCopy', False); currentTypeConnection := ini.ReadBool('Connection', 'typeConnection', false); // по умолчанию локальный хост end; procedure TMainForm.FormShow(Sender: TObject); begin // Определение положения формы на экране MainForm.Top := 0; MainForm.left := Screen.Width - MainForm.Width; frmLogin.Show; end; end.
unit VisibleDSA.MonteCarloExperiment; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Types, VisibleDSA.Circle, VisibleDSA.MonteCarloPiData; type TMonteCarloExperiment = class private _squareSide: integer; _count: integer; _outputInterval: integer; public constructor Create(squareSide, n: integer); destructor Destroy; override; procedure Run; procedure SetOutputInterval(interval: integer); end; implementation { TMonteCarloExperiment } constructor TMonteCarloExperiment.Create(squareSide, n: integer); begin if (squareSide <= 0) or (n <= 0) then raise Exception.Create('SquareSide and N must larger than zero!'); _squareSide := squareSide; _count := n; _outputInterval := 100; end; destructor TMonteCarloExperiment.Destroy; begin inherited Destroy; end; procedure TMonteCarloExperiment.Run; var Circle: TCircle; Data: TMonteCarloPiData; i: integer; p: TPoint; begin Circle := TCircle.Create(_squareSide div 2, _squareSide div 2, _squareSide div 2); Data := TMonteCarloPiData.Create(Circle); Randomize; for i := 0 to _count - 1 do begin if (i mod _outputInterval = 0) then Writeln(FloatToStr(Data.EstimatePI)); p := TPoint.Create(Random(_squareSide), Random(_squareSide)); Data.AddPoint(p); end; end; procedure TMonteCarloExperiment.SetOutputInterval(interval: integer); begin if (interval <= 0) then raise Exception.Create('interval must be larger than zero'); _outputInterval := interval; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [PCP_SERVICO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit PcpServicoController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, Generics.Collections, PcpServicoVO; type TPcpServicoController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TPcpServicoVO>; class function ConsultaObjeto(pFiltro: String): TPcpServicoVO; class procedure Insere(pObjeto: TPcpServicoVO); class function Altera(pObjeto: TPcpServicoVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses UDataModule, T2TiORM; class procedure TPcpServicoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TPcpServicoVO>; begin try Retorno := TT2TiORM.Consultar<TPcpServicoVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TPcpServicoVO>(Retorno); finally end; end; class function TPcpServicoController.ConsultaLista(pFiltro: String): TObjectList<TPcpServicoVO>; begin try Result := TT2TiORM.Consultar<TPcpServicoVO>(pFiltro, '-1', True); finally end; end; class function TPcpServicoController.ConsultaObjeto(pFiltro: String): TPcpServicoVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TPcpServicoVO>(pFiltro, True); finally end; end; class procedure TPcpServicoController.Insere(pObjeto: TPcpServicoVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TPcpServicoController.Altera(pObjeto: TPcpServicoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TPcpServicoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TPcpServicoVO; begin try ObjetoLocal := TPcpServicoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); TratarRetorno(Result); finally FreeAndNil(ObjetoLocal) end; end; class function TPcpServicoController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TPcpServicoController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TPcpServicoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TPcpServicoVO>(TObjectList<TPcpServicoVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TPcpServicoController); finalization Classes.UnRegisterClass(TPcpServicoController); end.
unit davecad_file; {$mode objfpc}{$H+} //{$R newFile.rc} interface uses Classes, SysUtils, davecad_enum, {$IFDEF XMLVersionLaz2} laz2_XMLRead, laz2_XMLWrite, laz2_DOM, {$ELSE} XMLRead, XMLWrite, DOM, {$endif} davecad_error, davecad_file_parser, dialogs, LResources, davecad_renderer; type TDaveCadFileErrorCallback = procedure (E: EXMLReadError); TDaveCADFileSession = record SelectedSheet: string; scale: double; translateX, translateY: integer; end; TDaveCadFile = class(TObject) private fFileName: string; fFileValid: boolean; fFile: TXMLDocument; fModified: boolean; fECallback: TDaveCadFileErrorCallback; procedure XMLErrorHandler(E: EXMLReadError); procedure modify; public Session: TDaveCADFileSession; //function for loading DaveCAD files function loadFile(fileName: string): integer; //function for closing the currently loaded DaveCAD file procedure closeFile; //This function will save the file if it can and return false, otherwise it will return true function save:boolean; //This turns this file into a new file procedure new; //This function gives a new file a name, it will fail if the file name is already set procedure newFileName(name: string); //function for getting validity function isValid: boolean; //find a sheet function getSheet(name_s:string): TDOMNode; //functions for adding things to the file, editting or removing them procedure addSheet(name_s: string; media_s: string; author_s: string; date_s: string); function deleteSheet(name_s: string): integer; procedure updateSheetProps(sheet: TDOMElement; newname, newAuthor, newDate, newMedia: string); procedure addObject(objType, sheetName, tool, colour: string; originX, originY, lastX, lastY: integer; origin: TPoint); procedure addObject(objType, sheetName, tool, colour: string; originX, originY, lastX, lastY: integer; origin: TPoint; text: string); overload; //function deleteObject(sheetName: string; objectID: integer): integer; //procedure updateObjectProps(sheet: string; objectID: integer; new...: string); //functions for getting info from the file function getDOM:TXMLDocument; //Gets everything function hasSheets:boolean; function getSheets:TDaveCADSheetList; //some stuff, the usual. constructor create; constructor create(E: TDaveCadFileErrorCallback); //adds callback too destructor destroy; override; property IsModified: boolean read fModified; property fileName: string read fFileNAme; end; const FileSaveVersionNumber: string = '0.1'; implementation procedure TDaveCadFile.modify; begin fModified:=true; end; constructor TDaveCadFile.create; begin inherited create; //just some inits... fFileName := ''; fFileValid := false; fModified:=false; session.scale:=1; session.translateX:=0; session.translateY:=0; end; constructor TDaveCadFile.create (E: TDaveCadFileErrorCallback); begin //another init... create; fEcallback := E; end; destructor TDaveCadFile.destroy; begin //make sure everything is free try closeFile; finally end; inherited destroy; end; procedure TDaveCadFile.XMLErrorHandler(E: EXMLReadError); begin if (E.Severity = esError) or (E.Severity = esFatal) then fFileValid := false; //There was an error, file is no longer valid if not(fECallback = nil) then //if there is another handler that wants to know fECallback(E); //let them! end; function TDaveCadFile.loadFile(fileName: string): integer; var Parser: TDOMParser; Src: TXMLInputSource; Input: TFileStream; sheetList: TDaveCadSheetList; begin //store the file name fFileName := fileName; if fileExists(fFileName) then begin try fFileValid := true; // create a parser object Parser := TDOMParser.Create; // get the actual file from disk Input := TFileStream.Create(fileName, fmOpenRead); // create the input source Src := TXMLInputSource.Create(Input); // we want validation Parser.Options.Validate := True; // assign a error handler which will receive notifications Parser.OnError := @XMLErrorHandler; // now do the job Parser.Parse(Src, fFile); except end; Input.free; Parser.Free; Src.Free; end else begin result := DCAD_ERROR_FILE_NOT_FOUND; fFileValid := false; end; sheetList := getSheets; if sheetList.count >= 1 then begin session.SelectedSheet:=sheetList.Item[0].Name; end; sheetList.Free; end; function TDaveCadFile.isValid: boolean; begin result := fFileValid; end; procedure TDaveCadFile.closeFile; begin //reset to new state fFileValid := false; fFileName := ''; try fFile.Free; except end; end; function TDaveCadFile.save:boolean; begin result:=true; if (not (ffileName = ''))and fFileValid then begin writeXMLFile(fFile, fFileName); fModified:=false; result:= false; end; end; procedure TDaveCadFile.new; var Parser: TDOMParser; Src: TXMLInputSource; InputS: TResourceStream; begin closeFile; try fFileValid := true; // create a parser object Parser := TDOMParser.Create; // get the data for a blank file InputS := TResourceStream.Create(HInstance, 'newFile', PChar(10));//is PChar(10) dodgy???? // create the input source Src := TXMLInputSource.Create(InputS); // we want validation Parser.Options.Validate := True; // assign a error handler which will receive notifications Parser.OnError := @XMLErrorHandler; // now do the job Parser.Parse(Src, fFile); except end; InputS.free; Parser.Free; Src.Free; session.SelectedSheet:='sheet1'; fFileValid:=true; modify; end; procedure TDaveCadFile.newFileName(name: string); begin fFileName:=name; modify; end; //This function adds a sheet to the currently loaded file. procedure TDaveCadFile.addSheet(name_s: string; media_s: string; author_s: string; date_s: string); var sheet, properties, objects, name, media, author, date: TDOMElement; name_data, media_data, author_data, date_data: TDOMText; begin //make a new sheet sheet := fFile.CreateElement('sheet'); //give the sheet some properties properties := fFile.CreateElement('properties'); sheet.AppendChild(properties); name := fFile.CreateElement('property'); name.SetAttribute('name', 'sheet-name'); media := fFile.CreateElement('property'); media.SetAttribute('name', 'media'); author := fFile.CreateElement('property'); author.SetAttribute('name', 'author'); date := fFile.CreateElement('property'); date.SetAttribute('name', 'date'); properties.AppendChild(name); properties.AppendChild(media); properties.AppendChild(author); properties.AppendChild(date); name_data := (fFile.CreateTextNode(name_s)); media_data := (fFile.CreateTextNode(media_s)); author_data := (fFile.CreateTextNode(author_s)); date_data := (fFile.CreateTextNode(date_s)); name.AppendChild(name_data); media.AppendChild(media_data); author.AppendChild(author_data); date.AppendChild(date_data); //Add the objects section objects := fFile.CreateElement('objects'); sheet.AppendChild(objects); fFile.DocumentElement.AppendChild(sheet); modify; end; //This function adds a sheet to the currently loaded file. procedure TDaveCadFile.addObject(objType, sheetName, tool, colour: string; originX, originY, lastX, lastY: integer; origin: TPoint); var sheet, dcObject, objects: TDOMElement; objectsnode: TDOMNode; begin addObject(objType, sheetName, tool, colour, originX, originY, lastX, lastY, origin, ''); end; //This function adds a sheet to the currently loaded file. procedure TDaveCadFile.addObject(objType, sheetName, tool, colour: string; originX, originY, lastX, lastY: integer; origin: TPoint; text: string); var sheet, dcObject, objects: TDOMElement; objectsnode: TDOMNode; begin //find the sheet sheet := TDOMElement(getSheet(sheetName)); dcObject := fFile.CreateElement('object'); dcObject.SetAttribute('tool', tool); if colour <> '' then dcObject.SetAttribute('colour', colour); dcObject.SetAttribute('top', inttostr(round((originY-origin.y)/session.scale))); dcObject.SetAttribute('left', inttostr(round((originX-origin.x)/session.scale))); dcObject.SetAttribute('top1', inttostr(round((lastY-origin.y)/session.scale))); dcObject.SetAttribute('left1', inttostr(round((lastX-origin.x)/session.scale))); if text <> '' then dcObject.SetAttribute('text', text); dcObject.AppendChild(fFile.CreateTextNode(objType)); objectsNode := sheet.FindNode('objects'); objects := TDOMElement(objectsNode); objects.AppendChild(dcObject); modify; end; function TDaveCadFile.getSheet(name_s:string): TDOMNode; var sheets: TDOMNodeList; sheet: TDaveCADSheet; i : integer; found : boolean; begin sheets := fFile.GetElementsByTagName('sheet'); for i := 0 to sheets.Count-1 do begin sheet := TDaveCADSheet.create; sheet.loadFrom(TDOMElement(sheets.Item[i])); found := sheet.Name = name_s; sheet.Free; if found then //we have our guy begin result := sheets.Item[i]; break; end; end; sheets.Free; if not found then result := nil; end; function TDaveCadFile.deleteSheet(name_s:string): integer; var{ sheets: TDOMNodeList; sheet: TDaveCADSheet; i : integer; found : boolean; } sheet: TDOMNode; begin sheet := getSheet(name_s); if sheet <> nil then begin fFile.DocumentElement.RemoveChild(sheet); result := 0; end else begin result := DCAD_WARN_INVALID_SHEET_SELECTED; end; { sheets := fFile.GetElementsByTagName('sheet'); for i := 0 to sheets.Count-1 do begin sheet := TDaveCADSheet.create; sheet.loadFrom(TDOMElement(sheets.Item[i])); found := sheet.Name = name_s; sheet.Free; if found then //we have our guy begin fFile.DocumentElement.RemoveChild(sheets.Item[i]); result:= 0; break; end; end; sheets.Free; if not found then result := DCAD_WARN_INVALID_SHEET_SELECTED; } end; procedure TDaveCadFile.updateSheetProps(sheet: TDOMElement; newname, newAuthor, newDate, newMedia: string); var properties: TDOMNodeList; i: integer; ThisProp: TDOMElement; begin properties := TDOMElement(sheet.FindNode('properties')).GetElementsByTagName('property'); for i := 0 to properties.Count-1 do begin ThisProp := TDOMElement(properties.Item[i]); if ThisProp.GetAttribute('name') = 'sheet-name' then ThisProp.ReplaceChild(fFile.CreateTextNode(newName), ThisProp.FirstChild); if ThisProp.GetAttribute('name') = 'author' then ThisProp.ReplaceChild(fFile.CreateTextNode(newAuthor), ThisProp.FirstChild); if ThisProp.GetAttribute('name') = 'media' then ThisProp.ReplaceChild(fFile.CreateTextNode(newMedia), ThisProp.FirstChild); if ThisProp.GetAttribute('name') = 'date' then ThisProp.ReplaceChild(fFile.CreateTextNode(newDate), ThisProp.FirstChild); end; modify; properties.Free; //ThisProp.Free; end; function TDaveCadFile.getDOM:TXMLDocument; begin result := fFile; end; function TDaveCadFile.hasSheets:boolean; var sheets: TDOMNodeList; begin sheets := fFile.GetElementsByTagName('sheet'); result := sheets.Count >= 1; sheets.Free; end; function TDaveCadFile.getSheets:TDaveCADSheetList; var sheets: TDOMNodeList; sheet: TDaveCADSheet; i: integer; begin sheets := fFile.GetElementsByTagName('sheet'); if sheets.Count<=0 then begin result := nil; end else begin result := TDaveCADSheetList.Create; for i := 0 to sheets.Count-1 do begin sheet := TDaveCADSheet.create; sheet.loadFrom(TDOMElement(sheets.Item[i])); result.add(sheet); sheet.free; end; end; sheets.free; end; end.
unit Minerva.Treinamento.ImpressaoEtiqueta; interface uses Minerva.Treinamento.Etiqueta, System.SysUtils, System.Classes, System.Generics.Collections; type TImprimirRegEvent = procedure(const pTexto: TStringList; const pEtiqueta: TEtiqueta) of object; TProcImprimirReg = reference to procedure(const pTexto: TStringList; const pEtiqueta: TEtiqueta); TProcImprimirFinal = reference to procedure(const pTexto: TStringList); TImpressaoDeEtiquetas = class private FListaEtiqueta: TObjectList<TEtiqueta>; public constructor Create; destructor Destroy; override; procedure Add(pEtiqueta: TEtiqueta); function Imprimir: string; overload; function Imprimir(pImprimirRegEvent: TImprimirRegEvent): string; overload; function Imprimir(pProcImprimirReg: TProcImprimirReg; pProcImprimirFinal: TProcImprimirFinal = nil): string; overload; end; implementation { TImpressaoDeEtiquetas } procedure TImpressaoDeEtiquetas.Add(pEtiqueta: TEtiqueta); begin FListaEtiqueta.Add(pEtiqueta); end; constructor TImpressaoDeEtiquetas.Create; begin FListaEtiqueta := TObjectList<TEtiqueta>.Create; end; destructor TImpressaoDeEtiquetas.Destroy; begin FListaEtiqueta.Free; inherited; end; function TImpressaoDeEtiquetas.Imprimir( pProcImprimirReg: TProcImprimirReg; pProcImprimirFinal: TProcImprimirFinal): string; var lTexto: TStringList; lEtiqueta: TEtiqueta; begin lTexto := TStringList.Create; try for lEtiqueta in FListaEtiqueta do begin if Assigned(pProcImprimirReg) then pProcImprimirReg(lTexto,lEtiqueta); end; if Assigned(pProcImprimirFinal) then pProcImprimirFinal(lTexto); Result := lTexto.Text; finally lTexto.Free; end; end; function TImpressaoDeEtiquetas.Imprimir( pImprimirRegEvent: TImprimirRegEvent): string; var lTexto: TStringList; lEtiqueta: TEtiqueta; begin lTexto := TStringList.Create; try for lEtiqueta in FListaEtiqueta do begin if Assigned(pImprimirRegEvent) then pImprimirRegEvent(lTexto,lEtiqueta); end; Result := lTexto.Text; finally lTexto.Free; end; end; function TImpressaoDeEtiquetas.Imprimir: string; var lTexto: TStringList; lEtiqueta: TEtiqueta; begin lTexto := TStringList.Create; try for lEtiqueta in FListaEtiqueta do begin lTexto.Add('Codigo: '+lEtiqueta.Codigo.ToString); lTexto.Add('Item: '+lEtiqueta.DescItem); lTexto.Add('Peso: '+FormatFloat('0.,00',lEtiqueta.Peso)+'KG'); lTexto.Add(''); end; Result := lTexto.Text; finally lTexto.Free; end; end; end.
{ *************************************************** PSPdisp (c) 2008 - 2015 Jochen Schleu display.pas - dealing with the display API This software is licensed under the BSD license. See license.txt for details. *************************************************** } unit display; interface uses Windows, Dialogs, SysUtils; var CurrentDeviceNumber: Integer; CurrentDeviceName: String; CurrentDeviceString: String; PSPdispDriverPosition: TPoint; PSPdispDriverSize: TPoint; function DispGetNumberOfDevices: Integer; function DispChangeResolution(DeviceNumber: Integer; Width: Integer; Height: Integer): Boolean; function DispSetDisplayEnabledState(DeviceNumber: Integer; Enable: Boolean): Boolean; function DispGetDisplayEnabledState(DeviceNumber: Integer): Boolean; function DispSetPosition(DeviceNumber: Integer; PositionX: Integer; PositionY: Integer): Boolean; function DispGetPosition(DeviceNumber: Integer; var PositionX: Integer; var PositionY: Integer): Boolean; procedure DispGetInformation(DeviceNumber: Integer; var Size: TPoint; var DeviceString: String; var DeviceName: String); function DispGetDeviceNumber: Integer; function DispEnumerateResolution(DeviceNumber: Integer; ModeNumber: Integer; var Width: Integer; var Height: Integer): Boolean; function DispHasScreenChanged: Boolean; function DispGetDeviceContainingPoint(Point: TPoint): Integer; procedure DispSwitchDesktopCompositionState(Enable: Boolean); implementation const // For some reason those are not defined in Turbo Delphi 2006 ENUM_CURRENT_SETTINGS = DWORD(-1); ENUM_REGISTRY_SETTINGS = DWORD(-2); DISPLAY_DEVICE_ATTACHED_TO_DESKTOP = 1; // This has to match the device name in the display driver DRIVER_NAME = 'PSPdisp Display Driver'; DRIVER_NAME_VISTA = 'PSPdisp Display Driver (Vista)'; // Custom escape command for checking if the screen content // has changed, must match the definition in the display driver ESCAPE_IS_DIRTY = ($10000 + 100); type // TDevMode declaration in windows.pas // is only for printer devices TDevModeMonitor = packed record dmDeviceName: array[0..CCHDEVICENAME - 1] of AnsiChar; dmSpecVersion: Word; dmDriverVersion: Word; dmSize: Word; dmDriverExtra: Word; dmFields: DWORD; // this is different from the windows.pas declaration dmPosition: TPoint; dmDisplayOrientation: DWORD; dmDisplayFixedOutput: DWORD; dmColor: SHORT; dmDuplex: SHORT; dmYResolution: SHORT; dmTTOption: SHORT; dmCollate: SHORT; dmFormName: array[0..CCHFORMNAME - 1] of AnsiChar; dmLogPixels: Word; dmBitsPerPel: DWORD; dmPelsWidth: DWORD; dmPelsHeight: DWORD; dmDisplayFlags: DWORD; dmDisplayFrequency: DWORD; dmICMMethod: DWORD; dmICMIntent: DWORD; dmMediaType: DWORD; dmDitherType: DWORD; dmICCManufacturer: DWORD; dmICCModel: DWORD; dmPanningWidth: DWORD; dmPanningHeight: DWORD; end; type DWMAPI_DwmEnableComposition = function(uCompositionAction: DWORD): HRESULT; stdcall; var DwmEnableComposition: DWMAPI_DwmEnableComposition; { DispSwitchDesktopCompositionState --------------------------------------------------- Enable or disable the Aero desktop composition. --------------------------------------------------- } procedure DispSwitchDesktopCompositionState(Enable: Boolean); const DWM_EC_DISABLECOMPOSITION = 0; DWM_EC_ENABLECOMPOSITION = 1; var DWMLibrary: THandle; begin DWMlibrary := LoadLibrary('DWMAPI.dll'); DwmEnableComposition := GetProcAddress(DWMLibrary, 'DwmEnableComposition'); if DWMlibrary <> 0 then begin if @DwmEnableComposition <> nil then begin if Enable then DwmEnableComposition(DWM_EC_ENABLECOMPOSITION) else DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); end; end; FreeLibrary(DWMLibrary); DwmEnableComposition := nil; end; { DispGetDeviceContainingPoint --------------------------------------------------- Retrieve the graphics device on which the given point lies. --------------------------------------------------- Returns device index. } function DispGetDeviceContainingPoint(Point: TPoint): Integer; var i: Integer; DeviceName: String; DeviceString: String; Size: TPoint; PositionX: Integer; PositionY: Integer; begin for i := 0 to DispGetNumberOfDevices - 1 do begin DispGetInformation(i, Size, DeviceString, DeviceName); if DispGetDisplayEnabledState(i) and (Size.X > 0) and (Size.Y > 0) then begin DispGetPosition(i, PositionX, PositionY); if (Point.X >= PositionX) and (Point.X < PositionX + Size.X) and (Point.Y >= PositionY) and (Point.Y < PositionY + Size.Y) then begin // Point lies on the devices screen Result := i; Exit; end; end; end; Result := -1; end; { DispHasScreenChanged --------------------------------------------------- Check if the screen content has changed. --------------------------------------------------- Returns False if the PSPdisp display screen has not changed, in any other case it returns True. } function DispHasScreenChanged: Boolean; var ReturnValue: Integer; Handle: HDC; begin if ((CurrentDeviceName = DRIVER_NAME) or (CurrentDeviceName = DRIVER_NAME_VISTA)) then begin ReturnValue := 99; Handle := CreateDC('DISPLAY', PAnsiChar(CurrentDeviceString), nil, nil); if (Handle > 0) then begin ExtEscape(Handle, ESCAPE_IS_DIRTY, 0, nil, 4, PAnsiChar(@ReturnValue)); DeleteDC(Handle); end; Result := (ReturnValue <> 0); end else Result := True; end; { DispGetNumberOfDevices --------------------------------------------------- Get the number of display devices. --------------------------------------------------- Returns the number of devices. } function DispGetNumberOfDevices: Integer; var DevNum: Cardinal; DisplayDevice: TDisplayDevice; begin DevNum := 0; ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); // search for the display while EnumDisplayDevices(nil, DevNum, DisplayDevice, 0) do Inc(DevNum); Result := DevNum; end; { DispSetPosition --------------------------------------------------- Change the position of the specified display. --------------------------------------------------- Returns True on success. } function DispSetPosition(DeviceNumber: Integer; PositionX: Integer; PositionY: Integer): Boolean; var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; begin DevNum := DispGetDeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); // device is present, get position info ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_REGISTRY_SETTINGS, TDevMode(DevMode)); DevMode.dmPosition.X := PositionX; DevMode.dmPosition.Y := PositionY; DevMode.dmFields := (DM_POSITION); ChangeDisplaySettingsEx(DisplayDevice.DeviceName, TDevMode(DevMode), 0, CDS_UPDATEREGISTRY, nil); Result := True; end else begin Result := False; end; end; { DispSetDisplayEnabledState --------------------------------------------------- Enable or disable the display driver as well as attaching to and detach it from the desktop. Look here for C code to attach / detach a display: MS Knowledge Base article 306399 --------------------------------------------------- Return False if the driver is not installed. } function DispSetDisplayEnabledState(DeviceNumber: Integer; Enable: Boolean): Boolean; var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; Res: Integer; begin DevNum := DispGetDeviceNumber; if DevNum > -1 then begin DispSwitchDesktopCompositionState(not Enable); ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); // device is present, get position info ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_REGISTRY_SETTINGS, TDevMode(DevMode)); // enabling a display device: // - set width and height to a valid value or // just use the one stored in DevMode // - position doesn't need to be set, it's last value is retrieved // from the registry // disabling a display device: // - set width and height to 0 if Enable then begin if ((DevMode.dmPelsWidth = 0) or (DevMode.dmPelsHeight = 0)) then begin DevMode.dmPelsWidth := 480; DevMode.dmPelsHeight := 272; end; end else begin DevMode.dmPelsWidth := 0; DevMode.dmPelsHeight := 0; end; DevMode.dmFields := (DM_PELSWIDTH or DM_PELSHEIGHT or DM_POSITION); Res := ChangeDisplaySettingsEx(DisplayDevice.DeviceName, TDevMode(DevMode), 0, CDS_UPDATEREGISTRY, nil); Result := (Res = DISP_CHANGE_SUCCESSFUL); end else begin Result := False; end; end; { DispGetDisplayEnabledState --------------------------------------------------- Determine wether the display is currently attached to the desktop. --------------------------------------------------- Return True if it is and False if not. } function DispGetDisplayEnabledState(DeviceNumber: Integer): Boolean; var DevNum: Integer; DisplayDevice: _DISPLAY_DEVICEA; DevMode: TDevModeMonitor; begin DevNum := DeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_REGISTRY_SETTINGS, TDevMode(DevMode)); // Report mirror drivers as not attached Result := (DisplayDevice.StateFlags and DISPLAY_DEVICE_ATTACHED_TO_DESKTOP > 0) and not (DisplayDevice.StateFlags and DISPLAY_DEVICE_MIRRORING_DRIVER > 0); end else begin Result := False; end; end; { DispGetDeviceNumber --------------------------------------------------- Get the index of the PSPdisp display device. --------------------------------------------------- Returns the device index. } function DispGetDeviceNumber: Integer; var DevNum: Cardinal; DisplayDevice: TDisplayDevice; begin DevNum := 0; ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); // search for the display while EnumDisplayDevices(nil, DevNum, DisplayDevice, 0) do begin if (((DisplayDevice.DeviceString = DRIVER_NAME) or (DisplayDevice.DeviceString = DRIVER_NAME_VISTA)) and not (DisplayDevice.StateFlags and DISPLAY_DEVICE_MIRRORING_DRIVER > 0)) then begin Result := DevNum; Exit; end; Inc(DevNum); end; Result := -1; end; { DispGetPosition --------------------------------------------------- Get the desktop position of the attached display. --------------------------------------------------- Return False if the driver is not installed. } function DispGetPosition(DeviceNumber: Integer; var PositionX: Integer; var PositionY: Integer): Boolean; var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; begin DevNum := DeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_CURRENT_SETTINGS, TDevMode(DevMode)); PositionX := DevMode.dmPosition.x; PositionY := DevMode.dmPosition.y; Result := True; end else begin PositionX := 0; PositionY := 0; Result := False; end; end; { DispGetInformation --------------------------------------------------- Retrieves the current display mode and display adapter name. --------------------------------------------------- } procedure DispGetInformation(DeviceNumber: Integer; var Size: TPoint; var DeviceString: String; var DeviceName: String); var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; begin DevNum := DeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); // For some reason ENUM_CURRENT_SETTINGS works on Windows 7 RC // while ENUM_REGISTRY_SETTINGS seems to always report (0,0) for size // on 64 bit systems and at the first start on 32 bit systems EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_CURRENT_SETTINGS, TDevMode(DevMode)); Size.X := DevMode.dmPelsWidth; Size.Y := DevMode.dmPelsHeight; DeviceName := DisplayDevice.DeviceName; DeviceString := DisplayDevice.DeviceString; end else begin Size.X := 0; Size.Y := 0; DeviceName := ''; DeviceString := ''; end; end; { DispChangeResolution --------------------------------------------------- Changes the display mode. --------------------------------------------------- Returns True on success. } function DispChangeResolution(DeviceNumber: Integer; Width: Integer; Height: Integer): Boolean; var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; ReturnedValue: Integer; begin DevNum := DeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); EnumDisplaySettings(DisplayDevice.DeviceName, ENUM_REGISTRY_SETTINGS, TDevMode(DevMode)); DevMode.dmPelsWidth := Width; DevMode.dmPelsHeight := Height; DevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; ReturnedValue := ChangeDisplaySettingsEx(DisplayDevice.DeviceName, TDevMode(DevMode), 0, CDS_UPDATEREGISTRY, nil); Result := (ReturnedValue = DISP_CHANGE_SUCCESSFUL); end else begin Result := False; end; end; { DispEnumerateResolution --------------------------------------------------- Retrieves information about the specified display mode. --------------------------------------------------- Returns True on success. } function DispEnumerateResolution(DeviceNumber: Integer; ModeNumber: Integer; var Width: Integer; var Height: Integer): Boolean; var DevNum: Integer; DisplayDevice: TDisplayDevice; DevMode: TDevModeMonitor; ReturnedValue: Boolean; begin DevNum := DeviceNumber; if DevNum > -1 then begin ZeroMemory(@DisplayDevice, sizeof(DisplayDevice)); DisplayDevice.cb := sizeof(DisplayDevice); EnumDisplayDevices(nil, DevNum, DisplayDevice, 0); ZeroMemory(@DevMode, sizeof(TDevModeMonitor)); DevMode.dmSize := sizeof(TDevModeMonitor); DevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; ReturnedValue := EnumDisplaySettings(DisplayDevice.DeviceName, ModeNumber, TDevMode(DevMode)); if (ReturnedValue) then begin Width := DevMode.dmPelsWidth; Height := DevMode.dmPelsHeight; end else begin Width := 0; Height := 0; end; Result := ReturnedValue; end else begin Result := False; end; end; end.
program creare_puzzle_v2; uses SysUtils; { has the function FileExists } const max_n = 100; { dimensiunea maxima a matrici } max_m = 100; { numarul maxim de cuvinte } max_dir = 8; { numarul de directii } { version information } version = '2.2.0'; autor = 'Micu Matei-Marius'; git = 'https://github.com/micumatei/generate-char-puzzle'; gmail = 'micumatei@gmail.com'; licenta = 'The MIT License (MIT)'; type vector_bool = array[1..255] of boolean; vector_int = array[1..8] of integer; matrice_c = array[1..max_n, 1..max_n] of char; cuvant = record st :string; len, poz_l, poz_c, dir :integer; vec_poz :vector_bool; end; vector_cuv = array[1..max_m] of cuvant; var vec_c :vector_cuv; mat :matrice_c; d_vec_poz, d_vec_undo, d_vec_poz_reusite :vector_int; nr_cuv, nr_n, len_max, d_nr_poz, d_nr_poz_reusite, d_nr_undo, d_nr_rec :integer; rez :boolean; { ====================================================== } { Initializare si DebugHelpers } { initializam programul } procedure init_program; var i :integer; begin { initializam vectori care vor contine cate pozitionari si undouri am facut } for i := 1 to 8 do begin d_vec_poz[i] := 0; d_vec_undo[i] := 0; d_vec_poz_reusite[i] := 0; end; d_nr_poz := 0; { nr total de pozitionari } d_nr_undo := 0; { nr total de undouri } d_nr_rec := 0; { nr total de recursivitati } nr_n := 0; nr_cuv := 0; end; procedure inc_poz(i :integer); { numaram o pozitionare } begin inc(d_vec_poz[i]); end; procedure inc_poz_reusita(i :integer); { numaram o pozitionare reusita } begin inc(d_vec_poz_reusite[i]); end; procedure inc_undo(i :integer); { numaram un undoing } begin inc(d_vec_undo[i]); end; procedure inc_nr_rec; { incrementam numarur de recursiuni } begin inc(d_nr_rec); end; { ====================================================== } { proceduri legate de matrice } { initializam matricea } procedure init_mat(var m:matrice_c; n:integer); var i, j :integer; begin for i := 1 to n do for j := 1 to n do m[i, j] := '-'; end; { afisarea matrici } procedure afis_mat(var m :matrice_c; n:integer); var i, j :integer; begin for i := 1 to n do begin for j := 1 to n do write(mat[i, j]:3, ' '); writeln; end; writeln; end; { ====================================================== } { procedures related to data structure <cuvant> } { construim cuvantul } procedure construct_cuv(var c :cuvant); begin with c do begin poz_l := 0; { pozitia de start } poz_c := 0; { pozitia de finish } dir := 0; { directia } fillbyte(vec_poz, sizeof(vec_poz), 0); { initializam vectorul cu FALSE } end; end; { initializam cuvantul } procedure init_cuv(var c :cuvant; s :string); begin construct_cuv(c); { construim cuvantul } with c do begin st := s; { atribuim stringul } len := length(s); { atribuim lungimea } fillbyte(vec_poz, sizeof(vec_poz), 0); { initializam vectorul cu FALSE } end; end; { stergem cuvantul din matrice stiind ca a fost scris spre dreapta } procedure undo_cuv_1(var c :cuvant); { stergem cuvantul stiind ca e scris spre dreapta } var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera de pe pozitia <i> a fost pusa } mat[poz_l, poz_c + i - 1] := '-'; { eliminam din matrice litera } end; { reinitializam cuvantul } init_cuv(c, c.st); end; { stergem cuvantul din matrice stiind ca a fost scris spre dreapta jos, diagonala principala spre dreapta } procedure undo_cuv_2(var c :cuvant); { stergem cuvantul stiind ca e scris spre dreapta } var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera de pe pozitia <i> a fost pusa } mat[poz_l + i - 1, poz_c + i - 1] := '-'; { eliminam din matrice litera } end; { reinitializam cuvantul } init_cuv(c, c.st); end; { stergem cuvantul din matrice stiind ca a fost scris in jos } procedure undo_cuv_3(var c :cuvant); { stergem cuvantul stiind ca e scris spre dreapta } var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera de pe pozitia <i> a fost pusa } mat[poz_l + i -1, poz_c] := '-'; { eliminam din matrice litera } end; { reinitializam cuvantul } init_cuv(c, c.st); end; { stergem cuvantul din matrice stiind ca a fost scris pe diagonala secundara in spre stanga } procedure undo_cuv_4(var c :cuvant); var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera a fost pozitionata intr-un loc gol } mat[poz_l+i-1, poz_c-i+1] := '-'; { eliminam litera din matrice } end; end; { stergem cuvantul din matrice stiind ca a fost scris spre stanga } procedure undo_cuv_5(var c :cuvant); var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca caracterul a fost pozitionat intr-un loc gol } mat[poz_l, poz_c-i+1] := '-'; { eliminam litera } end; end; { stergem cuvantul stiind ca a fost pozitionat pe diagonala principala spre stanga } procedure undo_cuv_6(var c :cuvant); var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca caracteruk <i> a fost pozitionat intr-un loc gol } mat[poz_l-i+1, poz_c-i+1] := '-'; { eliminam litera } end; end; { stergem cuvantul stiind ca a fost pozitionat in sus } procedure undo_cuv_7(var c :cuvant); var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera a fost introdusa } mat[poz_l-i+1, poz_c] := '-'; { eliminam litera } end; end; { stergem cuvantul stiind ca a fost pozitionat in dreapta sus } procedure undo_cuv_8(var c :cuvant); var i :integer; begin with c do begin for i := 1 to len do if vec_poz[i] then { daca litera a fost introdusa } mat[poz_l-i+1, poz_c+i-1] := '-'; { eliminam litera } end; end; procedure handle_undo_cuv(var c :cuvant); begin case c.dir of 1: begin { daca cuvantul a fost scris spre dreapta } undo_cuv_1(c); end; 2: begin { daca cuvantul a fost scris spre dreapta jos } undo_cuv_2(c); end; 3: begin { daca cuvantul a fost scris in jos} undo_cuv_3(c); end; 4: begin { daca cuvantul a fost scris in stanga jos} undo_cuv_4(c); end; 5: begin { daca cuvantul a fost scris in stanga } undo_cuv_5(c); end; 6: begin { daca cuvantul a fost scris stanga sus } undo_cuv_6(c); end; 7: begin { daca cuvantul a fost scris in sus } undo_cuv_7(c); end; 8: begin { daca cuvantul a scrids in dreapta sus } undo_cuv_8(c); end; end; { DebugHelp } inc_undo(c.dir); { numaram scoaterea din matrice } { EndDebugHelp } { reinitializam cuvantul } construct_cuv(c); end; { afisam informatii despre cuvant } procedure afis_cuv(var c :cuvant); var i :integer; begin with c do begin writeln('st = ', st); writeln('poz_lin = ', poz_l); writeln('poz_col= ', poz_c); writeln('len = ', len); writeln('DIr =', dir); for i := 1 to len do write(vec_poz[i], ' '); writeln; end; end; { ====================================================== } { pozitionam un cuvant } { pozitionam spre dreapta pornind din pozitia <i>, <j> } function poz_cuv_1(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_1 := true; { consideram ca il putem pozitiona } with c do begin if (col + len - 1) <= nr_n then { avem loc spre dreapta } begin for i := 1 to len do { parcurgem fiecare litera } if mat[lin, col + i -1] = '-' then { daca locul e gol } begin vec_poz[i] := true; { marcam litera ca pusa intr-un loc gol } mat[lin, col + i - 1] := st[i]; end else { exista deja o litera pe aceasta pozitie } if mat[lin, col +i -1] <> st[i] then { daca litera din matrice nu corespunde cu cea a cuvantuli } begin poz_cuv_1 := false; { nu putem pozitiona cuvantul } break; { iesim din loop } end; end else { nu avem loc spre dreapta } poz_cuv_1 := false; end; end; { pozitionam sprea dreapa jos, diagonala principala spre dreapta din pozitia <i>, <j> } function poz_cuv_2(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_2 := true; { consideram ca il putem pozitiona } with c do begin if ((col + len - 1) <= nr_n) AND ((lin+len-1) <= nr_n) then { avem loc spre dreapta } begin for i := 1 to len do { parcurgem fiecare litera } begin if mat[lin+i-1, col+i-1] = '-' then { daca locul e liber } begin vec_poz[i] := true; { marcam litera ca pusa intr-un loc gol } mat[lin+i-1, col+i-1] := st[i]; end else { locul nu e lober } if mat[lin+i-1, col+i-1] <> st[i] then { daca litera nu coincide cu a cuvantului } begin poz_cuv_2 := false; { nu putem pozitiona } break; { iesim din loop } end; end; end else { nu avem loc } poz_cuv_2 := false; end; end; { pozitionam in jos cuvantul } function poz_cuv_3(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_3 := true; { consideram ca il putem pozitiona } with c do begin if (lin+len-1) <= nr_n then { avem loc } begin for i := 1 to len do { mergem pe cuvinte } if mat[lin+i-1, col] = '-' then { locul este gol } begin vec_poz[i] := true; { marcam litera ca adaugata } mat[lin+i-1, col] := st[i]; { adaugam caracterul } end else { exista deja o litera } if mat[lin+i-1, col] <> st[i] then { daca litera din matrice nu coincide } begin poz_cuv_3 := false; { nu putem pozitiona } break; { iesim din loop } end; end else { nu avem loc } poz_cuv_3 := false; end; end; { pozitionam cuvantul in stanga jos, diagonala secundara spre stanga } function poz_cuv_4(lin, col :integer; var c :cuvant):boolean; var i :integer; begin poz_cuv_4 := true; { consideram ca il putem pozitiona } with c do begin if ((col-len+1) >= 1) AND ((lin+len-1) <= nr_n) then { avem loc spre stanga } begin for i := 1 to len do { parcurgem fiecare caracter } if mat[lin+i-1, col-i+1] = '-' then { avem spartiu liber } begin vec_poz[i] := true; { marcam litera ca pusa intr-un spatiu liber } mat[lin+i-1, col-i+1] := st[i]; { adaugam litera } end else { avem deja un caracter } if mat[lin+i-1, col-i+1] <> st[i] then { daca caracterul din matrice nu coincide } begin poz_cuv_4 := false; { nu putem aseja } break; end; end else { nu avem loc spre stanga } poz_cuv_4 := false; end; end; { pozitionam cuvantul in stanga } function poz_cuv_5(lin, col :integer; var c :cuvant):boolean; var i :integer; begin poz_cuv_5 := true; { consideram ca il putem pozitiona } with c do begin if (col-len+1) >= 1 then { avem spatiu } begin for i := 1 to len do { parcurgem caracterele } if mat[lin, col-i+1] = '-' then { avem spatiu liber } begin vec_poz[i] := true; { marcam caracterul ca introdus intr-un spatiu liber } mat[lin, col-i+1] := st[i]; { atribuim caracterul } end else { exista deja un caracter } if mat[lin, col-i+1] <> st[i] then { exista alt caracter } begin poz_cuv_5 := false; { nu putem pozitiona } break; end; end else { nu avem spatiu } poz_cuv_5 := false; end; end; { pozitionam pe diagonala principala spre stanga , stanga sus } function poz_cuv_6(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_6 := true; { presupunem ca putem pozitiona } with c do begin if ((col-len+1) >= 1 ) AND ((lin-len+1) >= 1) then { avem loc } begin for i := 1 to len do { parcurgem literele } if mat[lin-i+1, col-i+1] = '-' then { daca locul este liber } begin vec_poz[i] := true; { marcam caracterul ca inserat } mat[lin-i+1, col-i+1] := st[i]; end else { locul nu este liber } if mat[lin-i+1, col-i+1] <> st[i] then { literele nu coincid } begin poz_cuv_6 := false; { nu putem pozitiona } break; { iesim din loop } end; end else { nu avem loc } poz_cuv_6 := false; end; end; { pozitionam cuvantul in sus } function poz_cuv_7(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_7 := true; { consideram ca putem pozitiona } with c do begin if (lin-len+1) >= 1 then { avem loc in sus } begin for i := 1 to len do { parcurgem fiecare caracter } if mat[lin-i+1, col] = '-' then { locul este liber } begin vec_poz[i] := true; { marcam litera ca introdusa in matrice } mat[lin-i+1, col] := st[i]; end else { locul nu este liber } if mat[lin-i+1, col] <> st[i] then { daca litera nu coincide } begin poz_cuv_7 := false; { nu putem pozitiona } break; { iesim din loop } end; end else { nu avem loc } poz_cuv_7 := false; end; end; { pozitionam cuvantul dreapta sus } function poz_cuv_8(lin, col :integer;var c :cuvant):boolean; var i :integer; begin poz_cuv_8 := true; { consideram ca putem pozitiona } with c do begin if ((lin-len+1) >= 1) AND (col+len-1 <= nr_n) then { avem loc in dreapta sus } begin for i := 1 to len do { parcurgem fiecare caracter } if mat[lin-i+1, col+i-1] = '-' then { locul este liber } begin vec_poz[i] := true; { marcam litera ca introdusa in matrice } mat[lin-i+1, col+i-1] := st[i]; end else { locul nu este liber } if mat[lin-i+1, col+i-1] <> st[i] then { daca litera nu coincide } begin poz_cuv_8 := false; { nu putem pozitiona } break; { iesim din loop } end; end else { nu avem loc } poz_cuv_8 := false; end; end; { Manageriem Pozitionarea } function handle_poz_cuv(lin, col, dir :integer;var cuv :cuvant):boolean; begin handle_poz_cuv := false; { adaugam meta-data } cuv.poz_l := lin; cuv.poz_c := col; cuv.dir := dir; case dir of 1 : begin { pozitionare spre dreapta } handle_poz_cuv := poz_cuv_1(lin, col, cuv); end; 2 : begin { pozitionam spre dreapta jos } handle_poz_cuv := poz_cuv_2(lin, col, cuv); end; 3 : begin { pozitionam in jos } handle_poz_cuv := poz_cuv_3(lin, col, cuv); end; 4 : begin { pozitionam spre stanga jos } handle_poz_cuv := poz_cuv_4(lin, col, cuv); end; 5 : begin { pozitionam spre stanga } handle_poz_cuv := poz_cuv_5(lin, col, cuv); end; 6 : begin { pozitionam spre stanga sus } handle_poz_cuv := poz_cuv_6(lin, col, cuv); end; 7 : begin { pozitionam in sus } handle_poz_cuv := poz_cuv_7(lin, col, cuv); end; 8 : begin { pozitionam in sus } handle_poz_cuv := poz_cuv_8(lin, col, cuv); end; end; { DebugHelp } inc_poz(dir); { incrementam pozitionarea } if handle_poz_cuv then { daca a reusit pozitionarea } inc_poz_reusita(dir); { numaram } { EndDebugHelp } if not handle_poz_cuv then { daca nu am putut pozitiona } handle_undo_cuv(cuv); end; { ====================================================== } { File Handling } function citire_input(s :string):boolean; var i :integer; f :text; aux_s :string; begin len_max := 0; if FileExists(s) then { daca fisierul exista } begin assign(f, s); reset(f); readln(f, nr_n); { citim ordinul matrici } { initializam matricea } init_mat(mat, nr_n); readln(f, nr_cuv); { citim numarul de cuvinte } { citim cuvintele } for i := 1 to nr_cuv do begin readln(f, aux_s); if length(aux_s) > len_max then len_max := length(aux_s); init_cuv(vec_c[i], aux_s); { initializam cuvantul } end; citire_input := true; end else { fisierul nu exista } citire_input := false; end; { ====================================================== } { Starting searching } procedure start(nr_c :integer); var lin, col, dir :integer; begin { DebugHelp } inc_nr_rec; { EndDebugHelp } { initializam } lin := 1; col := 1; dir := 1; if nr_c <= nr_cuv then { cat timp mai avem cuvinte } while (lin <= nr_n) AND (not rez) do { cat timp mai avem linii } begin col := 1; while (col <= nr_n) AND (not rez) do { cat timp mai avem coloane } begin dir := 1; while (dir <= max_dir) AND (not rez) do { cat timp mai avem directii } begin handle_undo_cuv(vec_c[nr_c]); { reinitializam cuvantul } if handle_poz_cuv(lin, col, dir, vec_c[nr_c]) AND (not rez) then { am reusit sa pozitionam } begin start(nr_c + 1); dir := dir + 1; if not rez then handle_undo_cuv(vec_c[nr_c]); { reinitializam cuvantul } end else { nu am putut pozitiona } dir := dir + 1; { trecem la urmatoarea pozitie } end; { end directii } col := col + 1; { trecem la urmatoarea coloana } end; { end coloane } lin := lin + 1; { trecem la urmatoarea linie } end { end linii } else { nu mai avem cuvinte, am terminat } rez := true; end; { ====================================================== } { Interactive Mode } procedure help_int(s :string); begin case s of '' : begin writeln; writeln(' Aveti urmatoarele comezi :'); writeln(' poz : deschide un meniu din care puteti pozitiona un cuvant '); writeln; writeln(' undo : deschide un meniu din care puteti sterge un cuvant '); writeln; writeln(' show_mat : afiseaza matricea '); writeln; writeln(' show_cuv : afiseaza informatii despre un cuvant '); writeln; writeln(' init_mat : initializeaza o noua matrice de orce ordin '); writeln; writeln(' add_cuv : adaugati un cuvant in array '); writeln; writeln(' info : informatii generale despre statulul programului '); writeln; writeln(' q : iestiti din modul interactiv si din program '); writeln(' quit '); writeln(' exit '); end; 'info': begin writeln; writeln(' Numarul de cuvinte stocate : ', nr_cuv); writeln(' Ordinea matrici : ', nr_n); writeln(' Version : ', version); end; end; writeln; end; procedure Interactive; var aux_i, aux_j, aux_d, aux_n :integer; aux_s, cm :string; begin cm := ''; { initializam commanda } while (lowercase(cm) <> 'q') and (lowercase(cm) <> 'quit') and (lowercase(cm) <> 'exit') do begin write('>> '); readln(cm); { pozitionari } if lowercase(cm) = 'poz' then { daugam un cuvant } begin write('Linie :'); readln(aux_i); write('Coloana :'); readln(aux_j); write('Directie :'); readln(aux_d); write('Numarul cuvantului :'); readln(aux_n); handle_poz_cuv(aux_i, aux_j, aux_d, vec_c[aux_n]); end; if lowercase(cm) = 'add_cuv' then { adaugam un cuvant in vector } begin write('Cuvant :'); read(aux_s); nr_cuv := nr_cuv + 1; init_cuv(vec_c[nr_cuv], aux_s); end; { matrice commands } if lowercase(cm) = 'show_mat' then { daca se doreste afisarea matrici } begin afis_mat(mat, nr_n); end; if lowercase(cm) = 'init_mat' then { daca se doreste initializarea } begin write('n= '); readln(nr_n); init_mat(mat, nr_n); end; { undo } if lowercase(cm) = 'undo' then begin write('Numararul cuvantului :'); readln(aux_i); handle_undo_cuv(vec_c[aux_i]); end; { cuvant commands } if lowercase(cm) = 'show_cuv' then { afisam informatii despre cuvant } begin write('Numarul cuvantului :'); readln(aux_n); afis_cuv(vec_c[aux_n]); end; { daca se doreste ajutor } if lowercase(cm) = 'help' then { afisam help } begin help_int(''); end; { daca se doresc informatii } if lowercase(cm) = 'info' then begin help_int('info'); end; end; end; { ====================================================== } { Strings } { returam directia pozitionari } function get_dir(dir :integer):string; begin case dir of 1 : get_dir := ' dreapta'; 2 : get_dir := ' dreapta jos'; 3 : get_dir := ' jos'; 4 : get_dir := ' stanga jos'; 5 : get_dir := ' stanga'; 6 : get_dir := ' stanga sus'; 7 : get_dir := ' sus'; 8 : get_dir := ' dreapta sus'; end; end; { help handler } procedure help(s :string); var i :integer; begin case s of '' : begin writeln(' Scop :'); writeln(' Acest program creeaza o matrice in care se vor regasi toate cuvintele din fisier.'); writeln; writeln(' Fisierul este de forma :'); writeln; writeln(' <ordin_matrice>'); writeln(' <numar_cuvinte>'); writeln(' <cuvant_1>'); writeln(' <cuvant_2>'); writeln(' <........>'); writeln(' <cuvant_n>'); writeln; writeln(' Urmatoarele obtiuni sunt disponibile :'); writeln(' -f'); writeln(' --file=name : fisierul din care citim cuvintele si dimensiunile matrici'); writeln; writeln(' -i'); writeln(' --interactiv : acctivam modul interactiv, care ne permite sa manipulam cuvinte'); writeln; writeln(' -v'); writeln(' --version : afisam versiunea, si alte informatii'); writeln; writeln(' -d'); writeln(' --debug=true/false : valoarea default este false, dar daca se rescrie, se vor afisa diferite'); writeln(' valori auxiliare'); writeln; writeln(' -c'); writeln(' --create=name : se intra in modul care ajuta la creearea unui fisier input '); writeln(' daca un nume nu este precizat atunci se va folosi defaul.txt '); writeln; writeln(' -h'); writeln(' --help : afisam ajutorul acesta'); end; 'short': begin writeln(' Accesati -h sau --help pentru mai multe informatii.') end; 'nu_incape': begin writeln(' Urmatoarele cuvinte :'); for i := 1 to nr_cuv do if vec_c[i].len = len_max then writeln(' - ',vec_c[i].st); writeln; writeln(' Au lungimea ', len_max,' si nu pot incapea intr-o matrice de ordin ', nr_n, ' .'); end; 'nu_a_fost_gasit': begin writeln(' Nu am gasit fisierul!'); end; 'nu_am_rezolvat': begin writeln(' Nu am gasit o rezolvare, verificati fisierul!'); end; 'debug': begin d_nr_poz := 0; d_nr_poz_reusite := 0; d_nr_undo := 0; writeln; writeln(' Iformatii suplimentare :'); writeln; writeln('| Cod poz. | Dir. poz. | Nr. poz | Nr. poz. reusite | Nr. undo |'); for i := 1 to 8 do begin writeln('|',i:6,' |', get_dir(i):13,' |',d_vec_poz[i]:7,' | ',d_vec_poz_reusite[i]:9,' | ', d_vec_undo[i]:8,' |'); inc(d_nr_poz, d_vec_poz[i]); inc(d_nr_poz_reusite, d_vec_poz[i]); inc(d_nr_undo, d_vec_undo[i]); end; writeln('-------------------------------- TOTAL --------------------------------'); writeln(' Pozitionari :', d_nr_poz:10); writeln(' Pozitionari reusit :', d_nr_poz:10); writeln(' Undo :', d_nr_undo:10); writeln(' Apelari recursive :', d_nr_rec:10); end; 'version': begin writeln; writeln(' Version :', version); writeln(' Author :', autor); writeln(' Email :', gmail); writeln(' GitHub Repo :', git); writeln(' Licenta :', licenta); end; 'interactiv': begin writeln; writeln(' Ati intrat in modul interactiv puteti folosi comanda <help> pentru a afla mai multe'); writeln; end; 'nu_am_inteles': begin writeln(' Nu am inteles comanda !') end; 'create': begin writeln; writeln(' Doriti sa creati un fisier pe care sa il folosit ca input.'); end; end; writeln; end; { ====================================================== } { Command Line handeling } { cream un fisier input } procedure create_imput(s :string); var ok :boolean; comanda :string; f :text; aux_i, i :integer; begin if FileExists(s) then begin write(' Fisierul cu numele <',s,'> exista deja, doriti sa il rescrieti?(y/n):'); readln(comanda); if (lowercase(comanda) = 'y') or (lowercase(comanda) = 'yes') or (lowercase(comanda) = 'da') then ok := true else ok := false; end else ok := true; if ok then begin assign(f, s); rewrite(f); write(' Ce ordin doriti sa aiba matricea ( adica cat pe cat va fi patratul ) : '); read(aux_i); writeln(f, aux_i); { scriem in fisier ordinum latrici } write(' Cate cuvinte doriti sa pozitonati in matrice :'); read(aux_i); writeln(f, aux_i); { scriem in fisier numarul de cuvinte } for i := 1 to aux_i do begin write(' Cuvantul nr. ', i,' : '); readln(comanda); writeln(f, comanda); end; close(f); writeln(' Am creat fisierul cu succes !'); writeln; end else begin writeln(' Au existat probleme.'); writeln(' Oprim creearea fisierului !'); writeln; end; end; { verificam daca exista optiunea <s> } function HasOption(s :string):boolean; var i :integer; begin HasOption := false; if length(s) = 1 then { short param } begin for i := 1 to ParamCount do { mergem prin parametri } if concat('-', s) = ParamStr(i) then { avem parametrul } begin HasOption := true; break; end; end else { long param } begin for i := 1 to ParamCount do { mergem prin parametri } if concat('--', s) = ParamStr(i) then { avem parametrul } begin HasOption := true; break; end; end; end; { returnam valoarea parametrului <s> } function GetValueParam(s :string):string; var i :integer; begin GetValueParam := ''; if length(s) = 1 then begin for i := 1 to ParamCount do { parcurgem parametri } if concat('-', s) = ParamStr(i) then { am gasit parametrul } begin GetValueParam := ParamStr(i+1); { ii salvam valoarea } break; end; end else begin for i := 1 to ParamCount do { parcurgem parametri } if concat('--', s) = ParamStr(i) then { am gasit parametrul } begin GetValueParam := ParamStr(i+1); { ii salvam valoarea } break; end; end; end; { verificam daca a fost pasat macar un argument } function HasParams:boolean; begin HasParams := (ParamCount > 0) end; { returnam defaul.txt sau numele fisierului } function GetCreateParram(s :string):string; begin if GetValueParam(s) <> '' then GetCreateParram := GetValueParam(s) else GetCreateParram := 'default.txt'; end; { handler } procedure HandleInput; var something_was_run, start_was_run :boolean; aux_s :string; begin something_was_run := false; start_was_run := false; { verificam daca exista parametri } if HasParams then begin if HasOption('c') then { daca se doreste creearea unui fisier } begin aux_s := GetCreateParram('c'); help('create'); create_imput(aux_s); end else begin if HasOption('create') then begin aux_s := GetCreateParram('create'); help('create'); create_imput(aux_s); end else begin { verificam daca se doreste afisarea versiuni } if HasOption('v') or HasOption('version') then begin help('version'); something_was_run := true; end; { checking for help } if not something_was_run then begin if HasOption('h') or HasOption('help') then begin help(''); something_was_run := true; { s-a rulat o comanda } end else { se doreste rulare } begin { checking for filename problems } if HasOption('f') then begin if citire_input(GetValueParam('f')) then if len_max <= nr_n then { cel mai lung cuvant incape in matrice } begin start(1); { incepem sa rulam programul } something_was_run := true; { s-a rulat o comanda } start_was_run := true; { s-a rulat startu } end else { daca avem un cuvant prea lung } begin something_was_run := true; { s-a rulat o comanda } help('nu_incape'); help('short'); end else { nu am putut citi fisietul trimis ca parametrul lui 'f' } begin something_was_run := true; { s-a rulat o comanda } help('nu_a_fost_gasit'); help('short'); { Afisam un mic ajutor } end; end else { not has 'f' } if HasOption('file') then begin if citire_input(GetValueParam('file')) then if len_max <= nr_n then begin start(1); { incepem sa rulam programul } something_was_run := true; { s-a rulat o comanda } start_was_run := true; { s-a rulat startu } end else { nu incape } begin something_was_run := true; { s-a rulat o comanda } help('nu_incape'); help('short'); end else { nu am gasit fisierul } begin something_was_run := true; { s-a rulat o comanda } help('nu_a_fost_gasit'); help('short'); { Afisam un mic ajutor } end; end else { nu are optiunea 'file' } begin help('nu_a_fost_gasit'); something_was_run := true; { s-a rulat o comanda } help('short'); { Afisam un mic ajutor } end; if start_was_run then { daca am rulat staturl } begin if rez then { daca am rezolvar } begin writeln('Rezolvare :'); afis_mat(mat, nr_n); end else help('nu_am_rezolvat'); end; { vedem daca se doreste afisarea informatiilor suplimentar } if HasOption('d') OR HasOption('debug') then if (lowercase(GetValueParam('d')) = 'true') OR (lowercase(GetValueParam('debug')) = 'true') then begin help('debug'); something_was_run := true; end; { verificam daca se doreste modul interactiv } if HasOption('i') or HasOption('interactive') then begin help('interactiv'); Interactive; something_was_run := true; { s-a rulat o comanda } end; end; end; { end not something_.. } if not something_was_run then { daca nu s-a rulat nimic } begin help('nu_am_inteles'); help('short'); { Afisam un mic ajutor } end; end; end; { end de la has --create mode } end { end HasParams } else { daca nu s-au adaugat parametri } begin help('nu_am_inteles'); help('short'); { Afisam un mic ajutor } end; end; begin HandleInput; (* Interactive; *) end.
unit uAbastecimentoController; interface uses uAbastecimento, DBClient; type TAbastecimentoController = class public function Inserir(oAbastecimento: TAbastecimento; var sError: string): Boolean; function Atualizar(oAbastecimento: TAbastecimento; var sError: string): Boolean; function Excluir(oAbastecimento: TAbastecimento; var sError: string): Boolean; function Consultar(oAbastecimento: TAbastecimento; pFiltro: string; var sError: string): TClientDataSet; function ConsultarComWhere(oAbastecimento: TAbastecimento; pBomba: Integer; pDataInicial, pDataFinal: string; var sError: string): TClientDataSet; function CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; end; implementation uses uPersistencia, SysUtils; { TAbastecimentoController } function TAbastecimentoController.Atualizar(oAbastecimento: TAbastecimento; var sError: string): Boolean; begin Result := TPersistencia.Atualizar(oAbastecimento, sError); end; function TAbastecimentoController.CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; begin Result := TPersistencia.CarregaLookupChaveEstrangeira(pObjeto, pCampo); end; function TAbastecimentoController.Consultar(oAbastecimento: TAbastecimento; pFiltro: string; var sError: string): TClientDataSet; begin Result := TPersistencia.Consultar(oAbastecimento, 'NOME', pFiltro, sError); end; function TAbastecimentoController.ConsultarComWhere( oAbastecimento: TAbastecimento; pBomba: Integer; pDataInicial, pDataFinal: string; var sError: string): TClientDataSet; var where: string; begin where := ''; if IntToStr(pBomba) <> EmptyStr then where := 'BOMBA = ' + IntToStr(pBomba); if (pDataInicial <> EmptyStr) and (pDataFinal <> EmptyStr) then begin if IntToStr(pBomba) <> EmptyStr then where := where + ' AND DATA BETEWEEN ' + pDataInicial + ' AND ' + pDataFinal else where := where + ' DATA BETEWEEN ' + pDataInicial + ' AND ' + pDataFinal; end; Result := TPersistencia.ConsultarWhere(oAbastecimento, where, sError); end; function TAbastecimentoController.Excluir(oAbastecimento: TAbastecimento; var sError: string): Boolean; begin Result := TPersistencia.Excluir(oAbastecimento, sError); end; function TAbastecimentoController.Inserir(oAbastecimento: TAbastecimento; var sError: string): Boolean; begin Result := TPersistencia.Inserir(oAbastecimento, sError); end; end.
{***************************************************************************} { } { DelphiWebDriver } { } { Copyright 2017 inpwtepydjuf@gmail.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit Commands.GetText; interface uses Vcl.Forms, CommandRegistry, HttpServerCommand; type /// <summary> /// Handles 'GET' '/session/(.*)/element/(.*)/text' /// </summary> TGetTextCommand = class(TRESTCommand) private function OKResponse(const handle, value: String): String; public class function GetCommand: String; override; class function GetRoute: String; override; procedure Execute(AOwner: TForm); override; end; implementation uses System.JSON, System.JSON.Types, Vcl.Controls, Vcl.Grids, System.SysUtils, System.Classes, System.StrUtils, Vcl.ComCtrls, Vcl.Menus, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls, utils; procedure TGetTextCommand.Execute(AOwner: TForm); var comp: TComponent; ctrl: TWinControl; handle: Integer; parent: TComponent; values : TStringList; value: String; const Delimiter = '.'; begin if (isNumber(self.Params[2])) then begin handle := StrToInt(self.Params[2]); ctrl := FindControl(handle); if (ctrl <> nil) then begin if (ctrl is TEdit) then value := (ctrl as TEdit).Text else if (ctrl is TStaticText) then value := (ctrl as TStaticText).Caption else if (ctrl is TCheckBox) then value := (ctrl as TCheckBox).Caption else if (ctrl is TLinkLabel) then value := (ctrl as TLinkLabel).Caption else if (ctrl is TRadioButton) then value := (ctrl as TRadioButton).Caption; ResponseJSON(OKResponse(self.Params[2], value)); end else Error(404); end else begin // This might be a non-WinControl OR a DataItem for a container if (ContainsText(self.Params[2], Delimiter)) then begin values := TStringList.Create; try values.Delimiter := Delimiter; values.StrictDelimiter := True; values.DelimitedText := self.Params[2]; // Get parent parent := AOwner.FindComponent(values[0]); if (parent is TListBox) then begin value := (parent as TListBox).items[StrToInt(values[1])]; end else if (parent is TStringGrid) then begin value := (parent as TStringGrid).Cells[StrToInt(values[1]),StrToInt(values[2])]; end else if (parent is TPageControl) then begin value := (parent as TPageControl).Pages[StrToInt(values[1])].Caption; end else if (parent is TCombobox) then begin value := (parent as TCombobox).items[StrToInt(values[1])]; end; // Now send it back please ResponseJSON(OKResponse(self.Params[2], value)); finally values.free; end; end else begin comp := AOwner.FindComponent(self.Params[2]); if (comp <> nil) then begin if (comp is TSpeedButton) then Value := (comp as TSpeedButton).Caption else if (comp is TMenuItem) then Value := (comp as TMenuItem).Caption else if (comp is TLabel) then Value := (comp as TLabel).Caption; ResponseJSON(OKResponse(self.Params[2], value)); end else Error(404); end; end; end; function TGetTextCommand.OKResponse(const handle, value: String): String; var jsonObject: TJSONObject; begin jsonObject := TJSONObject.Create; jsonObject.AddPair(TJSONPair.Create('id', handle)); jsonObject.AddPair(TJSONPair.Create('value', value)); result := jsonObject.ToString; end; class function TGetTextCommand.GetCommand: String; begin result := 'GET'; end; class function TGetTextCommand.GetRoute: String; begin result := '/session/(.*)/element/(.*)/text'; end; end.
unit uMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, BZColors, BZGraphic, BZBitmap, BZBitmapIO, BZMath, BZVectorMath, BZInterpolationFilters, BZThreadTimer; type { TMainForm } TMainForm = class(TForm) procedure FormCreate(Sender : TObject); procedure FormClose(Sender : TObject; var CloseAction : TCloseAction); procedure FormCloseQuery(Sender : TObject; var CanClose : boolean); procedure FormPaint(Sender : TObject); procedure FormShow(Sender : TObject); private FThreadTimer : TBZThreadTimer; FBackBitmap : TBZBitmap; FGlassBitmap : TBZBitmap; FClockBitmap : TBZBitmap; FDisplayBitmap : TBZBitmap; FClockCenter : TBZPoint; public bWidth, bHeight : Integer; Second_PointA, Second_PointB : TBZPoint; Minute_PointA, Minute_PointB : TBZPoint; Hour_PointA, Hour_PointB : TBZPoint; FCanClose : Boolean; procedure UpdateClock(Sender:TObject); procedure RenderClock; end; var MainForm : TMainForm; implementation {$R *.lfm} uses BZTypesHelpers; { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); begin bWidth := 512; bHeight := 512; FThreadTimer := TBZThreadTimer.Create(Self); FThreadTimer.Enabled := False; FThreadTimer.OnTimer := @UpdateClock; FBackBitmap := TBZBitmap.Create; FBackBitmap.LoadFromFile('../../../../../media/images/stonefloor.jpg'); FBackBitmap.Transformation.Resample(bWidth,bHeight,ifmLanczos3); FGlassBitmap := TBZBitmap.Create; FGlassBitmap.LoadFromFile('../../../../../media/images/backclockGlass01.png'); FGlassBitmap.PreMultiplyAlpha; FClockBitmap := TBZBitmap.Create; FClockBitmap.LoadFromFile('../../../../../media/images/backclock01.png'); FBackBitmap.PutImage(FClockBitmap,0,0,bWidth, bHeight,0,0,dmSet,amAlpha); FreeAndNil(FClockBitmap); FDisplayBitmap := TBZBitmap.Create(512,512); FDisplayBitmap.Clear(clrBlack); FClockCenter.Create(255,255); end; procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction); begin FreeAndNil(FBackBitmap); FreeAndNil(FGlassBitmap); //FreeAndNil(FClockBitmap); FreeAndNil(FDisplayBitmap); end; procedure TMainForm.FormCloseQuery(Sender : TObject; var CanClose : boolean); begin FThreadTimer.Enabled := False; CanClose := FCanClose; OnPaint := nil; end; procedure TMainForm.FormPaint(Sender : TObject); begin FDisplayBitmap.DrawToCanvas(Canvas, ClientRect); end; procedure TMainForm.FormShow(Sender : TObject); begin FThreadTimer.Enabled := True; end; procedure TMainForm.UpdateClock(Sender : TObject); VAr Angle : Single; dMin,dMax : Integer; h,m, s : Word; sa, ca : Single; d : TDateTime; begin d := Now; s := d.Second; m := d.Minute; h := d.Hour; // Second Angle := -c2PI * (s/60); dMax := 200; dMin := 50; sa := Sin(Angle); ca := Cos(Angle); Second_PointA.Create(Round(FClockCenter.X + dMin * sa), Round(FClockCenter.Y + dMin * ca)); Second_PointB.Create(Round(FClockCenter.X - dMax * sa), Round(FClockCenter.Y - dMax * ca)); // Minute Angle := -c2PI * (m/60); dMax := 180; dMin := 30; sa := Sin(Angle); ca := Cos(Angle); Minute_PointA.Create(Round(FClockCenter.X + dMin * sa), Round(FClockCenter.Y + dMin * ca)); Minute_PointB.Create(Round(FClockCenter.X - dMax * sa), Round(FClockCenter.Y - dMax * ca)); // Hour if h > 12 then h := h - 12; Angle := -c2PI * (h/12); dMax := 150; dMin := 20; sa := Sin(Angle); ca := Cos(Angle); Hour_PointA.Create(Round(FClockCenter.X + dMin * sa), Round(FClockCenter.Y + dMin * ca)); Hour_PointB.Create(Round(FClockCenter.X - dMax * sa), Round(FClockCenter.Y - dMax * ca)); RenderClock; end; procedure TMainForm.RenderClock; begin FCanClose := False; FDisplayBitmap.PutImage(FBackBitmap,0,0,bWidth, bHeight,0,0); With FDisplayBitmap.Canvas do begin Antialias := True; Pen.Width := 3; Pen.Color := clrRed; Line(Second_PointA,Second_PointB); Pen.Color := clrBlack; Pen.Width := 5; Line(Minute_PointA,Minute_PointB); Pen.Width := 7; Line(Hour_PointA,Hour_PointB); Pen.Width := 1; Pen.Color := BZColor(234,234,173); Brush.Style := bsGradient; Brush.Gradient.Kind := gkRadial; Brush.Gradient.ColorSteps.AddColorStop(BZColor(217,217,26),0.0); Brush.Gradient.ColorSteps.AddColorStop(BZColor(204,127,50),1.0); Circle(FClockCenter.X-1, FClockCenter.Y,15); end; FDisplayBitmap.PutImage(FGlassBitmap,0,0,bWidth, bHeight,0,0,dmCombine,amAlphaBlend,255,cmHardLight); Invalidate; FCanClose := True; end; end.
unit HtmlReader; { The THTMLReader parses an HTML string into tokens, and presents them to the caller using a SAX-like eventing model. Listeners attach to the various OnXxx events: rdr.OnDocType := DocType; rdr.OnElementStart := ElementStart; rdr.OnElementEnd := ElementEnd; rdr.OnAttributeStart := AttributeStart; rdr.OnAttributeEnd := AttributeEnd; rdr.OnCDataSection := CDataSection; rdr.OnComment := Comment; rdr.OnEndElement := EndElement; rdr.OnEntityReference := EntityReference; rdr.OnTextNode := TextNode; This class is used by THTMLParser to process a string into a TDocument. You should not need to use this class directly unless you need to stream processing of a very large HTML document. See THtmlParser.ParseString for complete example of usage. var rdr: THtmlReader; rdr := THtmlReader.Create; rdr.OnElementStart := ElementStart; rdr.HtmlStr := '<HTML><BODY>Hello, world!</BODY></HTML>'; while rdr.Read do begin end; rdr.Free; TODO: Allow reading the HTML from a TStream. Version History =============== 1/7/2021 - Removed ReadEntityNode, since entities are no longer separate nodes - but instead just text 12/28/2021 - Set NodeType property before firing OnDocType event 12/22/2021 - LowerCase the doctype name - Doctype publicid and systemid can also be enclosed in apostrophe in addition to QUOTATION MARK 12/20/2021 - Fixed ReadQuotedStr to not also return the final '"' character. (only used by doctype reading) } interface uses Classes, DomCore; type TDelimiters = set of Byte; TReaderState = (rsInitial, rsBeforeAttr, rsBeforeValue, rsInValue, rsInQuotedValue); TStringGenerator = reference to function: UnicodeString; THtmlReader = class private FHtmlStr: TDomString; //the HTML string we are parsing FPosition: Integer; //current index in HtmlStr FNodeType: TNodeType; FPrefix: TDomString; FLocalName: TDomString; FNodeValue: TDomString; FPublicID: TDomString; FSystemID: TDomString; FIsEmptyElement: Boolean; FState: TReaderState; FQuotation: Word; FOnDocType: TNotifyEvent; FOnElementStart: TNotifyEvent; FOnElementEnd: TNotifyEvent; FOnEndElement: TNotifyEvent; FOnAttributeStart: TNotifyEvent; FOnAttributeValue: TNotifyEvent; FOnAttributeEnd: TNotifyEvent; FOnCDataSection: TNotifyEvent; FOnComment: TNotifyEvent; FOnEntityReference: TNotifyEvent; //FOnNotation: TNotifyEvent; //FOnProcessingInstruction: TNotifyEvent; FOnTextNode: TNotifyEvent; procedure LogFmt(const fmt: string; const Args: array of const); procedure LogBack(Callback: TStringGenerator); procedure SetHtmlStr(const Value: TDomString); procedure SetNodeName(Value: TDomString); function GetNodeName: TDomString; function IsEOF: Boolean; function GetToken(Delimiters: TDelimiters): TDomString; function IsAttrTextChar: Boolean; function IsDigit(HexBase: Boolean): Boolean; //current character is [0..9] function IsEndEntityChar: Boolean; //current character is [;] function IsEntityChar: Boolean; function IsEqualChar: Boolean; //current character is [=] function IsHexEntityChar: Boolean; function IsNumericEntity: Boolean; //current character is [#] function IsQuotation: Boolean; function IsSlashChar: Boolean; //current character is [/] function IsSpecialTagChar: Boolean; //current character is [!] function IsStartCharacterData: Boolean; function IsStartComment: Boolean; function IsStartDocumentType: Boolean; function IsStartEntityChar: Boolean; //current character is [&] function IsStartMarkupChar: Boolean; function IsStartTagChar: Boolean; function Match(const Signature: TDomString; IgnoreCase: Boolean): Boolean; function ReadElementNode: Boolean; //fires OnElementStart (NodeName, NodeType) procedure ReadElementTail; //fires OnElementEnd (NodeType) function ReadEndElementNode: Boolean; //fires OnEndElement (NodeName, NodeType) function ReadAttrNode: Boolean; //fires OnAttributeStart (NodeName) function ReadAttrTextNode: Boolean; //fires OnTextNode (NodeValue, NodeType) function ReadSpecialNode: Boolean; //calls ReadComment, ReadCharacterData, or ReadDocumentType function ReadComment: Boolean; //fires OnComment (NodeValue, NodeType) function ReadCharacterData: Boolean; //fires OnCDataSection (NodeValue, NodeType) function ReadDocumentType: Boolean; //fires OnDocType (NodeName, PublicID, SystemID) procedure ReadTextNode; //fires OnTextNode (NodeValue, NodeType) function ReadQuotedValue(var Value: TDomString): Boolean; function ReadTagNode: Boolean; function ReadValueNode: Boolean; function SkipTo(const Signature: TDomString): Boolean; procedure SkipWhiteSpaces; //Event callers procedure DoDocType(const Name, PublicID, SystemID: UnicodeString); procedure DoElementStart(const TagName: UnicodeString); procedure DoElementEnd(IsEmptyElement: Boolean); procedure DoEndElement(const TagName: UnicodeString); procedure DoAttributeStart(const AttributeName: UnicodeString); procedure DoAttributeValue(const AttributeValue: UnicodeString); procedure DoAttributeEnd(); procedure DoTextNode(const NodeValue: UnicodeString); procedure DoComment(const NodeValue: UnicodeString); procedure DoCDataSection(const NodeValue: UnicodeString); public constructor Create; function Read: Boolean; property HtmlStr: TDomString read FHtmlStr write SetHtmlStr; property Position: Integer read FPosition; property State: TReaderState read FState; // Properties of current read state property NodeType: TNodeType read FNodeType; property prefix: TDomString read FPrefix; property localName: TDomString read FLocalName; property nodeName: TDomString read GetNodeName; //synthetic from Prefix and LocalName property nodeValue: TDomString read FNodeValue; property publicID: TDomString read FPublicID; property systemID: TDomString read FSystemID; property isEmptyElement: Boolean read FIsEmptyElement; //SAX-like events property OnDocType: TNotifyEvent read FOnDocType write FOnDocType; property OnElementStart: TNotifyEvent read FOnElementStart write FOnElementStart; property OnElementEnd: TNotifyEvent read FOnElementEnd write FOnElementEnd; //nodeType, isEmptyElement property OnEndElement: TNotifyEvent read FOnEndElement write FOnEndElement; property OnAttributeStart: TNotifyEvent read FOnAttributeStart write FOnAttributeStart; property OnAttributeValue: TNotifyEvent read FOnAttributeValue write FOnAttributeValue; property OnAttributeEnd: TNotifyEvent read FOnAttributeEnd write FOnAttributeEnd; property OnTextNode: TNotifyEvent read FOnTextNode write FOnTextNode; property OnComment: TNotifyEvent read FOnComment write FOnComment; property OnEntityReference: TNotifyEvent read FOnEntityReference write FOnEntityReference; property OnCDataSection: TNotifyEvent read FOnCDataSection write FOnCDataSection; //Normally not allowed in HTML (only MathML and SVG elements) //property OnProcessingInstruction: TNotifyEvent read FOnProcessingInstruction write FOnProcessingInstruction; not allowed in HTML end; implementation uses SysUtils, Windows; const startTagChar = Ord('<'); endTagChar = Ord('>'); specialTagChar = Ord('!'); slashChar = Ord('/'); equalChar = Ord('='); quotation = [Ord(''''), Ord('"')]; tagDelimiter = [slashChar, endTagChar]; tagNameDelimiter = whiteSpace + tagDelimiter; attrNameDelimiter = tagNameDelimiter + [equalChar]; startEntity = Ord('&'); startMarkup = [startTagChar, startEntity]; endEntity = Ord(';'); notEntity = [endEntity] + startMarkup + whiteSpace; notAttrText = whiteSpace + quotation + tagDelimiter; numericEntity = Ord('#'); hexEntity = [Ord('x'), Ord('X')]; decDigit = [Ord('0')..Ord('9')]; hexDigit = [Ord('a')..Ord('f'), Ord('A')..Ord('F')]; const //https://infra.spec.whatwg.org/#code-points asciiDigit = [Ord('0')..Ord('9')]; //https://infra.spec.whatwg.org/#ascii-digit asciiUpperHexDigit = [Ord('A')..Ord('F')]; //https://infra.spec.whatwg.org/#ascii-upper-hex-digit asciiLowerHexDigit = [Ord('a')..Ord('f')]; //https://infra.spec.whatwg.org/#ascii-lower-hex-digit asciiHexDigit = asciiUpperHexDigit + asciiLowerHexDigit; //https://infra.spec.whatwg.org/#ascii-hex-digit asciiUpperAlpha = [Ord('A')..Ord('Z')]; //https://infra.spec.whatwg.org/#ascii-upper-alpha asciiLowerAlpha = [Ord('a')..Ord('z')]; //https://infra.spec.whatwg.org/#ascii-lower-alpha asciiAlpha = asciiUpperAlpha + asciiLowerAlpha; //https://infra.spec.whatwg.org/#ascii-alpha asciiAlphaNumeric = asciiDigit + asciiAlpha; //https://infra.spec.whatwg.org/#ascii-alphanumeric const DocTypeStartStr = 'DOCTYPE'; DocTypeEndStr = '>'; CDataStartStr = '[CDATA['; CDataEndStr = ']]>'; CommentStartStr = '--'; CommentEndStr = '-->'; SBoolean: array[Boolean] of string = ('False', 'True'); function DecValue(const Digit: WideChar): Word; begin Result := Ord(Digit) - Ord('0') end; function HexValue(const HexChar: WideChar): Word; var C: Char; begin if Ord(HexChar) in decDigit then Result := Ord(HexChar) - Ord('0') else begin C := UpCase(Chr(Ord(HexChar))); Result := Ord(C) - Ord('A') end end; constructor THtmlReader.Create; begin inherited Create; FHtmlStr := HtmlStr; FPosition := 1 end; function THtmlReader.GetNodeName: TDomString; begin if FPrefix <> '' then Result := FPrefix + ':' + FLocalName else Result := FLocalName end; function THtmlReader.GetToken(Delimiters: TDelimiters): TDomString; var start: Integer; begin start := FPosition; while (FPosition <= Length(FHtmlStr)) and not (Ord(FHtmlStr[FPosition]) in Delimiters) do Inc(FPosition); Result := Copy(FHtmlStr, start, FPosition - start) end; function THtmlReader.IsAttrTextChar: Boolean; var wc: WideChar; begin wc := FHtmlStr[FPosition]; if FState = rsInQuotedValue then Result := (Ord(wc) <> FQuotation) // and (Ord(wc) <> startEntity) else Result := not (Ord(wc) in notAttrText) end; function THtmlReader.IsDigit(HexBase: Boolean): Boolean; var wc: WideChar; begin wc := FHtmlStr[FPosition]; Result := Ord(wc) in decDigit; if not Result and HexBase then Result := Ord(wc) in hexDigit end; function THtmlReader.IsEndEntityChar: Boolean; var wc: WideChar; begin wc := FHtmlStr[FPosition]; Result := (Ord(wc) = endEntity); end; function THtmlReader.IsEntityChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := not (Ord(WC) in notEntity) end; function THtmlReader.IsEOF: Boolean; begin { Returns true if there are no more characters to read. } Result := (FPosition > Length(FHtmlStr)); end; function THtmlReader.IsEqualChar: Boolean; var wc: WideChar; begin wc := FHtmlStr[FPosition]; Result := (Ord(wc) = equalChar); end; function THtmlReader.IsHexEntityChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) in hexEntity; end; function THtmlReader.IsNumericEntity: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) = numericEntity end; function THtmlReader.IsQuotation: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; if FQuotation = 0 then Result := Ord(WC) in quotation else Result := Ord(WC) = FQuotation end; function THtmlReader.IsSlashChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) = slashChar end; function THtmlReader.IsSpecialTagChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) = specialTagChar end; function THtmlReader.IsStartCharacterData: Boolean; begin Result := Match(CDataStartStr, false) end; function THtmlReader.IsStartComment: Boolean; begin Result := Match(CommentStartStr, false) end; function THtmlReader.IsStartDocumentType: Boolean; begin Result := Match(DocTypeStartStr, true) end; function THtmlReader.IsStartEntityChar: Boolean; var wc: WideChar; begin { Returns true if the current input character is "&" - the entity start character. E.g.: &amp; &lt; &#128169; &#x1f4a9; } wc := FHtmlStr[FPosition]; Result := (Ord(wc) = startEntity); end; function THtmlReader.IsStartMarkupChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) in startMarkup end; function THtmlReader.IsStartTagChar: Boolean; var WC: WideChar; begin WC := FHtmlStr[FPosition]; Result := Ord(WC) = startTagChar end; procedure THtmlReader.LogBack(Callback: TStringGenerator); //var // s: UnicodeString; begin if IsDebuggerPresent then begin // s := Callback; // OutputDebugStringW(PWideChar(s)); end; end; procedure THtmlReader.LogFmt(const fmt: string; const Args: array of const); //var // s: string; begin if True then begin // s := Format(fmt, Args); // OutputDebugString(PChar('[THtmlReader] '+s)); end; end; function THtmlReader.Match(const Signature: TDomString; IgnoreCase: Boolean): Boolean; var I, J: Integer; W1, W2: WideChar; begin Result := false; for I := 1 to Length(Signature) do begin J := FPosition + I - 1; if (J < 1) or (J > Length(FHtmlStr)) then Exit; W1 := Signature[I]; W2 := FHtmlStr[J]; if (W1 <> W2) and (not IgnoreCase or (UpperCase(W1) <> UpperCase(W2))) then Exit end; Result := true end; function HtmlDecode(s: string): string; function UCS4CharToString(uch: UCS4Char): UnicodeString; var s: UCS4String; begin SetLength(s, 2); s[0] := uch; s[1] := 0; //null terminator Result := UCS4StringToUnicodeString(s); end; function GetCharRef(sValue: string; StartIndex: Integer; out CharRef: string): UnicodeString; var i: Integer; len: Integer; nChar: UCS4Char; begin { Character references come in either decimal or hex forms: &#9830; //decimal &#x2666; //hexidecimal As per the definition: CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' } Result := ''; CharRef := ''; len := Length(sValue) - StartIndex + 1; if len < 4 then Exit; i := StartIndex; if sValue[i] <> '&' then Exit; Inc(i); if sValue[i] <> '#' then Exit; Inc(i); if sValue[i] = 'x' then begin { Hex character reference CharRef ::= '&#x' [0-9a-fA-F]+ ';' E.g. &#x2666; } Inc(i); //skip the x while CharInSet(sValue[i], ['0'..'9', 'a'..'f', 'A'..'F']) do begin Inc(i); if i > Length(sValue) then Exit; end; if sValue[i] <> ';' then Exit; charRef := Copy(sValue, StartIndex, (i-StartIndex)+1); nChar := StrToInt('$'+Copy(charRef, 4, Length(charRef)-4)); end else begin { Decimal character reference CharRef ::= '&#' [0-9]+ ';' E.g. &#9830; } while CharInSet(sValue[i], ['0'..'9']) do begin Inc(i); if i > Length(sValue) then Exit; end; if sValue[i] <> ';' then Exit; charRef := Copy(sValue, StartIndex, (i-StartIndex)+1); nChar := StrToInt(Copy(charRef, 3, Length(charRef)-3)); end; Result := UCS4CharToString(nChar); end; function GetEntityRef(sValue: string; StartIndex: Integer; out CharRef: string): UnicodeString; function IsNameStartChar(ch: WideChar): Boolean; begin { NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] } Result := False; case ch of ':', 'A'..'Z', '_', 'a'..'z', #$C0..#$D6, #$D8..#$F6, #$F8..#$FF: Result := True; #$100..#$2FF, #$370..#$37D, #$37F..#$FFF: Result := True; #$1000..#$1FFF, #$200C..#$200D, #$2070..#$218F, #$2C00..#$2FEF, #$3001..#$D7FF, #$F900..#$FDCF, #$FDF0..#$FFFD: Result := True; else //We assume strings are UTF-16. But by assuming one 16-bit word is the same as one character is just wrong. //UTF-16, like UTF-8 can be multi-byte. //But it's just so haaaard to support. //The correct action is to convert the string to UCS4, where one code-point is always one character. case Integer(ch) of $10000..$EFFFF: Result := True; end; end; end; function IsNameChar(ch: WideChar): Boolean; begin if IsNameStartChar(ch) then begin Result := True; Exit; end; case ch of '-', '.', '0'..'9', #$B7, #$0300..#$036F, #$203F..#$2040: Result := True; else Result := False; end; end; type THtmlEntity = record entity: string; ch: UCS4Char; end; const //https://www.w3.org/TR/html4/sgml/entities.html#sym //html entities are case sensitive (e.g. "larr" is different from "lArr") HtmlEntities: array[0..252] of THtmlEntity = ( (entity: 'apos'; ch: 39; ), // apostrophe (originally only existed in xml, and not in HTML. Was added to HTML5 //24.2 Character entity references for ISO 8859-1 characters (entity: 'nbsp'; ch: 160; ), // no-break space = non-breaking space, U+00A0 (entity: 'iexcl'; ch: 161; ), // inverted exclamation mark, U+00A1 (entity: 'cent'; ch: 162; ), // cent sign, U+00A2 (entity: 'pound'; ch: 163; ), // pound sign, U+00A3 (entity: 'curren'; ch: 164; ), // currency sign, U+00A4 (entity: 'yen'; ch: 165; ), // yen sign = yuan sign, U+00A5 (entity: 'brvbar'; ch: 166; ), // broken bar = broken vertical bar, U+00A6 (entity: 'sect'; ch: 167; ), // section sign, U+00A7 (entity: 'uml'; ch: 168; ), // diaeresis = spacing diaeresis, U+00A8 (entity: 'copy'; ch: 169; ), // copyright sign, U+00A9 (entity: 'ordf'; ch: 170; ), // feminine ordinal indicator, U+00AA (entity: 'laquo'; ch: 171; ), // left-pointing double angle quotation mark = left pointing guillemet, U+00AB (entity: 'not'; ch: 172; ), // not sign, U+00AC (entity: 'shy'; ch: 173; ), // soft hyphen = discretionary hyphen, U+00AD (entity: 'reg'; ch: 174; ), // registered sign = registered trade mark sign, U+00AE (entity: 'macr'; ch: 175; ), // macron = spacing macron = overline = APL overbar, U+00AF (entity: 'deg'; ch: 176; ), // degree sign, U+00B0 (entity: 'plusmn'; ch: 177; ), // plus-minus sign = plus-or-minus sign, U+00B1 (entity: 'sup2'; ch: 178; ), // superscript two = superscript digit two = squared, U+00B2 (entity: 'sup3'; ch: 179; ), // superscript three = superscript digit three = cubed, U+00B3 (entity: 'acute'; ch: 180; ), // acute accent = spacing acute, U+00B4 (entity: 'micro'; ch: 181; ), // micro sign, U+00B5 (entity: 'para'; ch: 182; ), // pilcrow sign = paragraph sign, U+00B6 (entity: 'middot'; ch: 183; ), // middle dot = Georgian comma = Greek middle dot, U+00B7 (entity: 'cedil'; ch: 184; ), // cedilla = spacing cedilla, U+00B8 (entity: 'sup1'; ch: 185; ), // superscript one = superscript digit one, U+00B9 (entity: 'ordm'; ch: 186; ), // masculine ordinal indicator, U+00BA (entity: 'raquo'; ch: 187; ), // right-pointing double angle quotation mark = right pointing guillemet, U+00BB (entity: 'frac14'; ch: 188; ), // vulgar fraction one quarter = fraction one quarter, U+00BC (entity: 'frac12'; ch: 189; ), // vulgar fraction one half = fraction one half, U+00BD (entity: 'frac34'; ch: 190; ), // vulgar fraction three quarters = fraction three quarters, U+00BE (entity: 'iquest'; ch: 191; ), // inverted question mark = turned question mark, U+00BF (entity: 'Agrave'; ch: 192; ), // latin capital letter A with grave = latin capital letter A grave, U+00C0 (entity: 'Aacute'; ch: 193; ), // latin capital letter A with acute, U+00C1 (entity: 'Acirc'; ch: 194; ), // latin capital letter A with circumflex, U+00C2 (entity: 'Atilde'; ch: 195; ), // latin capital letter A with tilde, U+00C3 (entity: 'Auml'; ch: 196; ), // latin capital letter A with diaeresis, U+00C4 (entity: 'Aring'; ch: 197; ), // latin capital letter A with ring above = latin capital letter A ring, U+00C5 (entity: 'AElig'; ch: 198; ), // latin capital letter AE = latin capital ligature AE, U+00C6 (entity: 'Ccedil'; ch: 199; ), // latin capital letter C with cedilla, U+00C7 (entity: 'Egrave'; ch: 200; ), // latin capital letter E with grave, U+00C8 (entity: 'Eacute'; ch: 201; ), // latin capital letter E with acute, U+00C9 (entity: 'Ecirc'; ch: 202; ), // latin capital letter E with circumflex, U+00CA (entity: 'Euml'; ch: 203; ), // latin capital letter E with diaeresis, U+00CB (entity: 'Igrave'; ch: 204; ), // latin capital letter I with grave, U+00CC (entity: 'Iacute'; ch: 205; ), // latin capital letter I with acute, U+00CD (entity: 'Icirc'; ch: 206; ), // latin capital letter I with circumflex, U+00CE (entity: 'Iuml'; ch: 207; ), // latin capital letter I with diaeresis, U+00CF (entity: 'ETH'; ch: 208; ), // latin capital letter ETH, U+00D0 (entity: 'Ntilde'; ch: 209; ), // latin capital letter N with tilde, U+00D1 (entity: 'Ograve'; ch: 210; ), // latin capital letter O with grave, U+00D2 (entity: 'Oacute'; ch: 211; ), // latin capital letter O with acute, U+00D3 (entity: 'Ocirc'; ch: 212; ), // latin capital letter O with circumflex, U+00D4 (entity: 'Otilde'; ch: 213; ), // latin capital letter O with tilde, U+00D5 (entity: 'Ouml'; ch: 214; ), // latin capital letter O with diaeresis, U+00D6 (entity: 'times'; ch: 215; ), // multiplication sign, U+00D7 (entity: 'Oslash'; ch: 216; ), // latin capital letter O with stroke = latin capital letter O slash, U+00D8 (entity: 'Ugrave'; ch: 217; ), // latin capital letter U with grave, U+00D9 (entity: 'Uacute'; ch: 218; ), // latin capital letter U with acute, U+00DA (entity: 'Ucirc'; ch: 219; ), // latin capital letter U with circumflex, U+00DB (entity: 'Uuml'; ch: 220; ), // latin capital letter U with diaeresis, U+00DC (entity: 'Yacute'; ch: 221; ), // latin capital letter Y with acute, U+00DD (entity: 'THORN'; ch: 222; ), // latin capital letter THORN, U+00DE (entity: 'szlig'; ch: 223; ), // latin small letter sharp s = ess-zed, U+00DF (entity: 'agrave'; ch: 224; ), // latin small letter a with grave = latin small letter a grave, U+00E0 (entity: 'aacute'; ch: 225; ), // latin small letter a with acute, U+00E1 (entity: 'acirc'; ch: 226; ), // latin small letter a with circumflex, U+00E2 (entity: 'atilde'; ch: 227; ), // latin small letter a with tilde, U+00E3 (entity: 'auml'; ch: 228; ), // latin small letter a with diaeresis, U+00E4 (entity: 'aring'; ch: 229; ), // latin small letter a with ring above = latin small letter a ring, U+00E5 (entity: 'aelig'; ch: 230; ), // latin small letter ae = latin small ligature ae, U+00E6 (entity: 'ccedil'; ch: 231; ), // latin small letter c with cedilla, U+00E7 (entity: 'egrave'; ch: 232; ), // latin small letter e with grave, U+00E8 (entity: 'eacute'; ch: 233; ), // latin small letter e with acute, U+00E9 (entity: 'ecirc'; ch: 234; ), // latin small letter e with circumflex, U+00EA (entity: 'euml'; ch: 235; ), // latin small letter e with diaeresis, U+00EB (entity: 'igrave'; ch: 236; ), // latin small letter i with grave, U+00EC (entity: 'iacute'; ch: 237; ), // latin small letter i with acute, U+00ED (entity: 'icirc'; ch: 238; ), // latin small letter i with circumflex, U+00EE (entity: 'iuml'; ch: 239; ), // latin small letter i with diaeresis, U+00EF (entity: 'eth'; ch: 240; ), // latin small letter eth, U+00F0 (entity: 'ntilde'; ch: 241; ), // latin small letter n with tilde, U+00F1 (entity: 'ograve'; ch: 242; ), // latin small letter o with grave, U+00F2 (entity: 'oacute'; ch: 243; ), // latin small letter o with acute, U+00F3 (entity: 'ocirc'; ch: 244; ), // latin small letter o with circumflex, U+00F4 (entity: 'otilde'; ch: 245; ), // latin small letter o with tilde, U+00F5 (entity: 'ouml'; ch: 246; ), // latin small letter o with diaeresis, U+00F6 (entity: 'divide'; ch: 247; ), // division sign, U+00F7 (entity: 'oslash'; ch: 248; ), // latin small letter o with stroke, = latin small letter o slash, U+00F8 (entity: 'ugrave'; ch: 249; ), // latin small letter u with grave, U+00F9 (entity: 'uacute'; ch: 250; ), // latin small letter u with acute, U+00FA (entity: 'ucirc'; ch: 251; ), // latin small letter u with circumflex, U+00FB (entity: 'uuml'; ch: 252; ), // latin small letter u with diaeresis, U+00FC (entity: 'yacute'; ch: 253; ), // latin small letter y with acute, U+00FD (entity: 'thorn'; ch: 254; ), // latin small letter thorn, U+00FE (entity: 'yuml'; ch: 255; ), // latin small letter y with diaeresis, U+00FF //24.3 Character entity references for symbols, mathematical symbols, and Greek letters (entity: 'fnof'; ch: 402; ), // latin small f with hook = function = florin, U+0192 (entity: 'Alpha'; ch: 913; ), // greek capital letter alpha, U+0391 (entity: 'Beta'; ch: 914; ), // greek capital letter beta, U+0392 (entity: 'Gamma'; ch: 915; ), // greek capital letter gamma, U+0393 (entity: 'Delta'; ch: 916; ), // greek capital letter delta, U+0394 (entity: 'Epsilon'; ch: 917; ), // greek capital letter epsilon, U+0395 (entity: 'Zeta'; ch: 918; ), // greek capital letter zeta, U+0396 (entity: 'Eta'; ch: 919; ), // greek capital letter eta, U+0397 (entity: 'Theta'; ch: 920; ), // greek capital letter theta, U+0398 (entity: 'Iota'; ch: 921; ), // greek capital letter iota, U+0399 (entity: 'Kappa'; ch: 922; ), // greek capital letter kappa, U+039A (entity: 'Lambda'; ch: 923; ), // greek capital letter lambda, U+039B (entity: 'Mu'; ch: 924; ), // greek capital letter mu, U+039C (entity: 'Nu'; ch: 925; ), // greek capital letter nu, U+039D (entity: 'Xi'; ch: 926; ), // greek capital letter xi, U+039E (entity: 'Omicron'; ch: 927; ), // greek capital letter omicron, U+039F (entity: 'Pi'; ch: 928; ), // greek capital letter pi, U+03A0 (entity: 'Rho'; ch: 929; ), // greek capital letter rho, U+03A1 // there is no Sigmaf, and no U+03A2 character either (entity: 'Sigma'; ch: 931; ), // greek capital letter sigma, U+03A3 (entity: 'Tau'; ch: 932; ), // greek capital letter tau, U+03A4 (entity: 'Upsilon'; ch: 933; ), // greek capital letter upsilon, U+03A5 (entity: 'Phi'; ch: 934; ), // greek capital letter phi, U+03A6 (entity: 'Chi'; ch: 935; ), // greek capital letter chi, U+03A7 (entity: 'Psi'; ch: 936; ), // greek capital letter psi, U+03A8 (entity: 'Omega'; ch: 937; ), // greek capital letter omega, U+03A9 (entity: 'alpha'; ch: 945; ), // greek small letter alpha, U+03B1 (entity: 'beta'; ch: 946; ), // greek small letter beta, U+03B2 (entity: 'gamma'; ch: 947; ), // greek small letter gamma, U+03B3 (entity: 'delta'; ch: 948; ), // greek small letter delta, U+03B4 (entity: 'epsilon'; ch: 949; ), // greek small letter epsilon, U+03B5 (entity: 'zeta'; ch: 950; ), // greek small letter zeta, U+03B6 (entity: 'eta'; ch: 951; ), // greek small letter eta, U+03B7 (entity: 'theta'; ch: 952; ), // greek small letter theta, U+03B8 (entity: 'iota'; ch: 953; ), // greek small letter iota, U+03B9 (entity: 'kappa'; ch: 954; ), // greek small letter kappa, U+03BA (entity: 'lambda'; ch: 955; ), // greek small letter lambda, U+03BB (entity: 'mu'; ch: 956; ), // greek small letter mu, U+03BC (entity: 'nu'; ch: 957; ), // greek small letter nu, U+03BD (entity: 'xi'; ch: 958; ), // greek small letter xi, U+03BE (entity: 'omicron'; ch: 959; ), // greek small letter omicron, U+03BF NEW (entity: 'pi'; ch: 960; ), // greek small letter pi, U+03C0 (entity: 'rho'; ch: 961; ), // greek small letter rho, U+03C1 (entity: 'sigmaf'; ch: 962; ), // greek small letter final sigma, U+03C2 (entity: 'sigma'; ch: 963; ), // greek small letter sigma, U+03C3 (entity: 'tau'; ch: 964; ), // greek small letter tau, U+03C4 (entity: 'upsilon'; ch: 965; ), // greek small letter upsilon, U+03C5 (entity: 'phi'; ch: 966; ), // greek small letter phi, U+03C6 (entity: 'chi'; ch: 967; ), // greek small letter chi, U+03C7 (entity: 'psi'; ch: 968; ), // greek small letter psi, U+03C8 (entity: 'omega'; ch: 969; ), // greek small letter omega, U+03C9 (entity: 'thetasym'; ch: 977; ), // greek small letter theta symbol, U+03D1 NEW (entity: 'upsih'; ch: 978; ), // greek upsilon with hook symbol, U+03D2 NEW (entity: 'piv'; ch: 982; ), // greek pi symbol, U+03D6 (entity: 'bull'; ch: 8226; ), // bullet = black small circle, U+2022 (entity: 'hellip'; ch: 8230; ), // horizontal ellipsis = three dot leader, U+2026 (entity: 'prime'; ch: 8242; ), // prime = minutes = feet, U+2032 (entity: 'Prime'; ch: 8243; ), // double prime = seconds = inches, U+2033 (entity: 'oline'; ch: 8254; ), // overline = spacing overscore, U+203E NEW (entity: 'frasl'; ch: 8260; ), // fraction slash, U+2044 NEW (entity: 'weierp'; ch: 8472; ), // script capital P = power set = Weierstrass p, U+2118 (entity: 'image'; ch: 8465; ), // blackletter capital I = imaginary part, U+2111 (entity: 'real'; ch: 8476; ), // blackletter capital R = real part symbol, U+211C (entity: 'trade'; ch: 8482; ), // trade mark sign, U+2122 (entity: 'alefsym'; ch: 8501; ), // alef symbol = first transfinite cardinal, U+2135 NEW (alef symbol is NOT the same as hebrew letter alef, U+05D0 although the same glyph could be used to depict both characters) (entity: 'larr'; ch: 8592; ), // leftwards arrow, U+2190 (entity: 'uarr'; ch: 8593; ), // upwards arrow, U+2191 (entity: 'rarr'; ch: 8594; ), // rightwards arrow, U+2192 (entity: 'darr'; ch: 8595; ), // downwards arrow, U+2193 (entity: 'harr'; ch: 8596; ), // left right arrow, U+2194 (entity: 'crarr'; ch: 8629; ), // downwards arrow with corner leftwards = carriage return, U+21B5 NEW (entity: 'lArr'; ch: 8656; ), // leftwards double arrow, U+21D0 (entity: 'uArr'; ch: 8657; ), // upwards double arrow, U+21D1 (entity: 'rArr'; ch: 8658; ), // rightwards double arrow, U+21D2 (entity: 'dArr'; ch: 8659; ), // downwards double arrow, U+21D3 (entity: 'hArr'; ch: 8660; ), // left right double arrow, U+21D4 (entity: 'forall'; ch: 8704; ), // for all, U+2200 (entity: 'part'; ch: 8706; ), // partial differential, U+2202 (entity: 'exist'; ch: 8707; ), // there exists, U+2203 (entity: 'empty'; ch: 8709; ), // empty set = null set = diameter, U+2205 (entity: 'nabla'; ch: 8711; ), // nabla = backward difference, U+2207 (entity: 'isin'; ch: 8712; ), // element of, U+2208 (entity: 'notin'; ch: 8713; ), // not an element of, U+2209 (entity: 'ni'; ch: 8715; ), // contains as member, U+220B (entity: 'prod'; ch: 8719; ), // n-ary product = product sign, U+220F (entity: 'sum'; ch: 8721; ), // n-ary sumation, U+2211 (entity: 'minus'; ch: 8722; ), // minus sign, U+2212 (entity: 'lowast'; ch: 8727; ), // asterisk operator, U+2217 (entity: 'radic'; ch: 8730; ), // square root = radical sign, U+221A (entity: 'prop'; ch: 8733; ), // proportional to, U+221D (entity: 'infin'; ch: 8734; ), // infinity, U+221E (entity: 'ang'; ch: 8736; ), // angle, U+2220 (entity: 'and'; ch: 8743; ), // logical and = wedge, U+2227 (entity: 'or'; ch: 8744; ), // logical or = vee, U+2228 (entity: 'cap'; ch: 8745; ), // intersection = cap, U+2229 (entity: 'cup'; ch: 8746; ), // union = cup, U+222A (entity: 'int'; ch: 8747; ), // integral, U+222B (entity: 'there4'; ch: 8756; ), // therefore, U+2234 (entity: 'sim'; ch: 8764; ), // tilde operator = varies with = similar to, U+223C (entity: 'cong'; ch: 8773; ), // approximately equal to, U+2245 (entity: 'asymp'; ch: 8776; ), // almost equal to = asymptotic to, U+2248 (entity: 'ne'; ch: 8800; ), // not equal to, U+2260 (entity: 'equiv'; ch: 8801; ), // identical to, U+2261 (entity: 'le'; ch: 8804; ), // less-than or equal to, U+2264 (entity: 'ge'; ch: 8805; ), // greater-than or equal to, U+2265 (entity: 'sub'; ch: 8834; ), // subset of, U+2282 (entity: 'sup'; ch: 8835; ), // superset of, U+2283 (entity: 'nsub'; ch: 8836; ), // not a subset of, U+2284 (entity: 'sube'; ch: 8838; ), // subset of or equal to, U+2286 (entity: 'supe'; ch: 8839; ), // superset of or equal to, U+2287 (entity: 'oplus'; ch: 8853; ), // circled plus = direct sum, U+2295 (entity: 'otimes'; ch: 8855; ), // circled times = vector product, U+2297 (entity: 'perp'; ch: 8869; ), // up tack = orthogonal to = perpendicular, U+22A5 (entity: 'sdot'; ch: 8901; ), // dot operator, U+22C5 (entity: 'lceil'; ch: 8968; ), // left ceiling = apl upstile, U+2308 (entity: 'rceil'; ch: 8969; ), // right ceiling, U+2309 (entity: 'lfloor'; ch: 8970; ), // left floor = apl downstile, U+230A (entity: 'rfloor'; ch: 8971; ), // right floor, U+230B (entity: 'lang'; ch: 9001; ), // left-pointing angle bracket = bra, U+2329 (entity: 'rang'; ch: 9002; ), // right-pointing angle bracket = ket, U+232A (entity: 'loz'; ch: 9674; ), // lozenge, U+25CA (entity: 'spades'; ch: 9824; ), // black spade suit, U+2660 (entity: 'clubs'; ch: 9827; ), // black club suit = shamrock, U+2663 (entity: 'hearts'; ch: 9829; ), // black heart suit = valentine, U+2665 (entity: 'diams'; ch: 9830; ), // black diamond suit, U+2666 //24.4 Character entity references for markup-significant and internationalization characters (entity: 'quot'; ch: 34; ), // quotation mark = APL quote, U+0022 (entity: 'amp'; ch: 38; ), // ampersand, U+0026 (entity: 'lt'; ch: 60; ), // less-than sign, U+003C (entity: 'gt'; ch: 62; ), // greater-than sign, U+003E (entity: 'OElig'; ch: 338; ), // latin capital ligature OE, U+0152 (entity: 'oelig'; ch: 339; ), // latin small ligature oe, U+0153 (entity: 'Scaron'; ch: 352; ), // latin capital letter S with caron, U+0160 (entity: 'scaron'; ch: 353; ), // latin small letter s with caron, U+0161 (entity: 'Yuml'; ch: 376; ), // latin capital letter Y with diaeresis, U+0178 (entity: 'circ'; ch: 710; ), // modifier letter circumflex accent, U+02C6 (entity: 'tilde'; ch: 732; ), // small tilde, U+02DC (entity: 'ensp'; ch: 8194; ), // en space, U+2002 (entity: 'emsp'; ch: 8195; ), // em space, U+2003 (entity: 'thinsp'; ch: 8201; ), // thin space, U+2009 (entity: 'zwnj'; ch: 8204; ), // zero width non-joiner, U+200C NEW RFC 2070 (entity: 'zwj'; ch: 8205; ), // zero width joiner, U+200D NEW RFC 2070 (entity: 'lrm'; ch: 8206; ), // left-to-right mark, U+200E NEW RFC 2070 (entity: 'rlm'; ch: 8207; ), // right-to-left mark, U+200F NEW RFC 2070 (entity: 'ndash'; ch: 8211; ), // en dash, U+2013 (entity: 'mdash'; ch: 8212; ), // em dash, U+2014 (entity: 'lsquo'; ch: 8216; ), // left single quotation mark, U+2018 (entity: 'rsquo'; ch: 8217; ), // right single quotation mark, U+2019 (entity: 'sbquo'; ch: 8218; ), // single low-9 quotation mark, U+201A NEW (entity: 'ldquo'; ch: 8220; ), // left double quotation mark, U+201C (entity: 'rdquo'; ch: 8221; ), // right double quotation mark, U+201D (entity: 'bdquo'; ch: 8222; ), // double low-9 quotation mark, U+201E NEW (entity: 'dagger'; ch: 8224; ), // dagger, U+2020 (entity: 'Dagger'; ch: 8225; ), // double dagger, U+2021 (entity: 'permil'; ch: 8240; ), // per mille sign, U+2030 (entity: 'lsaquo'; ch: 8249; ), // single left-pointing angle quotation mark, U+2039 (entity: 'rsaquo'; ch: 8250; ), // single right-pointing angle quotation mark, U+203A (entity: 'euro'; ch: 8364; ) // euro sign, U+20AC NEW ); var i: Integer; len: Integer; nChar: UCS4Char; runEntity: string; begin { EntityRef ::= '&' Name ';' Name ::= NameStartChar (NameChar)* NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] } Result := ''; CharRef := ''; len := Length(sValue) - StartIndex + 1; if len < 4 then Exit; i := StartIndex; if sValue[i] <> '&' then Exit; Inc(i); if not IsNameStartChar(sValue[i]) then Exit; Inc(i); while IsNameChar(sValue[i]) do begin Inc(i); if i > Length(sValue) then Exit; end; if sValue[i] <> ';' then Exit; charRef := Copy(sValue, StartIndex, (i-StartIndex)+1); for i := Low(HtmlEntities) to High(HtmlEntities) do begin //now strip off the & and ; runEntity := Copy(charRef, 2, Length(charRef)-2); //Case sensitive check; as entites are case sensitive if runEntity = HtmlEntities[i].entity then begin nChar := HtmlEntities[i].ch; Result := UCS4CharToString(nChar); Exit; end; end; //It looks like a valid entity reference, but we don't recognize the text. //It's probably garbage that we might be able to fix if IsDebuggerPresent then OutputDebugString(PChar('HtmlDecode: Unknown HTML entity reference: "'+charRef+'"')); end; var i: Integer; entity: string; entityChar: string; begin i := 1; Result := ''; while i <= Length(s) do begin if s[i] <> '&' then begin Result := Result + s[i]; Inc(i); Continue; end; entityChar := GetCharRef(s, i, {out}entity); if entityChar <> '' then begin Result := Result + entityChar; Inc(i, Length(entity)); Continue; end; entityChar := GetEntityRef(s, i, {out}entity); if entityChar <> '' then begin Result := Result + entityChar; Inc(i, Length(entity)); Continue; end; Result := Result + s[i]; Inc(i); end; end; function THtmlReader.ReadAttrNode: Boolean; var attrName: TDomString; begin Result := false; SkipWhiteSpaces; attrName := LowerCase(GetToken(attrNameDelimiter)); if attrName = '' then Exit; SetNodeName(attrName); DoAttributeStart(attrName); FState := rsBeforeValue; FQuotation := 0; Result := True end; function THtmlReader.ReadAttrTextNode: Boolean; var start: Integer; attrValue: UnicodeString; begin Result := False; start := FPosition; while (not IsEOF) and IsAttrTextChar do Inc(FPosition); if FPosition = start then Exit; FNodeType := TEXT_NODE; attrValue := Copy(FHtmlStr, start, FPosition - start); attrValue := HtmlDecode(attrValue); //decode entity references FNodeValue:= attrValue; DoAttributeValue(FNodeValue); Result := true end; function THtmlReader.ReadCharacterData: Boolean; var startPos: Integer; begin Inc(FPosition, Length(CDataStartStr)); startPos := FPosition; Result := SkipTo(CDataEndStr); if Result then begin FNodeType := CDATA_SECTION_NODE; FNodeValue := Copy(FHtmlStr, startPos, FPosition - startPos - Length(CDataEndStr)); DoCDataSection(FNodeValue); end end; function THtmlReader.ReadComment: Boolean; var startPos: Integer; begin Inc(FPosition, Length(CommentStartStr)); startPos := FPosition; Result := SkipTo(CommentEndStr); if Result then begin FNodeType := COMMENT_NODE; FNodeValue := Copy(FHtmlStr, startPos, FPosition - startPos - Length(CommentEndStr)); DoComment(FNodeValue); end end; function THtmlReader.ReadDocumentType: Boolean; var name: TDomString; keyword: TDomString; publicID, systemID: TDomString; begin { Valid reader properties during the OnDocType event: - NodeType e.g. DOCUMENT_TYPE_NODE (10) - NodeName e.g. "html" - PublicID e.g. "-//W3C//DTD HTML 4.01//EN" - SystemID e.g. "http://www.w3.org/TR/html4/strict.dtd" Recommended list of Doctype declarations ----------------------------------------- From: https://www.w3.org/QA/2002/04/valid-dtd-list.html HTML 5: <!DOCTYPE HTML> HTML 4.01 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> XHTML 1.0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> MathML 2.0 <!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd"> MathML 1.0 <!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd"> SVG 1.1 Full <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> } Result := False; Inc(FPosition, Length(DocTypeStartStr)); SkipWhiteSpaces; name := GetToken(tagNameDelimiter); //"HTML" if name = '' then Exit; //https://html.spec.whatwg.org/#before-doctype-name-state //doctype names are to be lowercased. //Set the token's name to the lowercase version of the current input character (add 0x0020 to the character's code point) name := Lowercase(name); SkipWhiteSpaces; keyword := GetToken(tagNameDelimiter); //"PUBLIC" or "SYSTEM" SkipWhiteSpaces; if SameText(keyword, 'PUBLIC') then begin if not ReadQuotedValue({var}publicID) then // "-//x3C//DTD HTML 4.01 Transitional//EN" publicID := ''; //12/20/2021 Support for '<!doctype html>' where there is no public ID end; SkipWhiteSpaces; //https://html.spec.whatwg.org/#before-doctype-system-identifier-state //Both QUOTATION MARK and APOSTROPHE are allowed if (FHtmlStr[FPosition] = '"') or (FHtmlStr[FPosition] = '''') then begin if not ReadQuotedValue({var}systemID) then systemID := ''; end; Result := SkipTo(DocTypeEndStr); FNodeType := DOCUMENT_TYPE_NODE; SetNodeName(name); FPublicID := publicID; FSystemID := systemID; DoDocType(name, publicID, systemID); end; function THtmlReader.ReadElementNode: Boolean; var tagName: TDomString; begin Result := False; if FPosition > Length(FHtmlStr) then Exit; tagName := GetToken(tagNameDelimiter); if tagName = '' then Exit; FNodeType := ELEMENT_NODE; SetNodeName(tagName); FState := rsBeforeAttr; DoElementStart(tagName); Result := True; end; function THtmlReader.ReadEndElementNode: Boolean; var tagName: TDomString; begin Result := false; Inc(FPosition); if IsEOF then Exit; tagName := LowerCase(GetToken(tagNameDelimiter)); if tagName = '' then Exit; Result := SkipTo(WideChar(endTagChar)); if Result then begin FNodeType := END_ELEMENT_NODE; SetNodeName(tagName); DoEndElement(tagName); Result := true end end; function THtmlReader.ReadQuotedValue(var Value: TDomString): Boolean; var quotedChar: WideChar; start: Integer; begin quotedChar := FHtmlStr[FPosition]; //the quotation character will usually be " (quotation mark), but can also be ' (apostrophe) Inc(FPosition); start := FPosition; Result := SkipTo(quotedChar); if Result then Value := Copy(FHtmlStr, start, FPosition - start-1); // -1 ==> don't include the trailing quote in the returned string end; function THtmlReader.ReadSpecialNode: Boolean; begin Result := false; Inc(FPosition); if IsEOF then Exit; if IsStartDocumentType then Result := ReadDocumentType else if IsStartCharacterData then Result := ReadCharacterData else if IsStartComment then Result := ReadComment end; function THtmlReader.ReadTagNode: Boolean; var currPos: Integer; begin Result := False; currPos := FPosition; Inc(FPosition); if IsEOF then Exit; if IsSlashChar then Result := ReadEndElementNode else if IsSpecialTagChar then Result := ReadSpecialNode else Result := ReadElementNode; if not Result then FPosition := currPos; end; function THtmlReader.SkipTo(const Signature: TDomString): Boolean; begin while FPosition <= Length(FHtmlStr) do begin if Match(Signature, false) then begin Inc(FPosition, Length(Signature)); Result := true; Exit end; Inc(FPosition) end; Result := false end; procedure THtmlReader.DoAttributeEnd; begin LogFmt('AttributeEnd', []); if Assigned(OnAttributeEnd) then OnAttributeEnd(Self); end; procedure THtmlReader.DoAttributeStart(const AttributeName: UnicodeString); begin LogFmt('AttributeStart (Name="%s")', [AttributeName]); if Assigned(OnAttributeStart) then OnAttributeStart(Self); end; procedure THtmlReader.DoAttributeValue(const AttributeValue: UnicodeString); begin LogFmt('AttributeValue (Value="%s")', [AttributeValue]); if Assigned(OnAttributeValue) then OnAttributeValue(Self); end; procedure THtmlReader.DoCDataSection(const NodeValue: UnicodeString); begin { NOTE: HTML does not normally allow CDATA sections. https://html.spec.whatwg.org/#cdata-sections > CDATA sections can only be used in foreign content (MathML or SVG). > In this example, a CDATA section is used to escape the contents of a MathML ms element > > <p>You can add a string to a number, but this stringifies the number:</p> > <math> > <ms><![CDATA[x<y]]></ms> > <mo>+</mo> > <mn>3</mn> > <mo>=</mo> > <ms><![CDATA[x<y3]]></ms> > </math> } LogFmt('CDataSection (NodeValue="%s")', [NodeValue]); if Assigned(OnCDataSection) then OnCDataSection(Self); end; procedure THtmlReader.DoComment(const NodeValue: UnicodeString); begin LogFmt('Comment (NodeValue="%s")', [NodeValue]); if Assigned(OnComment) then OnComment(Self); end; procedure THtmlReader.DoDocType(const Name, PublicID, SystemID: UnicodeString); begin LogFmt('DocType (Name="%s", PublicID="%s", SystemID="%s")', [Name, PublicID, SystemID]); if Assigned(OnDocType) then OnDocType(Self); end; procedure THtmlReader.DoElementEnd(IsEmptyElement: Boolean); begin { When we've reached the end of an element's start tag. <DIV lang="en" id="pnlMain"> ^__ IsEmtpyElement: False <BR/> ^__ IsEmptyElement: True } LogFmt('ElementEnd (IsEmptyElement=%s)', [SBoolean[IsEmptyElement]]); if Assigned(OnElementEnd) then OnElementEnd(Self); end; procedure THtmlReader.DoElementStart(const TagName: UnicodeString); begin { Occurs on an element start tag. } LogFmt('ElementStart (Name="%s")', [TagName]); if Assigned(OnElementStart) then OnElementStart(Self); end; procedure THtmlReader.DoEndElement(const TagName: UnicodeString); begin { Occurs on an element's end tag. } LogFmt('EndElement (Name="%s")', [TagName]); if Assigned(OnEndElement) then OnEndElement(Self); end; procedure THtmlReader.DoTextNode(const NodeValue: UnicodeString); var s: UnicodeString; begin // LogFmt('TextNode(NodeValue="%s")', [NodeValue]); LogBack(function: string begin s := NodeValue; s := StringReplace(s, #13#10, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, #13, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, #10, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, ' ', #$2423, [rfReplaceAll]); //U+2423 OPEN BOX Result := 'TextNode (NodeValue="'+s+'")'; end); if Assigned(OnTextNode) then OnTextNode(Self); end; function THtmlReader.read: Boolean; begin Result := False; //Reset current state FNodeType := NONE; FPrefix := ''; FLocalName := ''; FNodeValue := ''; FPublicID := ''; FSystemID := ''; FIsEmptyElement := False; if IsEOF then Exit; Result := True; if FState in [rsBeforeValue, rsInValue, rsInQuotedValue] then begin if ReadValueNode then Exit; if FState = rsInQuotedValue then Inc(FPosition); FNodeType := ATTRIBUTE_NODE; DoAttributeEnd(); FState := rsBeforeAttr; end else if FState = rsBeforeAttr then begin if ReadAttrNode then Exit; ReadElementTail; FState := rsInitial; end else if IsStartTagChar then begin if ReadTagNode then Exit; Inc(FPosition); end else ReadTextNode; end; procedure THtmlReader.ReadTextNode; var start: Integer; data: TDomString; begin start := FPosition; repeat Inc(FPosition) until IsEOF or IsStartMarkupChar; FNodeType := TEXT_NODE; data := Copy(FHtmlStr, start, FPosition - start); data := HtmlDecode(data); //decode entity references FNodeValue:= data; DoTextNode(FNodeValue); end; function THtmlReader.ReadValueNode: Boolean; begin Result := False; if FState = rsBeforeValue then begin SkipWhiteSpaces; if IsEOF then Exit; if not IsEqualChar then Exit; Inc(FPosition); SkipWhiteSpaces; if IsEOF then Exit; if IsQuotation then begin FQuotation := Ord(FHtmlStr[FPosition]); Inc(FPosition); FState := rsInQuotedValue end else FState := rsInValue end; if IsEOF then Exit; Result := ReadAttrTextNode; end; procedure THtmlReader.ReadElementTail; begin { Reading the closing > of an element's opening tag: <SPAN> ^ If the element is self-closing (i.e. "<SPAN/>") then IsElementEmpty will be true Reader properties: - NodeType (ELEMNET_NODE) - IsElementEmpty: if the element was self-closed } SkipWhiteSpaces; if (FPosition <= Length(FHtmlStr)) and IsSlashChar then begin FIsEmptyElement := True; Inc(FPosition) end; SkipTo(WideChar(endTagChar)); FNodeType := ELEMENT_NODE; DoElementEnd(IsEmptyElement); end; procedure THtmlReader.SetHtmlStr(const Value: TDomString); begin FHtmlStr := Value; FPosition := 1 end; procedure THtmlReader.SetNodeName(Value: TDomString); var I: Integer; begin { Split Value into Prefix and LocalName NodeName is sythesized as Prefix:LocalName If Prefix is empty, then NodeName is just LocalName. } I := Pos(':', Value); if I > 0 then begin FPrefix := Copy(Value, 1, I - 1); FLocalName := Copy(Value, I + 1, Length(Value) - I) end else begin FPrefix := ''; FLocalName := Value end end; procedure THtmlReader.SkipWhiteSpaces; begin while (FPosition <= Length(FHtmlStr)) and (Ord(FHtmlStr[FPosition]) in whiteSpace) do Inc(FPosition) end; end.
{ Procedure Usun ( ? tab:Tklaser, nazwa:String ); usuwa maksymalnie jeden element z tablicy o zadanej nazwie, procedure Modyfikuj ( tab:TKlaser, indeks:Integer ); modyfikuje w tablicy jeden element o indeksie zadanym procedure dodaj2 ( tKlaser ) dodaje znaczek w pierwsze wolne miejsce Procedure zapisztxt ( tab tKlaser ) zapisuje dane do pliku TXT, w postaci # nazwa rok prod nominal } program project1; uses filatel, Crt; const sciezka: string = 'baza'; sciezkaTxt: string = 'baza.txt'; var komendy : set of Char = ['U', 'u', 'D', 'd', 'M', 'm', 'Z', 'z', 'T', 't', 'O', 'o', Char(0)]; klaser1: tKlaser; tmpNazwaZnaczka: string; tmpIndeksZnaczka: integer; sterowanie: char = char(0); begin Randomize(); klaser1 := DodajZnaczki(); while sterowanie <> char(27) do begin if ( sterowanie in komendy ) then begin ClrScr(); TextColor(LightBlue); writeln('(U)sun / (D)odaj / (M)odyfikuj / (Z)apisz / zapisz(T)xt / (O)dczytaj / (ESC)'); TextColor(White); WypiszKlaser(klaser1); end; sterowanie := ReadKey(); case sterowanie of 'U', 'u': begin WriteLn(); Write('Podaj nazwe zaczka, ktorego chcesz usunac: '); readln(tmpNazwaZnaczka); UsunZnaczek(klaser1, tmpNazwaZnaczka); end; 'D', 'd': DodajZnaczek2(klaser1); 'M', 'm': begin WriteLn(); Write('Indeks znaczka ktorego chcesz modyfikowac'); ReadLn(tmpIndeksZnaczka); ModyfikujZnaczek(klaser1, tmpIndeksZnaczka); end; 'Z', 'z': ZapiszDoPliku(klaser1, sciezka); 'T', 't': ZapiszDoPlikuTXT(klaser1, sciezkaTxt); 'O', 'o': OdczytajDane(klaser1, sciezka); end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Layout The MIT License Copyright: Copyright (C) 2017 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author T2Ti @version 2.0 *******************************************************************************} unit UEtiquetaLayout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, EtiquetaLayoutVO, EtiquetaLayoutController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, JvBaseEdits, Controller, Biblioteca; type TFEtiquetaLayout = class(TFTelaCadastro) EditFormatoPapel: TLabeledEdit; EditCodigoFabricante: TLabeledEdit; EditIdFormatoPapel: TLabeledCalcEdit; EditQuantidade: TLabeledCalcEdit; EditQuantidadeHorizontal: TLabeledCalcEdit; EditMargemSuperior: TLabeledCalcEdit; EditQuantidadeVertical: TLabeledCalcEdit; EditMargemInferior: TLabeledCalcEdit; EditMargemEsquerda: TLabeledCalcEdit; EditMargemDireita: TLabeledCalcEdit; EditEspacamentoHorizontal: TLabeledCalcEdit; EditEspacamentoVertical: TLabeledCalcEdit; procedure FormCreate(Sender: TObject); procedure EditIdFormatoPapelKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FEtiquetaLayout: TFEtiquetaLayout; implementation uses ULookup, EtiquetaFormatoPapelController, EtiquetaFormatoPapelVO; {$R *.dfm} {$REGION 'Infra'} procedure TFEtiquetaLayout.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TEtiquetaLayoutVO; ObjetoController := TEtiquetaLayoutController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFEtiquetaLayout.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdFormatoPapel.SetFocus; end; end; function TFEtiquetaLayout.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdFormatoPapel.SetFocus; end; end; function TFEtiquetaLayout.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('EtiquetaLayoutController.TEtiquetaLayoutController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('EtiquetaLayoutController.TEtiquetaLayoutController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFEtiquetaLayout.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TEtiquetaLayoutVO.Create; TEtiquetaLayoutVO(ObjetoVO).IdFormatoPapel := EditIdFormatoPapel.AsInteger; TEtiquetaLayoutVO(ObjetoVO).CodigoFabricante := EditCodigoFabricante.Text; TEtiquetaLayoutVO(ObjetoVO).Quantidade := EditQuantidade.AsInteger; TEtiquetaLayoutVO(ObjetoVO).QuantidadeHorizontal := EditQuantidadeHorizontal.AsInteger; TEtiquetaLayoutVO(ObjetoVO).QuantidadeVertical := EditQuantidadeVertical.AsInteger; TEtiquetaLayoutVO(ObjetoVO).MargemSuperior := EditMargemSuperior.AsInteger; TEtiquetaLayoutVO(ObjetoVO).MargemInferior := EditMargemInferior.AsInteger; TEtiquetaLayoutVO(ObjetoVO).MargemEsquerda := EditMargemEsquerda.AsInteger; TEtiquetaLayoutVO(ObjetoVO).MargemDireita := EditMargemDireita.AsInteger; TEtiquetaLayoutVO(ObjetoVO).EspacamentoHorizontal := EditEspacamentoHorizontal.AsInteger; TEtiquetaLayoutVO(ObjetoVO).EspacamentoVertical := EditEspacamentoVertical.AsInteger; if StatusTela = stInserindo then begin TController.ExecutarMetodo('EtiquetaLayoutController.TEtiquetaLayoutController', 'Insere', [TEtiquetaLayoutVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TEtiquetaLayoutVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('EtiquetaLayoutController.TEtiquetaLayoutController', 'Altera', [TEtiquetaLayoutVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controles de Grid'} procedure TFEtiquetaLayout.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TEtiquetaLayoutVO(TController.BuscarObjeto('EtiquetaLayoutController.TEtiquetaLayoutController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdFormatoPapel.AsInteger := TEtiquetaLayoutVO(ObjetoVO).IdFormatoPapel; EditCodigoFabricante.Text := TEtiquetaLayoutVO(ObjetoVO).CodigoFabricante; EditQuantidade.AsInteger := TEtiquetaLayoutVO(ObjetoVO).Quantidade; EditQuantidadeHorizontal.AsInteger := TEtiquetaLayoutVO(ObjetoVO).QuantidadeHorizontal; EditQuantidadeVertical.AsInteger := TEtiquetaLayoutVO(ObjetoVO).QuantidadeVertical; EditMargemSuperior.AsInteger := TEtiquetaLayoutVO(ObjetoVO).MargemSuperior; EditMargemInferior.AsInteger := TEtiquetaLayoutVO(ObjetoVO).MargemInferior; EditMargemEsquerda.AsInteger := TEtiquetaLayoutVO(ObjetoVO).MargemEsquerda; EditMargemDireita.AsInteger := TEtiquetaLayoutVO(ObjetoVO).MargemDireita; EditEspacamentoHorizontal.AsInteger := TEtiquetaLayoutVO(ObjetoVO).EspacamentoHorizontal; EditEspacamentoVertical.AsInteger := TEtiquetaLayoutVO(ObjetoVO).EspacamentoVertical; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFEtiquetaLayout.EditIdFormatoPapelKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdFormatoPapel.Value <> 0 then Filtro := 'ID = ' + EditIdFormatoPapel.Text else Filtro := 'ID=0'; try EditIdFormatoPapel.Clear; EditFormatoPapel.Clear; if not PopulaCamposTransientes(Filtro, TEtiquetaFormatoPapelVO, TEtiquetaFormatoPapelController) then PopulaCamposTransientesLookup(TEtiquetaFormatoPapelVO, TEtiquetaFormatoPapelController); if CDSTransiente.RecordCount > 0 then begin EditIdFormatoPapel.Text := CDSTransiente.FieldByName('ID').AsString; EditFormatoPapel.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditCodigoFabricante.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
unit UDMCia; interface uses SysUtils, Classes, DB, DBTables, Variants, Dialogs, DBIProcs; type TDMCia = class(TDataModule) tCia: TTable; tCiaCodigo: TIntegerField; tCiaNome: TStringField; tCiaObs: TMemoField; tCiaDtCadastro: TDateField; tCiaItens: TTable; tCiaItensCodigo: TIntegerField; tCiaItensItem: TIntegerField; tCiaItensCodProduto: TIntegerField; tCiaItensPreco: TFloatField; tCiaItensProcesso: TStringField; dsCia: TDataSource; dsCiaItens: TDataSource; tCiaItensCodConstrucao: TIntegerField; tConstrucao2: TTable; tConstrucao2Codigo: TIntegerField; tConstrucao2Nome: TStringField; tCiaItenslkReferencia: TStringField; tCiaItenslkNomeConstrucao: TStringField; procedure tCiaAfterPost(DataSet: TDataSet); procedure tCiaItensAfterPost(DataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var DMCia: TDMCia; implementation uses UDM1; {$R *.dfm} procedure TDMCia.tCiaAfterPost(DataSet: TDataSet); begin DBISaveChanges(tCia.Handle); end; procedure TDMCia.tCiaItensAfterPost(DataSet: TDataSet); begin DBISaveChanges(tCiaItens.Handle); end; procedure TDMCia.DataModuleCreate(Sender: TObject); begin tConstrucao2.Open; tCia.Open; tCiaItens.Open; end; end.
unit InfraVCLCommand; interface uses InfraMVPVCLIntf, InfraValueTypeIntf, InfraCommand; (* *** type TCloseFormCommand = class(TCommand, ICloseFormCommand) protected procedure Execute(const Parameters: IInfraList); override; end; *) procedure RegisterOnReflection; implementation uses InfraCommonIntf, InfraMVPIntf; procedure RegisterOnReflection; begin with TypeService do begin (* *** RegisterNewType(ICloseFormCommand, 'CloseForm', TCloseFormCommand, ICommand, GetTypeInfo(ICommand)); RegisterNewType(ICloseFormWithOKCommand, 'CloseFormWithOK', TCloseFormWithOKCommand, ICommand, GetTypeInfo(ICommand)); *) end; end; (* *** { TCloseFormCommand } procedure TCloseFormCommand.Execute(const Parameters: IInfraList); begin inherited Execute(Parameters); ((Owner as IPresenter).View as IVCLCustomFormView).Close; end; *) end.
unit Controller.Form.Login; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniGUIApplication, uniGUIBaseClasses, uniGUIVars, View.Form.Login; type TControllerFormLogin = class private type TViewFormLogin = class(View.Form.Login.TViewFormLogin) strict private FController: TControllerFormLogin; public constructor Create(Aowner: TComponent); override; end; strict private FView: TControllerFormLogin.TViewFormLogin; procedure BindView; procedure UniFormDestroy(Sender: TObject); procedure UniFormCreate(Sender: TObject); procedure BtnLoginClick(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); public constructor Create(Aview: TControllerFormLogin.TViewFormLogin); reintroduce; end; implementation constructor TControllerFormLogin.TViewFormLogin.Create(Aowner: TComponent); begin inherited Create(Aowner); FController := TControllerFormLogin.Create(Self); end; constructor TControllerFormLogin.Create(Aview: TControllerFormLogin.TViewFormLogin); begin inherited Create; FView := Aview; BindView; end; procedure TControllerFormLogin.BindView; begin FView.OnCreate := UniFormCreate; FView.BtnLogin.OnClick := Self.BtnLoginClick; FView.BtnCancelar.OnClick := Self.BtnCancelarClick; FView.OnDestroy := Self.UniFormDestroy; end; procedure TControllerFormLogin.BtnLoginClick(Sender: TObject); begin FView.ModalResult := mrOk; end; procedure TControllerFormLogin.BtnCancelarClick(Sender: TObject); begin FView.ModalResult := mrCancel; end; procedure TControllerFormLogin.UniFormCreate(Sender: TObject); begin FView.BtnLogin.Caption := 'Login'; end; procedure TControllerFormLogin.UniFormDestroy(Sender: TObject); begin Self.Free; end; initialization RegisterAppFormClass(TControllerFormLogin.TViewFormLogin); end.
unit DW.MultiReceiver.Android; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Embarcadero; type TMultiReceiver = class; TMultiReceiverListener = class(TJavaLocal, JFMXBroadcastReceiverListener) private FMultiReceiver: TMultiReceiver; public { JFMXBroadcastReceiverListener } procedure onReceive(context: JContext; intent: JIntent); cdecl; public constructor Create(const AMultiReceiver: TMultiReceiver); end; TMultiReceiver = class(TObject) private FBroadcastReceiver: JFMXBroadcastReceiver; FIntentFilter: JIntentFilter; FLocal: Boolean; FReceiverListener: TMultiReceiverListener; protected procedure Receive(context: JContext; intent: JIntent); virtual; abstract; procedure ConfigureActions; virtual; abstract; property IntentFilter: JIntentFilter read FIntentFilter; public constructor Create(const ALocal: Boolean = False); destructor Destroy; override; end; implementation uses // Android Androidapi.Helpers, // DW DW.Androidapi.JNI.SupportV4; { TMultiReceiverListener } constructor TMultiReceiverListener.Create(const AMultiReceiver: TMultiReceiver); begin inherited Create; FMultiReceiver := AMultiReceiver; end; procedure TMultiReceiverListener.onReceive(context: JContext; intent: JIntent); begin FMultiReceiver.Receive(context, intent); end; { TMultiReceiver } constructor TMultiReceiver.Create(const ALocal: Boolean = False); begin inherited Create; FLocal := ALocal; FReceiverListener := TMultiReceiverListener.Create(Self); FBroadcastReceiver := TJFMXBroadcastReceiver.JavaClass.init(FReceiverListener); FIntentFilter := TJIntentFilter.JavaClass.init; ConfigureActions; if not FLocal then TAndroidHelper.Context.registerReceiver(FBroadcastReceiver, FIntentFilter) else TJLocalBroadcastManager.JavaClass.getInstance(TAndroidHelper.Context).registerReceiver(FBroadcastReceiver, FIntentFilter); end; destructor TMultiReceiver.Destroy; begin if not FLocal then TAndroidHelper.Context.unregisterReceiver(FBroadcastReceiver) else TJLocalBroadcastManager.JavaClass.getInstance(TAndroidHelper.Context).unregisterReceiver(FBroadcastReceiver); FBroadcastReceiver := nil; end; end.
unit Game; interface uses AvL, avlUtils, avlEventBus, avlMath, avlVectors, VSECore, VSEGUI, Scene, GameData, GameObjects; type TPlayer = class; TGameStage = class; TGame = class private FScene: TScene; FStage: TGameStage; FActivePlayer: TPlayer; FCharacters: array of TCharacter; FPlayers: array of TPlayer; FMissions: TDeck; function GetCharacter(const Name: string): TCharacter; function GetPlayer(const Name: string): TPlayer; procedure SetActivePlayer(const Value: TPlayer); public constructor Create(Scene: TScene); destructor Destroy; override; procedure Update; property Character[const Name: string]: TCharacter read GetCharacter; property Player[const Name: string]: TPlayer read GetPlayer; property Missions: TDeck read FMissions; property Scene: TScene read FScene; property Stage: TGameStage read FStage; property ActivePlayer: TPlayer read FActivePlayer write SetActivePlayer; end; TPlayerAction = class; TPlayerActionsArray = array of TPlayerAction; TPlayer = class private protected FName: string; FCharacter: TCharacter; FVictoryChip: TChip; FGame: TGame; FArguments: Integer; FAvailActions: TPlayerActionsArray; FObjects: TGameObjectsArray; FDeck: TDeck; function VictoryPos(Arguments: Integer): TVector3D; procedure SetArguments(Value: Integer); public Resources: array[TResourceType] of Integer; constructor Create(Game: TGame; const Name: string); destructor Destroy; override; procedure Update; virtual; procedure AddAction(Action: TPlayerAction); procedure RemoveAction(Action: TPlayerAction); procedure ClearActions; property Game: TGame read FGame; property Name: string read FName; property Character: TCharacter read FCharacter; property Arguments: Integer read FArguments write SetArguments; property AvailActions: TPlayerActionsArray read FAvailActions; property Objects: TGameObjectsArray read FObjects; property Deck: TDeck read FDeck; end; TPlayerAction = class protected FPlayer: TPlayer; FForm: TGUIForm; procedure Complete; public constructor Create(Player: TPlayer); destructor Destroy; override; property Form: TGUIForm read FForm; end; TGameStage = class protected FGame: TGame; FNextStage: TGameStage; public constructor Create(Game: TGame); function Update: TGameStage; virtual; end; const GameOnActivePlayerChanged = 'Game.OnActivePlayerChanged'; //<Out> PrevPlayer, NewPlayer GameOnMouseEvent = 'Game.OnMouseEvent'; //<Out> Event, Mouse3D PlayerOnActionsChanged = 'Player.OnActionsChanged'; //<Out> PlayerOnActionCompleted = 'Player.OnActionCompleted'; //<Out> Action implementation uses GameStages, Missions {$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF}; { TGame } constructor TGame.Create(Scene: TScene); var i: Integer; begin inherited Create; EventBus.RegisterEvent(GameOnActivePlayerChanged); FScene := Scene; for i := Low(TQuarterIndex) to High(TQuarterIndex) do FScene.Objects.Add(TQuarter.Create(i)); SetLength(FCharacters, Length(Characters)); for i := 0 to High(FCharacters) do with Characters[i] do FCharacters[i] := TCharacter.Create(Name, Profile^); SetLength(FPlayers, Length(PlayerNames)); for i := 0 to High(PlayerNames) do FPlayers[i] := TPlayer.Create(Self, PlayerNames[i]); FMissions := TDeck.Create; CreateMissions(FMissions); FStage := TStageStart.Create(Self); end; destructor TGame.Destroy; var i: Integer; begin FScene.Objects.Clear; FStage.Free; FAN(FMissions); for i := 0 to High(FPlayers) do FAN(FPlayers[i]); Finalize(FPlayers); Finalize(FCharacters); inherited; end; procedure TGame.Update; var i: Integer; begin FStage := FStage.Update; for i := 0 to High(FPlayers) do FPlayers[i].Update; end; function TGame.GetCharacter(const Name: string): TCharacter; var i: Integer; begin for i := 0 to High(FCharacters) do if FCharacters[i].Name = Name then begin Result := FCharacters[i]; Exit; end; Result := nil; end; function TGame.GetPlayer(const Name: string): TPlayer; var i: Integer; begin for i := 0 to High(FPlayers) do if FPlayers[i].Name = Name then begin Result := FPlayers[i]; Exit; end; Result := nil; end; procedure TGame.SetActivePlayer(const Value: TPlayer); var PrevPlayer: TPlayer; begin PrevPlayer := FActivePlayer; FActivePlayer := Value; EventBus.SendEvent(GameOnActivePlayerChanged, Self, [PrevPlayer, Value]); end; { TPlayer } constructor TPlayer.Create(Game: TGame; const Name: string); begin inherited Create; FName := Name; FGame := Game; FCharacter := FGame.GetCharacter(FName); FObjects := TGameObjectsArray.Create; FDeck := TDeck.Create; if Name <> SPlague then begin FVictoryChip := TChip.Create(FName, 0.75); FVictoryChip.Pos := VictoryPos(3); EventBus.SendEvent(SceneAddObject, Self, [FVictoryChip]); end; end; destructor TPlayer.Destroy; begin ClearActions; FAN(FDeck); FAN(FObjects); inherited; end; procedure TPlayer.Update; begin end; procedure TPlayer.AddAction(Action: TPlayerAction); begin SetLength(FAvailActions, Length(FAvailActions) + 1); FAvailActions[High(FAvailActions)] := Action; EventBus.SendEvent(PlayerOnActionsChanged, Self, []); end; procedure TPlayer.RemoveAction(Action: TPlayerAction); var i, j: Integer; begin for i := 0 to High(FAvailActions) do if FAvailActions[i] = Action then begin for j := i to High(FAvailActions) - 1 do FAvailActions[j] := FAvailActions[j + 1]; SetLength(FAvailActions, Length(FAvailActions) - 1); EventBus.SendEvent(PlayerOnActionsChanged, Self, []); Break; end; end; procedure TPlayer.ClearActions; begin while Length(FAvailActions) > 0 do FAvailActions[High(FAvailActions)].Free; EventBus.SendEvent(PlayerOnActionsChanged, Self, []); end; function TPlayer.VictoryPos(Arguments: Integer): TVector3D; var i: Integer; begin for i := 0 to High(VictoryTracks) do with VictoryTracks[i] do if Name = FName then Result := Track[Max(0, Min(Arguments - 1, High(Track)))]; end; procedure TPlayer.SetArguments(Value: Integer); begin FArguments := Max(1, Value); FVictoryChip.AddAnimationStep(aaMoveTo, VictoryPos(FArguments), 100); end; { TPlayerAction } procedure TPlayerAction.Complete; begin EventBus.SendEvent(PlayerOnActionCompleted, FPlayer, [Self]); Free; end; constructor TPlayerAction.Create(Player: TPlayer); begin inherited Create; FPlayer := Player; FPlayer.AddAction(Self); end; destructor TPlayerAction.Destroy; begin FPlayer.RemoveAction(Self); inherited; end; { TGameStage } constructor TGameStage.Create(Game: TGame); begin inherited Create; FGame := Game; end; function TGameStage.Update: TGameStage; begin if Assigned(FNextStage) then begin Result := FNextStage; Free; end else Result := Self; end; end.
{***************************************************************************} { } { DMemCached - Copyright (C) 2014 - Víctor de Souza Faria } { } { victor@victorfaria.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DMemcached.Util; interface uses SysUtils; function UInt64ToByte(value: UInt64): TBytes; function ByteToUInt64(value: TBytes): UInt64; function UInt32ToByte(value: UInt32): TBytes; function ByteToUInt32(value: TBytes): UInt32; function WordToByte(value: Word): TBytes; function ByteToWord(value: TBytes): Word; implementation function WordToByte(value: Word): TBytes; begin SetLength(Result, 2); Result[0] := (value shr 8); Result[1] := (value); end; function ByteToWord(value: TBytes): Word; begin Result := (value[0] shl 8) or value[1]; end; function UInt32ToByte(value: UInt32): TBytes; begin SetLength(Result, 4); Result[0] := (value shr 24); Result[1] := (value shr 16); Result[2] := (value shr 8); Result[3] := (value); end; function ByteToUInt32(value: TBytes): UInt32; begin Result := (value[0] shl 24) or ( value[1] shl 16) or (value[2] shl 8) or value[3]; end; function UInt64ToByte(value: UInt64): TBytes; begin SetLength(Result, 8); Result[0] := (value shr 56); Result[1] := (value shr 48); Result[2] := (value shr 40); Result[3] := (value shr 32); Result[4] := (value shr 24); Result[5] := (value shr 16); Result[6] := (value shr 8); Result[7] := (value); end; function ByteToUInt64(value: TBytes): UInt64; begin Result := (Int64(value[0]) shl 56) or (Int64(value[1]) shl 48) or (Int64(value[2]) shl 40) or (Int64(value[3]) shl 32) or (value[4] shl 24) or (value[5] shl 16) or ( value[6] shl 8) or value[7]; end; end.
Unit Mouse; Interface Uses Kernel,F_Mouse; Procedure InitMouse; Procedure DoneMouse; Procedure HideMouse; Procedure ShowMouse; Const InitMouseFlag:Boolean=False; DisableMouse:Boolean=False; Implementation Const Count:Byte=0; DoubTime:Longint=0; Lup:Integer=4; Ldown:Integer=2; Rdown:Integer=8; Rup:Integer=16; DoubleTime:Longint=9; OldButt:Integer=0; Procedure MouseHandler(Mask,Butt,X,Y,dX,dY:Integer);Far; Var T:Longint; Event:TEvent; Begin If DisableMouse Then Exit; T:=Clock_Val; Event.What:=0; Event.Double:=False; Event.Global.X:=X; Event.Global.Y:=Y; Event.Where:=Event.Global; Event.Buttons:=Butt; Event.Ctrl:=Serve_Val And svCtrl<>0; Event.Shift:=Serve_Val And (svLShift+svRShift)<>0; If Mask And 1=1 Then Event.What:=Event.What or evMouseMove; If (Mask And Lup<>0)or((OldButt And 1<>0)And(Butt And 1=0))Then Event.What:=Event.What or evMouseLup; If (Mask And Rup<>0)or((OldButt And 2<>0)And(Butt And 2=0))Then Event.What:=Event.What or evMouseRup; If (Mask And Ldown<>0)or((OldButt And 1=0)And(Butt And 1<>0))Then Event.What:=Event.What or evMouseLdown; If (Mask And Rdown<>0)or((OldButt And 2=0)And(Butt and 2<>0))Then Event.What:=Event.What or evMouseRdown; OldButt:=Butt; If (Mask And Ldown<>0)And(Count Mod 2=0) Then Begin If Count=0 Then DoubTime:=T; If T-DoubTime>=DoubleTime Then Begin Count:=1; DoubTime:=T; End Else Inc(Count); End; If (Mask And Lup<>0)And(Count Mod 2<>0) Then Begin If T-DoubTime>=DoubleTime Then Count:=0 Else Inc(Count); If Count=4 Then Begin Event.Double:=True; Count:=0; End; End; If Butt And 1=1 Then Event.What:=Event.What or evMouseAuto; KernelSelf^.AddEvent(Event); End; Procedure InitMouse; Begin If InitMouseFlag Then Exit; InitMouseFlag:=True; F_Mouse.InitMouse; F_Mouse.ShowMouse; With RScreen Do F_mouse.MouseWindow(A.X,A.Y,B.X,B.Y); SetMouseHandler(1+ldown+rdown+lup+rup,MouseHandler); End; Procedure DoneMouse; Begin If Not InitMouseFlag Then Exit; InitMouseFlag:=False; ClearMouseHandler; End; Procedure HideMouse; Begin F_Mouse.HideMouse; End; Procedure ShowMouse; Begin F_Mouse.ShowMouse; End; End.
UNIT CIEChromaticity; INTERFACE USES Windows, // TRect Graphics, // TBitmap; XYZtoRGBconversion, // TColorSystem, XYZtoRGB, InsideGamut ColorMatchingFunctions; // TCIEStandardObserver, xyChromaticityCoordinates FUNCTION CIE1931xyChart(CONST CIEStandardObserver: TCIEStandardObserver; CONST ColorSystem : TColorSystem; CONST Gamma : TReal; CONST BackgroundColor: TColor; CONST ChartSize : INTEGER; CONST ShowFullChart : BOOLEAN; CONST ShowGridLines : BOOLEAN; CONST ShowWavelengthValues: BOOLEAN): TBitmap; FUNCTION CIEuvChart (CONST CIEChart: TCIEChart; CONST CIEStandardObserver: TCIEStandardObserver; CONST ColorSystem : TColorSystem; CONST Gamma : TReal; CONST BackgroundColor: TColor; CONST ChartSize : INTEGER; CONST ShowFullChart : BOOLEAN; CONST ShowGridLines : BOOLEAN; CONST ShowWavelengthValues: BOOLEAN): TBitmap; PROCEDURE ShowAnnotation(CONST Canvas: TCanvas; CONST iText, jText : INTEGER; CONST iTarget, jTarget: INTEGER; CONST s: STRING); IMPLEMENTATION USES Classes, // Rect Math, // MaxValue SysUtils, // IntToStr MapWorldToPixel; // TRealRect, MapRealToPixel, MoveTo, LineTo CONST PixelCountMax = 32768; TYPE TRGBTripleArray = ARRAY[0..PixelCountMax-1] OF TRGBTriple; pRGBTripleArray = ^TRGBTripleArray; FUNCTION CIE1931xyChart(CONST CIEStandardObserver: TCIEStandardObserver; CONST ColorSystem : TColorSystem; CONST Gamma : TReal; CONST BackgroundColor: TColor; CONST ChartSize : INTEGER; CONST ShowFullChart : BOOLEAN; CONST ShowGridLines : BOOLEAN; CONST ShowWavelengthValues: BOOLEAN): TBitmap; CONST xMax = 0.84; xMin = 0.00; yMax = 0.84; yMin = 0.00; VAR CIE1931xyRect : TRealRect; factor : TReal; i : INTEGER; iDelta : INTEGER; iText : INTEGER; j : INTEGER; jDelta : INTEGER; jText : INTEGER; PixelRect : TRect; R,G,B : TFloat; row : pRGBTripleArray; s : STRING; SideLeft : INTEGER; SideRight : INTEGER; SimplePantograph : TSimplePantograph; PerpendicularSlope: TReal; TickLength : TReal; Wavelength : INTEGER; x : TReal; xDelta : TReal; xNormalDelta : TReal; xNormalUnitDelta : TReal; xOld : TReal; y : TReal; yDelta : TReal; yNormalDelta : TReal; yNormalUnitDelta : TReal; yUnitDelta : TReal; yOld : TReal; z : TReal; PROCEDURE PlotPoint; VAR maxRGB: TFloat; BEGIN R := Clamp(R, 0.0, 1.0); G := Clamp(G, 0.0, 1.0); B := Clamp(B, 0.0, 1.0); maxRGB := MaxValue( [R, G, B] ); WITH Row[i] DO BEGIN IF ABS(Gamma - 1.00) < 0.0001 THEN BEGIN rgbtRed := ROUND(255 * R / maxRGB); rgbtGreen := ROUND(255 * G / maxRGB); rgbtBlue := ROUND(255 * B / maxRGB) END ELSE BEGIN rgbtRed := ROUND(255* Power( R/maxRGB, Gamma) ); rgbtGreen := ROUND(255* Power( G/maxRGB, Gamma) ); rgbtBlue := ROUND(255* Power( B/maxRGB, Gamma) ) END END END {PlotPoint}; BEGIN RESULT := TBitmap.Create; RESULT.Width := ChartSize; // create only a square bitmap for now RESULT.Height := ChartSize; RESULT.PixelFormat := pf24bit; // avoid using palettes RESULT.Canvas.Brush.Color := clBlack; RESULT.Canvas.FillRect(RESULT.Canvas.ClipRect); iDelta := RESULT.Canvas.ClipRect.Right - RESULT.Canvas.ClipRect.Left; jDelta := RESULT.Canvas.ClipRect.Bottom - RESULT.Canvas.ClipRect.Top; PixelRect := Rect(RESULT.Canvas.ClipRect.Left + MulDiv(iDelta, 5, 100), RESULT.Canvas.ClipRect.Top + MulDiv(jDelta, 5, 100), RESULT.Canvas.ClipRect.Left + MulDiv(iDelta, 95,100), RESULT.Canvas.ClipRect.Top + MulDiv(jDelta, 95,100)); CIE1931xyRect := RealRect(xMin, yMin, xMax, yMax); SimplePantograph := TSimplePantograph.Create(PixelRect, CIE1931xyRect); TRY RESULT.Canvas.Pen.Color := clRed; // Plot wavelengths only from 360 to 730 nm to avoid "hook" in // 1964 data above 740 nm // Plot outline of chromaticity chart wavelength := 360; // nm xyChromaticityCoordinates(CIEStandardObserver, Wavelength, x,y); SimplePantograph.MoveTo(RESULT.Canvas, x,y); FOR wavelength := 361 TO 730 DO // nm BEGIN xyChromaticityCoordinates(CIEStandardObserver, Wavelength, x,y); SimplePantograph.LineTo(RESULT.Canvas, x,y) END; Wavelength := 360; // nm xyChromaticityCoordinates(CIEStandardObserver, Wavelength, x,y); SimplePantograph.LineTo(RESULT.Canvas, x,y); // Fill in each scanline inside outline FOR j := 0 TO RESULT.Height-1 DO BEGIN Row := RESULT.Scanline[j]; SideLeft := 0; WHILE (SideLeft < RESULT.Width) AND (Row[SideLeft].rgbtRed <> 255) DO INC(SideLeft); SideRight := RESULT.Width-1; WHILE (SideRight > 0) AND (Row[SideRight].rgbtRed <> 255) DO DEC(SideRight); FOR i := SideLeft TO SideRight DO BEGIN SimplePantograph.MapPixelToReal(i,j, x,y); // A color, C, can be defined using CIE color primaries X, Y, and Z: // // C = X + Y + Z // // The chromaticity coordinates (x,y,z) are defined as // // x = X/C // y = Y/C // z = Z/C // // For the purposes of this diagram, assume C = 1.0, so for this case // x = X, y = Y and z = Z z := 1.0 - x - y; // It's a little confusing, but (x,y,z) (i.e., chromaticity values) // are the same as (X,Y,Z) (i.e., imaginary additive primaries) here. XYZtoRGB(ColorSystem, x, y, z, R, G, B); IF ShowFullChart OR InsideGamut(R,G,B) THEN PlotPoint END; // If we're not showing the full chart, make another pass through to // "fix" the outline of the horseshoe to be either a spectral color, // or a "line of purple" color. This is somewhat of a kludge, but // optimization isn't really necessary. IF NOT ShowFullChart THEN BEGIN // point(s) on left side (usually only one) i := SideLeft; WHILE (i < SideRight) AND (Row[i].rgbtRed = 255) DO BEGIN SimplePantograph.MapPixelToReal(i,j, x,y); z := 1.0 - x - y; XYZtoRGB(ColorSystem, x, y, z, R, G, B); PlotPoint; INC (i) END; // point(s) on right side (usually only one) i := SideRight; WHILE (i > 0) AND (Row[i].rgbtRed = 255) DO BEGIN SimplePantograph.MapPixelToReal(i,j, x,y); z := 1.0 - x - y; XYZtoRGB(ColorSystem, x, y, z, R, G, B); PlotPoint; DEC (i) END; END END; // Gridlines are "under" Wavelength Values IF ShowGridLines THEN BEGIN RESULT.Canvas.Font.Name := 'Arial Narrow'; RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); RESULT.Canvas.Font.Color := clDkGray; RESULT.Canvas.Pen.Width := 1; RESULT.Canvas.Pen.Color := clDkGray; RESULT.Canvas.Pen.Style := psDot; RESULT.Canvas.Brush.Style := bsClear; FOR i := 0 TO TRUNC( (xMax - xMin)/0.10 ) DO BEGIN x := 0.1*i; SimplePantograph.MoveTo(RESULT.Canvas, x, yMin); SimplePantograph.LineTo(RESULT.Canvas, x, yMax); s := Format('%.1f', [0.1*i]); SimplePantograph.MapRealToPixel(x,yMin, iText,jText); RESULT.Canvas.TextOut(iText-RESULT.Canvas.TextWidth(s) DIV 2, jText, s); END; // Label x Axis RESULT.Canvas.Font.Height := MulDiv(Result.Height, 6,100); RESULT.Canvas.TextOut(RESULT.Width - 3*RESULT.Canvas.TextWidth('X') DIV 2, jText - RESULT.Canvas.TextHeight('X') DIV 2, 'x'); RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); FOR j := 0 TO TRUNC( (yMax - yMin)/0.10 ) DO BEGIN y := 0.1*j; SimplePantograph.MoveTo(RESULT.Canvas, xMin, 0.1*j); SimplePantograph.LineTo(RESULT.Canvas, xMax, 0.1*j); s := Format('%.1f', [0.1*j]); SimplePantograph.MapRealToPixel(xMin,y, iText,jText); IF j = 0 // avoid overwrite at origin THEN jText := jText-3*RESULT.Canvas.TextHeight(s) DIV 4 ELSE jText := jText-RESULT.Canvas.TextHeight(s) DIV 2; RESULT.Canvas.TextOut(iText-RESULT.Canvas.TextWidth(s), jText, s); END; // Label y Axis RESULT.Canvas.Font.Height := MulDiv(Result.Height, 6,100); RESULT.Canvas.TextOut(RESULT.Canvas.TextWidth('X') DIV 2, 0,'y') END; IF ShowWavelengthValues THEN BEGIN TickLength := 0.02 * 0.84; // Show wavelength values wavelength := 419; // nm xyChromaticityCoordinates(CIEStandardObserver, Wavelength, xOld,yOld); RESULT.Canvas.Pen.Width := 1; RESULT.Canvas.Pen.Style := psSolid; RESULT.Canvas.Font.Name := 'Arial Narrow'; RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); RESULT.Canvas.Font.Color := clWhite; RESULT.Canvas.Brush.Style := bsClear; FOR wavelength := 420 TO 680 DO // nm BEGIN xyChromaticityCoordinates(CIEStandardObserver, Wavelength, x,y); RESULT.Canvas.Pen.Color := clWhite; factor := 0; IF wavelength MOD 10 = 0 THEN factor := 1.0 ELSE IF wavelength MOD 5 = 0 THEN factor := 0.5; // Kludge to get rid of too many tick marks IF (wavelength > 420) AND (wavelength < 450) THEN factor := 0.0; IF (wavelength > 630) AND (wavelength < 680) THEN factor := 0.0; IF factor > 0 THEN BEGIN xDelta := x - xOld; yDelta := y - yOld; xNormalDelta := yDelta; yNormalDelta := -xDelta; xNormalUnitDelta := xNormalDelta / SQRT( SQR(xNormalDelta) + SQR(yNormalDelta) ); yNormalUnitDelta := yNormalDelta / SQRt( SQR(xNormalDelta) + SQR(yNormalDelta) ); IF (wavelength MOD 10 = 0) AND // every 10th nm (wavelength DIV 10 IN // divide by 10 to use 0..255 set ([42..68] - [43,44,45, 50, 62,64..67])) // avoid overwrites THEN BEGIN // Show wavelength annotation SimplePantograph.MapRealToPixel(x,y, i,j); SimplePantograph.MapRealToPixel(x-factor*TickLength*xNormalUnitDelta, y-factor*TickLength*yNormalUnitDelta, iText, jText); ShowAnnotation(RESULT.Canvas, iText,jText, i,j, IntToStr(wavelength)) END ELSE BEGIN // SimplePantograph.MoveTo(RESULT.Canvas, x,y); // SimplePantograph.LineTo(RESULT.Canvas, x+factor*TickLength*xNormalUnitDelta, // y+factor*TickLength*yNormalUnitDelta); SimplePantograph.MoveTo(RESULT.Canvas, x,y); SimplePantograph.LineTo(RESULT.Canvas, x-factor*TickLength*xNormalUnitDelta, y-factor*TickLength*yNormalUnitDelta); END END; xOld := x; yOld := y; END END FINALLY SimplePantograph.Free END END {CIE1931Chart}; // 1960 uv Chart or 1976 u'v' Chart FUNCTION CIEuvChart (CONST CIEChart: TCIEChart; CONST CIEStandardObserver: TCIEStandardObserver; CONST ColorSystem : TColorSystem; CONST Gamma : TReal; CONST BackgroundColor: TColor; CONST ChartSize : INTEGER; CONST ShowFullChart : BOOLEAN; CONST ShowGridLines : BOOLEAN; CONST ShowWavelengthValues: BOOLEAN): TBitmap; CONST xMax = 0.60; xMin = 0.00; yMax = 0.60; yMin = 0.00; VAR CIE1960uvRect : TRealRect; denominator : TReal; factor : TReal; i : INTEGER; iDelta : INTEGER; iText : INTEGER; j : INTEGER; jDelta : INTEGER; jText : INTEGER; maxRGB : TFloat; PerpendicularSlope: TReal; PixelRect : TRect; R,G,B : TFloat; row : pRGBTripleArray; s : STRING; SideLeft : INTEGER; SideRight : INTEGER; SimplePantograph : TSimplePantograph; TickLength : TReal; wavelength : INTEGER; u : TReal; v : TReal; x : TReal; xDelta : TReal; xNormalDelta : TReal; xNormalUnitDelta : TReal; xOld : TReal; y : TReal; yDelta : TReal; yNormalDelta : TReal; yNormalUnitDelta : TReal; yOld : TReal; z : TReal; PROCEDURE PlotPoint; VAR maxRGB: TFloat; BEGIN R := Clamp(R, 0.0, 1.0); G := Clamp(G, 0.0, 1.0); B := Clamp(B, 0.0, 1.0); maxRGB := MaxValue( [R, G, B] ); WITH Row[i] DO BEGIN rgbtRed := ROUND(255* Power( R/maxRGB, Gamma) ); rgbtGreen := ROUND(255* Power( G/maxRGB, Gamma) ); rgbtBlue := ROUND(255* Power( B/maxRGB, Gamma) ); END END {PlotPoint}; BEGIN RESULT := TBitmap.Create; RESULT.Width := ChartSize; // create only a square bitmap for now RESULT.Height := ChartSize; RESULT.PixelFormat := pf24bit; // avoid using of palettes RESULT.Canvas.Brush.Color := clBlack; RESULT.Canvas.FillRect(RESULT.Canvas.ClipRect); iDelta := RESULT.Canvas.ClipRect.Right - RESULT.Canvas.ClipRect.Left; jDelta := RESULT.Canvas.ClipRect.Bottom - RESULT.Canvas.ClipRect.Top; PixelRect := Rect(RESULT.Canvas.ClipRect.Left + MulDiv(iDelta, 5, 100), RESULT.Canvas.ClipRect.Top + MulDiv(jDelta, 5, 100), RESULT.Canvas.ClipRect.Left + MulDiv(iDelta, 95,100), RESULT.Canvas.ClipRect.Top + MulDiv(jDelta, 95,100)); CIE1960uvRect := RealRect(0.0, 0.0, 0.60, 0.60); SimplePantograph := TSimplePantograph.Create(PixelRect, CIE1960uvRect); TRY RESULT.Canvas.Pen.Color := clRed; // Plot wavelengths only from 360 to 730 nm to avoid "hook" in // 1964 data above 740 nm // Plot outline of chromaticity chart Wavelength := 360; // nm uvChromaticityCoordinates(CIEChart, CIEStandardObserver, Wavelength, u,v); SimplePantograph.MoveTo(RESULT.Canvas, u,v); FOR Wavelength := 361 TO 730 DO // nm BEGIN uvChromaticityCoordinates(CIEChart, CIEStandardObserver, Wavelength, u,v); SimplePantograph.LineTo(RESULT.Canvas, u,v) END; // Avoid compiler warning about initialization x := 0; y := 0; Wavelength := 360; // nm uvChromaticityCoordinates(CIEChart, CIEStandardObserver, Wavelength, u,v); SimplePantograph.LineTo(RESULT.Canvas, u,v); // Fill in each scanline inside outline FOR j := 0 TO RESULT.Height-1 DO BEGIN Row := RESULT.Scanline[j]; SideLeft := 0; WHILE (SideLeft < RESULT.Width) AND (Row[SideLeft].rgbtRed = 0) DO INC(SideLeft); SideRight := RESULT.Width-1; WHILE (SideRight > 0) AND (Row[SideRight].rgbtREd = 0) DO DEC(SideRight); FOR i := SideLeft TO SideRight DO BEGIN SimplePantograph.MapPixelToReal(i,j, u,v); CASE CIEChart OF CIEChart1960: BEGIN // "Color Theory and Its Application in Art and Design" // George A. Agoston, Springer-Verlag, p. 240, 1987 // // "Color in Business, Science and Industry" (3rd edition) // Deane B. Judd and Gunter Wyszecki, John Wiley, p. 296, 1975 // for inverse of these functions // denominator := 2*u - 8*v + 4; x := 3*u / denominator; y := 2*v / denominator END; CIEChart1976: BEGIN // Here (u,v) is really (u',v') // "Principles of Color Technology" (2nd edition) // Fred W. Billmeyer, Jr. and Max Saltzman // John Wiley, p. 58, 1981 denominator := 18*u - 48*v + 36; x := 27*u / denominator; y := 12*v / denominator; END; END; z := 1.0 - x - y; // See comments above in CIE1931Chart as to why x=X, y=Y and z=Z here XYZtoRGB(ColorSystem, x, y, z, R, G, B); IF ShowFullChart OR InsideGamut(R,G,B) THEN BEGIN R := Clamp(R, 0.0, 1.0); G := Clamp(G, 0.0, 1.0); B := Clamp(B, 0.0, 1.0); maxRGB := MaxValue( [R, G, B] ); WITH Row[i] DO BEGIN rgbtRed := ROUND(255* Power( R/maxRGB, Gamma) ); rgbtGreen := ROUND(255* Power( G/maxRGB, Gamma) ); rgbtBlue := ROUND(255* Power( B/maxRGB, Gamma) ); END END END; // If we're not showing the full chart, make another pass through to // "fix" the outline of the horseshoe to be either a spectral color, // or a "line of purple" color. This is somewhat of a kludge, but // optimization isn't really necessary. IF NOT ShowFullChart THEN BEGIN // point(s) on left side (usually only one) i := SideLeft; WHILE (i < SideRight) AND (Row[i].rgbtRed > 0) DO BEGIN SimplePantograph.MapPixelToReal(i,j, u,v); CASE CIEChart OF CIEChart1960: BEGIN // "Color Theory and Its Application in Art and Design" // George A. Agoston, Springer-Verlag, p. 240, 1987 // // "Color in Business, Science and Industry" (3rd edition) // Deane B. Judd and Gunter Wyszecki, John Wiley, p. 296, 1975 // for inverse of these functions // denominator := 2*u - 8*v + 4; x := 3*u / denominator; y := 2*v / denominator END; CIEChart1976: BEGIN // Here (u,v) is really (u',v') // "Principles of Color Technology" (2nd edition) // Fred W. Billmeyer, Jr. and Max Saltzman // John Wiley, p. 58, 1981 denominator := 18*u - 48*v + 36; x := 27*u / denominator; y := 12*v / denominator END; END; z := 1.0 - x - y; XYZtoRGB(ColorSystem, x, y, z, R, G, B); PlotPoint; INC (i) END; // point(s) on right side (usually only one) i := SideRight; WHILE (i > 0) AND (Row[i].rgbtRed > 0) DO BEGIN SimplePantograph.MapPixelToReal(i,j, u,v); CASE CIEChart OF CIEChart1960: BEGIN // "Color Theory and Its Application in Art and Design" // George A. Agoston, Springer-Verlag, p. 240, 1987 // // "Color in Business, Science and Industry" (3rd edition) // Deane B. Judd and Gunter Wyszecki, John Wiley, p. 296, 1975 // for inverse of these functions // denominator := 2*u - 8*v + 4; x := 3*u / denominator; y := 2*v / denominator END; CIEChart1976: BEGIN // Here (u,v) is really (u',v') // "Principles of Color Technology" (2nd edition) // Fred W. Billmeyer, Jr. and Max Saltzman // John Wiley, p. 58, 1981 x := 27*u / (18*u - 48*v + 36); y := 12*v / (18*u - 48*v + 36); END; END; z := 1.0 - x - y; XYZtoRGB(ColorSystem, x, y, z, R, G, B); PlotPoint; DEC (i) END; END END; // Gridlines are "under" Wavelength Values IF ShowGridLines THEN BEGIN RESULT.Canvas.Font.Name := 'Arial Narrow'; RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); RESULT.Canvas.Font.Color := clDkGray; RESULT.Canvas.Pen.Width := 1; RESULT.Canvas.Pen.Color := clDkGray; RESULT.Canvas.Pen.Style := psDot; RESULT.Canvas.Brush.Style := bsClear; FOR i := 0 TO TRUNC( (xMax - xMin)/0.10 ) DO BEGIN x := 0.1*i; SimplePantograph.MoveTo(RESULT.Canvas, x, yMin); SimplePantograph.LineTo(RESULT.Canvas, x, yMax); s := Format('%.1f', [0.1*i]); SimplePantograph.MapRealToPixel(x,yMin, iText,jText); RESULT.Canvas.TextOut(iText-RESULT.Canvas.TextWidth(s) DIV 2, jText, s); END; // Label x Axis RESULT.Canvas.Font.Height := MulDiv(Result.Height, 6,100); IF CIEChart = CIEChart1960 THEN s := 'u' ELSE s := 'u'''; SimplePantograph.MapRealToPixel(xMax,yMin, iText,jText); RESULT.Canvas.TextOut(iText + RESULT.Canvas.TextWidth('x') DIV 2, jText - 3*RESULT.Canvas.TextHeight(s) DIV 4, s); RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); FOR j := 0 TO TRUNC( (yMax - yMin)/0.10 ) DO BEGIN y := 0.1*j; SimplePantograph.MoveTo(RESULT.Canvas, xMin, 0.1*j); SimplePantograph.LineTo(RESULT.Canvas, xMax, 0.1*j); s := Format('%.1f', [0.1*j]); SimplePantograph.MapRealToPixel(xMin,y, iText,jText); IF j = 0 // avoid overwrite at origin THEN jText := jText-3*RESULT.Canvas.TextHeight(s) DIV 4 ELSE jText := jText-RESULT.Canvas.TextHeight(s) DIV 2; RESULT.Canvas.TextOut(iText-RESULT.Canvas.TextWidth(s), jText, s); END; RESULT.Canvas.Font.Height := MulDiv(Result.Height, 6,100); IF CIEChart = CIEChart1960 THEN s := 'v' ELSE s := 'v'''; SimplePantograph.MapRealToPixel(xMin,yMax, iText,jText); RESULT.Canvas.TextOut(iText, jText - RESULT.Canvas.TextHeight(s), s) END; IF ShowWavelengthValues THEN BEGIN TickLength := 0.02 * 0.84; // Show wavelength values wavelength := 419; // nm uvChromaticityCoordinates(CIEChart, CIEStandardObserver, Wavelength, xOld,yOld); RESULT.Canvas.Pen.Width := 1; RESULT.Canvas.Pen.Style := psSolid; RESULT.Canvas.Font.Name := 'Arial Narrow'; RESULT.Canvas.Font.Height := MulDiv(Result.Height, 4,100); RESULT.Canvas.Font.Color := clWhite; RESULT.Canvas.Brush.Style := bsClear; FOR wavelength := 420 TO 680 DO // nm BEGIN uvChromaticityCoordinates(CIEChart, CIEStandardObserver, Wavelength, x,y); RESULT.Canvas.Pen.Color := clWhite; factor := 0; IF wavelength MOD 10 = 0 THEN factor := 1.0 ELSE IF wavelength MOD 5 = 0 THEN factor := 0.5; // Kludge to get rid of too many tick marks // IF (wavelength > 420) AND (wavelength < 440) // THEN factor := 0.0; IF (wavelength > 640) AND (wavelength < 680) THEN factor := 0.0; IF factor > 0 THEN BEGIN xDelta := x - xOld; yDelta := y - yOld; xNormalDelta := yDelta; yNormalDelta := -xDelta; xNormalUnitDelta := xNormalDelta / SQRT( SQR(xNormalDelta) + SQR(yNormalDelta) ); yNormalUnitDelta := yNormalDelta / SQRt( SQR(xNormalDelta) + SQR(yNormalDelta) ); IF (wavelength MOD 10 = 0) AND // every 10th nm (wavelength DIV 10 IN // divide by 10 to use 0..255 set ([42..68] - [43, 50,51, 63, 65..67])) // avoid overwrites THEN BEGIN // Show wavelength annotation SimplePantograph.MapRealToPixel(x,y, i,j); SimplePantograph.MapRealToPixel(x-factor*TickLength*xNormalUnitDelta, y-factor*TickLength*yNormalUnitDelta, iText, jText); ShowAnnotation(RESULT.Canvas, iText,jText, i,j, IntToStr(wavelength)) END ELSE BEGIN // SimplePantograph.MoveTo(RESULT.Canvas, x,y); // SimplePantograph.LineTo(RESULT.Canvas, x+factor*TickLength*xNormalUnitDelta, // y+factor*TickLength*yNormalUnitDelta); SimplePantograph.MoveTo(RESULT.Canvas, x,y); SimplePantograph.LineTo(RESULT.Canvas, x-factor*TickLength*xNormalUnitDelta, y-factor*TickLength*yNormalUnitDelta); END END; xOld := x; yOld := y; END END FINALLY SimplePantograph.Free END END {CIEuvChart}; // Draw Text in a "smart" way at the end of a line PROCEDURE ShowAnnotation(CONST Canvas: TCanvas; CONST iText, jText : INTEGER; CONST iTarget, jTarget: INTEGER; CONST s: STRING); VAR angle : Double; i : INTEGER; index : INTEGER; j : INTEGER; width : INTEGER; height: INTEGER; BEGIN // Given points(iText,jText) and (iTarget,jTarget). The angle between // the x-axis and the vector (iTarget-iText, jTarget-jText) ranges in the // open interval [0.0, 360.0) degrees. Note: Normally, ArcTan2 returns // a value from -PI to PI. angle := 180 * (1 + ArcTan2(jText-jTarget, iTarget-iText) / PI); IF angle >= 360.0 THEN angle := angle - 360.0; index := TRUNC( (angle + 22.5) / 45.0); Canvas.MoveTo(iText,jText); Canvas.LineTo(iTarget, jTarget); width := Canvas.TextWidth(s); height := Canvas.TextHeight(s); CASE index OF 0,8: BEGIN // East i := iText; j := jText - height DIV 2 END; 1: BEGIN //NorthEast i := iText; j := jText - height; END; 2: BEGIN // North i := iText - width DIV 2; j := jText - height; END; 3: BEGIN // NorthWest i := iText - width; j := jText - height; END; 4: BEGIN // West i := iText - width; j := jText - height DIV 2 END; 5: BEGIN // SouthWest i := iText - width; j := jText END; 6: BEGIN // South i := iText - width DIV 2; j := jText END; 7: BEGIN // SouthEast i := iText; j := jText END; ELSE i := iText; j := jText; END; // Draw Text in a "smart" way at end of line Canvas.TextOut(i, j, s) END; END.
unit VirtualStringTreeComboBox; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface Uses Windows, SysUtils, Types, Classes, Graphics, Messages, Controls, StdCtrls, Forms, VirtualTrees; Type TGetListEvent = procedure (context : String; list : TStrings) of object; TVirtualStringTreeComboBox = class (TInterfacedObject, IVTEditLink) private FCombo: TCombobox; // One of the property editor classes. FTree: TVirtualStringTree; // A back reference to the tree calling. FNode: PVirtualNode; // The node being edited. FColumn: Integer; // The column of the node being edited. FText : String; FOnlyList : Boolean; FGetList : TGetListEvent; FContext : String; protected procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); public Constructor Create(text : String; onlyList : boolean; OnGetList : TGetListEvent; context : string); destructor Destroy; override; function BeginEdit: Boolean; stdcall; function CancelEdit: Boolean; stdcall; function EndEdit: Boolean; stdcall; function GetBounds: TRect; stdcall; function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall; procedure ProcessMessage(var Message: TMessage); stdcall; procedure SetBounds(R: TRect); stdcall; end; // this is defined to support autoedit - capture the first typed character TVirtualStringTreeEdit = class (TInterfacedObject, IVTEditLink) private FEdit : TEdit; // One of the property editor classes. FTree: TVirtualStringTree; // A back reference to the tree calling. FNode: PVirtualNode; // The node being edited. FColumn: Integer; // The column of the node being edited. FText : String; FNoSelect : boolean; protected procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); public Constructor Create(text : String; NoSelect : boolean); destructor Destroy; override; function BeginEdit: Boolean; stdcall; function CancelEdit: Boolean; stdcall; function EndEdit: Boolean; stdcall; function GetBounds: TRect; stdcall; function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall; procedure ProcessMessage(var Message: TMessage); stdcall; procedure SetBounds(R: TRect); stdcall; end; implementation { TVirtualStringTreeComboBox } constructor TVirtualStringTreeComboBox.Create(text : String; onlyList: boolean; OnGetList: TGetListEvent; context: string); begin inherited Create; FText := text; FOnlyList := onlyList; FGetList := OnGetList; FContext := context; end; destructor TVirtualStringTreeComboBox.Destroy; begin //FEdit.Free; casues issue #357. Fix: if FCombo.HandleAllocated then PostMessage(FCombo.Handle, CM_RELEASE, 0, 0); inherited; end; function TVirtualStringTreeComboBox.BeginEdit: Boolean; begin Result := True; FCombo.Show; FCombo.SetFocus; end; //---------------------------------------------------------------------------------------------------------------------- function TVirtualStringTreeComboBox.CancelEdit: Boolean; begin Result := True; FCombo.Hide; end; function TVirtualStringTreeComboBox.EndEdit: Boolean; begin Result := True; if FCombo.Text <> FText then begin FTree.OnNewText(FTree, FNode, FColumn, FCombo.Text); FTree.InvalidateNode(FNode); end; FCombo.Hide; FTree.SetFocus; end; function TVirtualStringTreeComboBox.GetBounds: TRect; begin Result := FCombo.BoundsRect; end; function TVirtualStringTreeComboBox.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; begin Result := True; FTree := Tree as TVirtualStringTree; FNode := Node; FColumn := Column; // determine what edit type actually is needed FCombo.Free; FCombo := nil; FCombo := TComboBox.Create(nil); FCombo.Visible := False; FCombo.Parent := Tree; if FOnlyList then FCombo.Style := csDropDownList else FCombo.Style := csDropDown; FGetList(FContext, FCombo.Items); if FCombo.Items.IndexOf(FText) = -1 then FCombo.Items.Insert(0, FText); FCombo.Text := FText; FCombo.OnKeyDown := EditKeyDown; FCombo.OnKeyUp := EditKeyUp; end; procedure TVirtualStringTreeComboBox.ProcessMessage(var Message: TMessage); begin FCombo.WindowProc(Message); end; //---------------------------------------------------------------------------------------------------------------------- procedure TVirtualStringTreeComboBox.SetBounds(R: TRect); var Dummy: Integer; begin // Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn) // we have to set the edit's width explicitly to the width of the column. FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right); FCombo.BoundsRect := R; end; procedure TVirtualStringTreeComboBox.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var CanAdvance: Boolean; begin CanAdvance := true; case Key of VK_ESCAPE: begin Key := 0;//ESC will be handled in EditKeyUp() end; VK_RETURN: if CanAdvance then begin FTree.EndEditNode; Key := 0; end; VK_UP, VK_DOWN: begin // Consider special cases before finishing edit mode. CanAdvance := Shift = []; CanAdvance := CanAdvance and not FCombo.DroppedDown; if CanAdvance then begin // Forward the keypress to the tree. It will asynchronously change the focused node. PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0); Key := 0; end; end; end; end; procedure TVirtualStringTreeComboBox.EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin FTree.CancelEditNode; Key := 0; end;//VK_ESCAPE end;//case end; { TVirtualStringTreeEdit } constructor TVirtualStringTreeEdit.Create(text : String; NoSelect : boolean); begin inherited Create; FText := text; FNoSelect := NoSelect; end; destructor TVirtualStringTreeEdit.Destroy; begin //FEdit.Free; casues issue #357. Fix: if FEdit.HandleAllocated then PostMessage(FEdit.Handle, CM_RELEASE, 0, 0); inherited; end; function TVirtualStringTreeEdit.BeginEdit: Boolean; begin Result := True; FEdit.Show; FEdit.SetFocus; if FNoSelect then FEdit.SelStart := length(FEdit.Text); end; //---------------------------------------------------------------------------------------------------------------------- function TVirtualStringTreeEdit.CancelEdit: Boolean; begin Result := True; FEdit.Hide; end; function TVirtualStringTreeEdit.EndEdit: Boolean; begin Result := True; if FEdit.Text <> FText then begin FTree.OnNewText(FTree, FNode, FColumn, FEdit.Text); FTree.InvalidateNode(FNode); end; FEdit.Hide; FTree.SetFocus; end; function TVirtualStringTreeEdit.GetBounds: TRect; begin Result := FEdit.BoundsRect; end; function TVirtualStringTreeEdit.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; begin Result := True; FTree := Tree as TVirtualStringTree; FNode := Node; FColumn := Column; // determine what edit type actually is needed FEdit.Free; FEdit := nil; FEdit := TEdit.Create(nil); FEdit.Visible := False; FEdit.Parent := Tree; FEdit.Text := FText; FEdit.OnKeyDown := EditKeyDown; FEdit.OnKeyUp := EditKeyUp; end; procedure TVirtualStringTreeEdit.ProcessMessage(var Message: TMessage); begin FEdit.WindowProc(Message); end; //---------------------------------------------------------------------------------------------------------------------- procedure TVirtualStringTreeEdit.SetBounds(R: TRect); var Dummy: Integer; begin // Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn) // we have to set the edit's width explicitly to the width of the column. FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right); FEdit.BoundsRect := R; end; procedure TVirtualStringTreeEdit.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var CanAdvance: Boolean; begin CanAdvance := true; case Key of VK_ESCAPE: begin Key := 0;//ESC will be handled in EditKeyUp() end; VK_RETURN: if CanAdvance then begin FTree.EndEditNode; Key := 0; end; VK_UP, VK_DOWN: begin // Consider special cases before finishing edit mode. CanAdvance := Shift = []; //CanAdvance := CanAdvance and not FCombo.DroppedDown; if CanAdvance then begin // Forward the keypress to the tree. It will asynchronously change the focused node. PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0); Key := 0; end; end; end; end; procedure TVirtualStringTreeEdit.EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin FTree.CancelEditNode; Key := 0; end;//VK_ESCAPE end;//case end; end.
unit uLogger; interface type ILogger = interface ['{955784CD-D867-4B41-A8F2-3D31B4593F39}'] procedure Log(const aString: string); end; TLogger = class(TInterfacedObject, ILogger) procedure Log(const aString: string); end; implementation { TLogger } procedure TLogger.Log(const aString: string); begin WriteLn(aString); end; end.
{----------------------------------------------------------------------------- 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvOdacSmartQuery.PAS, released on 2002-05-26. The Initial Developer of the Original Code is Jens Fudickar All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Description: Oracle Dataset with Threaded Functions Known Issues: -----------------------------------------------------------------------------} // $Id: JvOracleDataSet.pas 13104 2011-09-07 06:50:43Z obones $ unit JvOracleDataSet; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, StdCtrls, ExtCtrls, Forms, Controls, DB, OracleData, JvThread, JvThreadDialog, JvDynControlEngine, JvBaseDBThreadedDataSet; type TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions = class(TJvBaseThreadedDatasetAllowedContinueRecordFetchOptions) public constructor Create; override; published property All; property Cancel; property Pause; end; TJvDoaThreadedDatasetEnhancedOptions = class(TJvBaseThreadedDatasetEnhancedOptions) private function GetAllowedContinueRecordFetchOptions: TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions; procedure SetAllowedContinueRecordFetchOptions(const Value: TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions); protected function CreateAllowedContinueRecordFetchOptions: TJvBaseThreadedDatasetAllowedContinueRecordFetchOptions; override; published property AllowedContinueRecordFetchOptions: TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions read GetAllowedContinueRecordFetchOptions write SetAllowedContinueRecordFetchOptions; end; TJvOracleDatasetThreadHandler = class(TJvBaseDatasetThreadHandler) private function GetEnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions; procedure SetEnhancedOptions(const Value: TJvDoaThreadedDatasetEnhancedOptions); protected function CreateEnhancedOptions: TJvBaseThreadedDatasetEnhancedOptions; override; published property EnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions read GetEnhancedOptions write SetEnhancedOptions; end; {$IFDEF RTL230_UP} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF RTL230_UP} TJvOracleDataset = class(TOracleDataset, IJvThreadedDatasetInterface) procedure BreakExecution; procedure BringThreadDialogToFront; function DoGetInheritedNextRecord: Boolean; procedure DoInheritedAfterOpen; procedure DoInheritedAfterRefresh; procedure DoInheritedAfterScroll; procedure DoInheritedBeforeOpen; procedure DoInheritedBeforeRefresh; procedure DoInheritedInternalLast; procedure DoInheritedInternalRefresh; procedure DoInheritedSetActive(Active: Boolean); procedure DoInternalOpen; function GetDatasetFetchAllRecords: Boolean; function IsThreadAllowed: Boolean; procedure SetDatasetFetchAllRecords(const Value: Boolean); private FAfterFetchRecord: TAfterFetchRecordEvent; FThreadHandler: TJvBaseDatasetThreadHandler; function GetAfterOpenFetch: TDataSetNotifyEvent; function GetBeforeThreadExecution: TJvThreadedDatasetThreadEvent; function GetAfterThreadExecution: TJvThreadedDatasetThreadEvent; function GetDialogOptions: TJvThreadedDatasetDialogOptions; function GetEnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions; function GetThreadOptions: TJvThreadedDatasetThreadOptions; procedure SetAfterOpenFetch(const Value: TDataSetNotifyEvent); procedure SetBeforeThreadExecution(const Value: TJvThreadedDatasetThreadEvent); procedure SetAfterThreadExecution(const Value: TJvThreadedDatasetThreadEvent); procedure SetDialogOptions(Value: TJvThreadedDatasetDialogOptions); procedure SetEnhancedOptions(const Value: TJvDoaThreadedDatasetEnhancedOptions); procedure SetThreadOptions(const Value: TJvThreadedDatasetThreadOptions); property ThreadHandler: TJvBaseDatasetThreadHandler read FThreadHandler; protected procedure DoAfterOpen; override; procedure DoAfterScroll; override; procedure DoAfterRefresh; override; procedure DoBeforeOpen; override; procedure DoBeforeRefresh; override; function GetNextRecord: Boolean; override; function GetOnThreadException: TJvThreadedDatasetThreadExceptionEvent; procedure InternalLast; override; procedure InternalRefresh; override; procedure ReplaceAfterFetchRecord(Sender: TOracleDataSet; FilterAccept: Boolean; var Action: TAfterFetchRecordAction); procedure SetActive(Value: Boolean); override; procedure SetOnThreadException(const Value: TJvThreadedDatasetThreadExceptionEvent); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; function CurrentFetchDuration: TDateTime; function CurrentOpenDuration: TDateTime; function EofReached: Boolean; function ErrorException: Exception; function ErrorMessage: string; function ThreadIsActive: Boolean; published property BeforeThreadExecution: TJvThreadedDatasetThreadEvent read GetBeforeThreadExecution write SetBeforeThreadExecution; property DialogOptions: TJvThreadedDatasetDialogOptions read GetDialogOptions write SetDialogOptions; property EnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions read GetEnhancedOptions write SetEnhancedOptions; property ThreadOptions: TJvThreadedDatasetThreadOptions read GetThreadOptions write SetThreadOptions; property AfterFetchRecord: TAfterFetchRecordEvent read FAfterFetchRecord write FAfterFetchRecord; property AfterOpenFetch: TDataSetNotifyEvent read GetAfterOpenFetch write SetAfterOpenFetch; property AfterThreadExecution: TJvThreadedDatasetThreadEvent read GetAfterThreadExecution write SetAfterThreadExecution; property OnThreadException: TJvThreadedDatasetThreadExceptionEvent read GetOnThreadException write SetOnThreadException; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvOracleDataSet.pas $'; Revision: '$Revision: 13104 $'; Date: '$Date: 2011-09-07 08:50:43 +0200 (mer. 07 sept. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation constructor TJvOracleDataset.Create(AOwner: TComponent); begin inherited Create(AOwner); FThreadHandler := TJvOracleDatasetThreadHandler.Create(Self, Self); inherited AfterFetchRecord := ReplaceAfterFetchRecord; end; destructor TJvOracleDataset.Destroy; begin FreeAndNil(FThreadHandler); inherited Destroy; end; procedure TJvOracleDataset.BreakExecution; begin if Assigned(Session) and Session.Connected then Session.BreakExecution; end; procedure TJvOracleDataset.BringThreadDialogToFront; begin if Assigned(ThreadHandler) then ThreadHandler.BringDialogToFront; end; function TJvOracleDataset.CurrentFetchDuration: TDateTime; begin if Assigned(ThreadHandler) then Result := ThreadHandler.CurrentFetchDuration else Result := 0; end; function TJvOracleDataset.CurrentOpenDuration: TDateTime; begin if Assigned(ThreadHandler) then Result := ThreadHandler.CurrentOpenDuration else Result := 0; end; procedure TJvOracleDataset.InternalLast; begin if Assigned(ThreadHandler) then ThreadHandler.InternalLast; end; procedure TJvOracleDataset.InternalRefresh; begin if Assigned(ThreadHandler) then ThreadHandler.InternalRefresh; end; procedure TJvOracleDataset.SetActive(Value: Boolean); begin if Assigned(ThreadHandler) then ThreadHandler.SetActive(Value); end; procedure TJvOracleDataset.DoAfterOpen; begin ThreadHandler.AfterOpen; end; procedure TJvOracleDataset.DoAfterScroll; begin ThreadHandler.AfterScroll; end; procedure TJvOracleDataset.DoAfterRefresh; begin ThreadHandler.AfterRefresh; end; procedure TJvOracleDataset.DoBeforeOpen; begin ThreadHandler.BeforeOpen; end; procedure TJvOracleDataset.DoBeforeRefresh; begin ThreadHandler.BeforeRefresh; end; function TJvOracleDataset.DoGetInheritedNextRecord: Boolean; begin Result := Inherited GetNextRecord; end; procedure TJvOracleDataset.DoInheritedAfterOpen; begin inherited DoAfterOpen; end; procedure TJvOracleDataset.DoInheritedAfterRefresh; begin inherited DoAfterRefresh; end; procedure TJvOracleDataset.DoInheritedAfterScroll; begin inherited DoAfterScroll; end; procedure TJvOracleDataset.DoInheritedBeforeOpen; begin inherited DoBeforeOpen; end; procedure TJvOracleDataset.DoInheritedBeforeRefresh; begin inherited DoBeforeRefresh; end; procedure TJvOracleDataset.DoInheritedInternalLast; begin inherited InternalLast; end; procedure TJvOracleDataset.DoInheritedInternalRefresh; begin inherited InternalRefresh; end; procedure TJvOracleDataset.DoInheritedSetActive(Active: Boolean); begin inherited SetActive(Active); end; procedure TJvOracleDataset.DoInternalOpen; begin InternalOpen; end; function TJvOracleDataset.ErrorException: Exception; begin if Assigned(ThreadHandler) then Result := ThreadHandler.ErrorException else Result := Nil; end; function TJvOracleDataset.ErrorMessage: string; begin if Assigned(ThreadHandler) then Result := ThreadHandler.ErrorMessage else Result := ''; end; function TJvOracleDataset.GetBeforeThreadExecution: TJvThreadedDatasetThreadEvent; begin if Assigned(ThreadHandler) then Result := ThreadHandler.BeforeThreadExecution else Result := nil; end; function TJvOracleDataset.GetAfterThreadExecution: TJvThreadedDatasetThreadEvent; begin if Assigned(ThreadHandler) then Result := ThreadHandler.AfterThreadExecution else Result := nil; end; function TJvOracleDataset.GetDatasetFetchAllRecords: Boolean; begin Result := QueryAllRecords; end; function TJvOracleDataset.GetDialogOptions: TJvThreadedDatasetDialogOptions; begin if Assigned(ThreadHandler) then Result := ThreadHandler.DialogOptions else Result := nil; end; function TJvOracleDataset.GetEnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions; begin if Assigned(ThreadHandler) then Result := TJvDoaThreadedDatasetEnhancedOptions(ThreadHandler.EnhancedOptions) else Result := nil; end; function TJvOracleDataset.EofReached: Boolean; begin if Assigned(ThreadHandler) then Result := ThreadHandler.EofReached else Result := False; end; function TJvOracleDataset.GetAfterOpenFetch: TDataSetNotifyEvent; begin if Assigned(ThreadHandler) then Result := ThreadHandler.AfterOpenFetch else Result := nil; end; function TJvOracleDataset.GetNextRecord: Boolean; begin if Assigned(ThreadHandler) then Result := ThreadHandler.GetNextRecord else Result := inherited GetNextRecord; end; function TJvOracleDataset.GetOnThreadException: TJvThreadedDatasetThreadExceptionEvent; begin if Assigned(ThreadHandler) then Result := ThreadHandler.OnThreadException else Result := nil; end; function TJvOracleDataset.GetThreadOptions: TJvThreadedDatasetThreadOptions; begin if Assigned(ThreadHandler) then Result := ThreadHandler.ThreadOptions else Result := nil; end; function TJvOracleDataset.IsThreadAllowed: Boolean; begin if Assigned(Master) and (Master is TJvOracleDataset) then Result := not TJvOracleDataset(Master).ThreadHandler.ThreadIsActive else Result := True; end; procedure TJvOracleDataset.ReplaceAfterFetchRecord(Sender: TOracleDataSet; FilterAccept: Boolean; var Action: TAfterFetchRecordAction); begin if Assigned(ThreadHandler) then case ThreadHandler.CheckContinueRecordFetch of tdccrContinue: Action := afContinue; tdccrAll: Action := afContinue; tdccrCancel: Action := afCancel; tdccrPause: Action := afPause; tdccrStop: Action := afStop; else Action := afStop; end; if Assigned(AfterFetchRecord) then AfterFetchRecord(Sender, FilterAccept, Action); end; procedure TJvOracleDataset.SetAfterOpenFetch(const Value: TDataSetNotifyEvent); begin if Assigned(ThreadHandler) then ThreadHandler.AfterOpenFetch := Value; end; procedure TJvOracleDataset.SetBeforeThreadExecution(const Value: TJvThreadedDatasetThreadEvent); begin if Assigned(ThreadHandler) then ThreadHandler.BeforeThreadExecution := Value; end; procedure TJvOracleDataset.SetAfterThreadExecution(const Value: TJvThreadedDatasetThreadEvent); begin if Assigned(ThreadHandler) then ThreadHandler.AfterThreadExecution := Value; end; procedure TJvOracleDataset.SetDatasetFetchAllRecords(const Value: Boolean); begin QueryAllRecords := Value; end; procedure TJvOracleDataset.SetDialogOptions(Value: TJvThreadedDatasetDialogOptions); begin if Assigned(ThreadHandler) then ThreadHandler.DialogOptions.Assign(Value); end; procedure TJvOracleDataset.SetEnhancedOptions(const Value: TJvDoaThreadedDatasetEnhancedOptions); begin if Assigned(ThreadHandler) then ThreadHandler.EnhancedOptions.Assign(Value); end; procedure TJvOracleDataset.SetOnThreadException(const Value: TJvThreadedDatasetThreadExceptionEvent); begin if Assigned(ThreadHandler) then ThreadHandler.OnThreadException := Value; end; procedure TJvOracleDataset.SetThreadOptions(const Value: TJvThreadedDatasetThreadOptions); begin if Assigned(ThreadHandler) then ThreadHandler.ThreadOptions.Assign(Value); end; function TJvOracleDataset.ThreadIsActive: Boolean; begin if Assigned(ThreadHandler) then Result := ThreadHandler.ThreadIsActive else Result := False; end; function TJvOracleDatasetThreadHandler.CreateEnhancedOptions: TJvBaseThreadedDatasetEnhancedOptions; begin Result := TJvDoaThreadedDatasetEnhancedOptions.Create; end; function TJvOracleDatasetThreadHandler.GetEnhancedOptions: TJvDoaThreadedDatasetEnhancedOptions; begin Result := TJvDoaThreadedDatasetEnhancedOptions(inherited EnhancedOptions); end; procedure TJvOracleDatasetThreadHandler.SetEnhancedOptions(const Value: TJvDoaThreadedDatasetEnhancedOptions); begin inherited EnhancedOptions := Value; end; constructor TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions.Create; begin inherited Create; All := True; end; function TJvDoaThreadedDatasetEnhancedOptions.CreateAllowedContinueRecordFetchOptions: TJvBaseThreadedDatasetAllowedContinueRecordFetchOptions; begin Result := TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions.Create; end; function TJvDoaThreadedDatasetEnhancedOptions.GetAllowedContinueRecordFetchOptions: TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions; begin Result := TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions(inherited AllowedContinueRecordFetchOptions); end; procedure TJvDoaThreadedDatasetEnhancedOptions.SetAllowedContinueRecordFetchOptions( const Value: TJvDoaThreadedDatasetAllowedContinueRecordFetchOptions); begin inherited AllowedContinueRecordFetchOptions := Value; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
{ 单元名称: uJxdClientHashManage 单元作者: 江晓德(Terry) 邮 箱: jxd524@163.com jxd524@gmail.com 说 明: 开始时间: 2011-09-13 修改时间: 2011-09-13 (最后修改时间) 类说明 : 管理客户端的HASH信息, 间隔上传HASH信息到HASH服务器 } unit uJxdClientHashManage; interface uses Windows, SysUtils, Classes, uJxdUdpDefine, uJxdHashCalc, uJxdDataStream, uJxdUdpSynchroBasic, uJxdThread, uJxdServerManage, uJxdFileShareManage; type THashManageStyle = (hmsNull, hmsUpdateFileHash, hmsUpdateWebHash, hmsUpdateBoth); PHashManageInfo = ^THashManageInfo; THashManageInfo = record FFileHash: TxdHash; FWebHash: TxdHash; FStyle: THashManageStyle; FLastActiveTime: Cardinal; end; TxdClientHashManage = class public constructor Create; destructor Destroy; override; procedure AddHash(const AFileHash, AWebHash: TxdHash); {FileShareManage 事件处理} procedure DoFileShareManageOnAddEvent(Sender: TObject; const Ap: PFileShareInfo); procedure DoLoopFileShareManageToAddHashCallBack(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel: Boolean; var AFindNext: Boolean); private FHashList: TList; FLock: TRTLCriticalSection; FThreadRunning: Boolean; FUDP: TxdUdpSynchroBasic; FOnGetServerInfo: TOnGetServerInfo; FServerManage: TxdServerManage; procedure LockManage; inline; procedure UnLockManage; inline; function DoGetServerInfo(const AServerStyle: TServerStyle; var AServerInfos: TAryServerInfo): Boolean; procedure DoThreadToUpdateHash; public property OnGetServerInfo: TOnGetServerInfo read FOnGetServerInfo write FOnGetServerInfo; property UDP: TxdUdpSynchroBasic read FUDP write FUDP; property ServerManage: TxdServerManage read FServerManage write FServerManage; end; implementation uses WinSock2; { TxdClientHashManage } procedure TxdClientHashManage.AddHash(const AFileHash, AWebHash: TxdHash); var i: Integer; bFind, bUpdateHash: Boolean; p: PHashManageInfo; begin if not Assigned(FUDP) or (IsEmptyHash(AFileHash) and IsEmptyHash(AWebHash)) then Exit; bFind := False; bUpdateHash := False; p := nil; LockManage; try //搜索 for i := 0 to FHashList.Count - 1 do begin p := FHashList[i]; if not IsEmptyHash(p^.FFileHash) and HashCompare(AFileHash, p^.FFileHash) then begin bFind := True; if not IsEmptyHash(AWebHash) and IsEmptyHash(p^.FWebHash) then begin p^.FWebHash := AWebHash; bUpdateHash := True; end; end else if not IsEmptyHash(p^.FWebHash) and HashCompare(AWebHash, p^.FWebHash) then begin bFind := True; if not IsEmptyHash(AFileHash) and IsEmptyHash(p^.FFileHash) then begin p^.FFileHash := AFileHash; bUpdateHash := True; end; end; end; //新建 if not bFind then begin New( p ); p^.FFileHash := AFileHash; p^.FWebHash := AWebHash; p^.FStyle := hmsNull; bUpdateHash := True; FHashList.Add( p ); end; //更新 if bUpdateHash then begin if Assigned(p) then p^.FLastActiveTime := GetTickCount; if not FThreadRunning then begin FThreadRunning := True; RunningByThread( DoThreadToUpdateHash ); end; end; finally UnLockManage; end; end; constructor TxdClientHashManage.Create; begin InitializeCriticalSection( FLock ); FHashList := TList.Create; FThreadRunning := False; end; destructor TxdClientHashManage.Destroy; var i: Integer; begin LockManage; try for i := 0 to FHashList.Count - 1 do Dispose( FHashList[i] ); finally UnLockManage; end; FreeAndNil( FHashList ); DeleteCriticalSection( FLock ); inherited; end; procedure TxdClientHashManage.DoFileShareManageOnAddEvent(Sender: TObject; const Ap: PFileShareInfo); begin AddHash( Ap^.FFileHash, Ap^.FWebHash ); end; function TxdClientHashManage.DoGetServerInfo(const AServerStyle: TServerStyle; var AServerInfos: TAryServerInfo): Boolean; begin // if AServerStyle = srvHash then // begin // Result := True; // SetLength( AServerInfos, 1 ); // AServerInfos[0].FServerStyle := srvHash; // AServerInfos[0].FServerIP := inet_addr( '192.168.2.102' ); // AServerInfos[0].FServerPort := 8989; // end // else Result := FServerManage.GetServerGroup( AServerStyle, AServerInfos ) > 0; // Result := Assigned(OnGetServerInfo) and OnGetServerInfo(AServerStyle, AServerInfos); end; procedure TxdClientHashManage.DoLoopFileShareManageToAddHashCallBack(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel, AFindNext: Boolean); var p: PFileShareInfo; begin p := pData; AddHash( p^.FFileHash, p^.FWebHash ); end; procedure TxdClientHashManage.DoThreadToUpdateHash; var i, j, nPos, nHashCount, nLen: Integer; oSendStream: TxdStaticMemory_1K; aryHashInfo: TAryServerInfo; p: PHashManageInfo; bEmptyFileHash, bEmptyWebHash: Boolean; begin FThreadRunning := True; //暂缓执行 for i := 0 to 60 do Sleep( 30 ); oSendStream := TxdStaticMemory_1K.Create; LockManage; try if not Assigned(FUDP) then Exit; if not DoGetServerInfo(srvHash, aryHashInfo) then Exit; nHashCount := 0; FUDP.AddCmdHead( oSendStream, CtCmd_UpdateFileHashTable ); nPos := oSendStream.Position; oSendStream.Position := oSendStream.Position + 2; for i := 0 to FHashList.Count - 1 do begin p := FHashList[i]; if p^.FStyle = hmsUpdateBoth then Continue; bEmptyFileHash := IsEmptyHash( p^.FFileHash ); bEmptyWebHash := IsEmptyHash( p^.FWebHash ); case p^.FStyle of hmsNull: begin Inc( nHashCount ); oSendStream.WriteLong( p^.FFileHash, CtHashSize ); oSendStream.WriteLong( p^.FWebHash, CtHashSize ); if not bEmptyFileHash and not bEmptyWebHash then p^.FStyle := hmsUpdateBoth else if bEmptyFileHash then p^.FStyle := hmsUpdateWebHash else p^.FStyle := hmsUpdateFileHash; end; hmsUpdateFileHash: begin if not bEmptyWebHash then begin Inc( nHashCount ); oSendStream.WriteLong( p^.FFileHash, CtHashSize ); oSendStream.WriteLong( p^.FWebHash, CtHashSize ); p^.FStyle := hmsUpdateBoth; end; end; hmsUpdateWebHash: begin if not bEmptyFileHash then begin Inc( nHashCount ); oSendStream.WriteLong( p^.FFileHash, CtHashSize ); oSendStream.WriteLong( p^.FWebHash, CtHashSize ); p^.FStyle := hmsUpdateBoth; end; end; end; //end: case p^.FStyle of if nHashCount >= 10 then begin nLen := oSendStream.Position; oSendStream.Position := nPos; oSendStream.WriteWord( nHashCount ); for j := 0 to Length(aryHashInfo) - 1 do FUDP.SendBuffer( aryHashInfo[j].FServerIP, aryHashInfo[j].FServerPort, oSendStream.Memory, nLen ); oSendStream.Clear; FUDP.AddCmdHead( oSendStream, CtCmd_UpdateFileHashTable ); nPos := oSendStream.Position; oSendStream.Position := oSendStream.Position + 2; nHashCount := 0; end; end; if nHashCount > 0 then begin nLen := oSendStream.Position; oSendStream.Position := nPos; oSendStream.WriteWord( nHashCount ); for j := 0 to Length(aryHashInfo) - 1 do FUDP.SendBuffer( aryHashInfo[j].FServerIP, aryHashInfo[j].FServerPort, oSendStream.Memory, nLen ); end; finally UnLockManage; FThreadRunning := False; FreeAndNil( oSendStream ); SetLength( aryHashInfo, 0 ); end; end; procedure TxdClientHashManage.LockManage; begin EnterCriticalSection( FLock ); end; procedure TxdClientHashManage.UnLockManage; begin LeaveCriticalSection( FLock ); end; end.
{******************************************************************************* 作者: dmzn@163.com 2010-9-5 描述: 内容编辑区 *******************************************************************************} unit UEditControl; interface uses Windows, Forms, StdCtrls, Classes, Controls, SysUtils, Graphics; type PBitmapDataItem = ^TBitmapDataItem; TBitmapDataItem = record FBitmap: TBitmap; //图片内容 FText: string; //文本内容 FFont: TFont; //字体风格 FVerAlign: Byte; FHorAlign: Byte; //排列模式 FModeEnter: string[2]; FModeExit: string[2]; //进出场模式 FSpeedEnter: string[2]; FSpeedExit: string[2]; //进出场速度 FKeedTime: string[2]; FModeSerial: string[2]; //停留时间,跟随前屏 end; TDynamicBitmapArray = array of TBitmap; //图片数组 TDynamicBitmapDataArray = array of TBitmapDataItem; //图片数据数组 TScrollMode = (smNormal, smHor, smVer); //字母滚动模式: 常规,纯水平,纯垂直 THBEditControl = class(TGraphicControl) private FText: string; //文本 FActiveData: PBitmapDataItem; FData: TList; //数据 FHasClock: Boolean; //有时钟 FClockWidth: Word; //时钟宽度 FNormalFont: TFont; //常规字体 FWraper: TMemo; //分行对象 FHideBlank: Boolean; //消除空格 protected procedure Paint; override; procedure PaintClock; //绘制 function NewDataItem(var nIdx: Integer; const nList: TList): Boolean; //新建数据内容 function TextWidth: Integer; //文本区宽度 procedure WrapText(const nText: string; const nFont: TFont); //拆分文本 function HorPaint(var nBMPs: TDynamicBitmapArray): Boolean; function VerPaint(var nBMPs: TDynamicBitmapArray): Boolean; //按特定用途绘制 function SplitData(const nList: TList; nData: TDynamicBitmapArray): Boolean; //拆分数据 public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //创建释放 procedure DeleteData(const nData: TList; const nIdx: Integer); procedure ClearData(const nData: TList; const nFree: Boolean = True; nForm: Integer = 0); //清理资源 function SpitTextVer(const nData: TList): Boolean; function SpitTextHor(const nData: TList): Boolean; function SpitTextNormal(const nData: TList): Boolean; //拆分文本 procedure PaintData(const nValue: PBitmapDataItem); //绘制文本内容 procedure SetActiveData(const nValue: PBitmapDataItem; const nFocus: Boolean = False); //设置活动数据 function ScrollMode: TScrollMode; //滚动模式 property Data: TList read FData; property NormalFont: TFont read FNormalFont; property Text: string read FText write FText; property ActiveData: PBitmapDataItem read FActiveData; property HasClock: Boolean read FHasClock write FHasClock; property HideBlank: Boolean read FHideBlank write FHideBlank; end; implementation uses IniFiles, ULibFun, UMgrLang, USysConst; const cYes = '01'; cNo = '00'; cWord = '00'; cChar = '01'; //------------------------------------------------------------------------------ constructor THBEditControl.Create(AOwner: TComponent); var nStr: string; nIni: TIniFile; begin inherited; ParentFont := True; Width := 128; Height := 64; FText := ''; FHasClock := False; HideBlank := False; FActiveData := nil; FData := TList.Create; FWraper := TMemo.Create(AOwner); FWraper.Visible := False; FNormalFont := TFont.Create; FNormalFont.Assign(Font); FNormalFont.Color := clRed; nIni := TIniFile.Create(gPath + sFormConfig); try nStr := nIni.ReadString('Editor', 'FontName', ''); if nStr <> '' then FNormalFont.Name := nStr; nStr := nIni.ReadString('Editor', 'FontSize', ''); if IsNumber(nStr, False) then FNormalFont.Size := StrToInt(nStr); if FNormalFont.Size < 9 then FNormalFont.Size := 9; nStr := nIni.ReadString('Editor', 'FontColor', ''); if IsNumber(nStr, False) then FNormalFont.Color := StrToInt(nStr); finally nIni.Free; end; end; destructor THBEditControl.Destroy; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try nIni.WriteString('Editor', 'FontName', FNormalFont.Name); nIni.WriteInteger('Editor', 'FontSize', FNormalFont.Size); nIni.WriteInteger('Editor', 'FontColor', FNormalFont.Color); finally nIni.Free; FNormalFont.Free; end; ClearData(FData); inherited; end; //Desc: 删除nData中索引为nIdx的数据 procedure THBEditControl.DeleteData(const nData: TList; const nIdx: Integer); var nItem: PBitmapDataItem; begin if (nIdx > -1) and (nIdx < nData.Count) then begin nItem := nData[nIdx]; if nItem = FActiveData then FActiveData := nil; //xxxxx nItem.FBitmap.Free; nItem.FBitmap := nil; nItem.FFont.Free; nItem.FFont := nil; Dispose(nItem); nData.Delete(nIdx); end; end; //Date: 2010-9-8 //Parm: 数据;是否释放;开始位置 //Desc: 从nForm索引开始释放nData列表中的数据 procedure THBEditControl.ClearData(const nData: TList; const nFree: Boolean; nForm: Integer); var nIdx: Integer; begin if (nForm < 0) or nFree then nForm := 0; //索引矫正 for nIdx:=nData.Count - 1 downto nForm do DeleteData(nData, nIdx); //xxxxx if nFree then nData.Free; //释放对象 end; //Desc: 有效的文本区宽度 function THBEditControl.TextWidth: Integer; begin Result := Width - FClockWidth; if Result <= 0 then Result := 1; end; //Desc: 将nValue的内容自动换行 procedure THBEditControl.WrapText(const nText: string; const nFont: TFont); begin FWraper.Parent := Self.Parent; FWraper.Width := TextWidth; FWraper.Height := Height * 3; FWraper.Font.Assign(nFont); Application.ProcessMessages; FWraper.Text := nText; end; //Desc: 绘制nValue的内容到nValue.FBitmap procedure THBEditControl.PaintData(const nValue: PBitmapDataItem); var nIdx,nLen: Integer; nL,nT,nW,nH: Integer; begin with nValue^ do begin if not Assigned(FBitmap) then FBitmap := TBitmap.Create; FBitmap.Width := TextWidth; FBitmap.Height := Height; FBitmap.Canvas.Brush.Color := clBlack; FBitmap.Canvas.FillRect(Rect(0, 0, FBitmap.Width, FBitmap.Height)); FBitmap.Canvas.Font.Assign(nValue.FFont); SetBkMode(FBitmap.Canvas.Handle, TRANSPARENT); WrapText(nValue.FText, nValue.FFont); nLen := FWraper.Lines.Count - 1; if nValue.FVerAlign = 0 then //据上 nT := 0 else begin nH := 0; for nIdx:=0 to nLen do nH := nH + FBitmap.Canvas.TextHeight(FWraper.Lines[nIdx]); //内容总高度 if nValue.FVerAlign = 1 then //居中 nT := Trunc((Height - nH) / 2) else nT := Height - nH; //居下 end; for nIdx:=0 to nLen do begin if nValue.FHorAlign = 0 then nL := 0 else begin nW := FBitmap.Canvas.TextWidth(FWraper.Lines[nIdx]); //本行宽 if nValue.FHorAlign = 1 then //居中 nL := Trunc((Width - nW) / 2) else nL := Width - nW; //居右 end; FBitmap.Canvas.TextOut(nL, nT, FWraper.Lines[nIdx]); nH := FBitmap.Canvas.TextHeight(FWraper.Lines[nIdx]); nT := nT + nH; if nT >= Height then Break; end; end; end; //Desc: 设置活动数据 procedure THBEditControl.SetActiveData(const nValue: PBitmapDataItem; const nFocus: Boolean = False); begin if (nValue = FActiveData) and (not nFocus) then Exit; //不需要更新 if Assigned(nValue) then PaintData(nValue); //xxxxx FActiveData := nValue; Invalidate; end; procedure THBEditControl.Paint; begin Canvas.Brush.Color := clBlack; Canvas.FillRect(ClientRect); FClockWidth := 0; if FHasClock then PaintClock; if Assigned(FActiveData) and Assigned(FActiveData.FBitmap) then begin Canvas.Draw(FClockWidth+1, 0, FActiveData.FBitmap); end; end; function WeekNow: string; begin case DayOfWeek(Now) of 1: Result := '日'; 2: Result := '一'; 3: Result := '二'; 4: Result := '三'; 5: Result := '四'; 6: Result := '五'; 7: Result := '六'; end; Result := '星期' + Result; end; //Desc: 绘制时钟 procedure THBEditControl.PaintClock; var nStr: string; nL,nT,nW,nH: Word; begin with gSysParam do begin if FClockChar = cChar then FClockWidth := 64 else FClockWidth := 96; Canvas.Brush.Color := clSkyBlue; Canvas.FillRect(Rect(1, 1, FClockWidth, Height-1)); Canvas.Font.Assign(Font); SetBkMode(Canvas.Handle, TRANSPARENT); if Height < 17 then begin nStr := Time2Str(Now); nW := Canvas.TextWidth(nStr); nH := Canvas.TextHeight(nStr); nL := Trunc((FClockWidth - nW) / 2); nT := Trunc((Height - nH) / 2); Canvas.Font.Color := clRed; Canvas.TextOut(nL, nT, nStr); end else if Height < 33 then begin if gSysParam.FClockChar = '00' then begin nStr := ML('YYYY年MM月DD日', sMLCommon); nStr := FormatDateTime(nStr, Date()); end else nStr := Date2Str(Now); nW := Canvas.TextWidth(nStr); nL := Trunc((FClockWidth - nW) / 2); Canvas.Font.Color := clRed; Canvas.TextOut(nL, 1, nStr); nStr := Time2Str(Now); nW := Canvas.TextWidth(nStr); nH := Canvas.TextHeight(nStr); nL := Trunc((FClockWidth - nW) / 2); nT := Height - nH - 1; Canvas.Font.Color := clRed; Canvas.TextOut(nL, nT, nStr); end else begin if gSysParam.FClockChar = '00' then begin nStr := ML('YYYY年MM月DD日', sMLCommon); nStr := FormatDateTime(nStr, Date()); end else nStr := Date2Str(Now); nW := Canvas.TextWidth(nStr); nL := Trunc((FClockWidth - nW) / 2); Canvas.Font.Color := clRed; Canvas.TextOut(nL, 1, nStr); nStr := Time2Str(Now); nW := Canvas.TextWidth(nStr); nH := Canvas.TextHeight(nStr); nL := Trunc((FClockWidth - nW) / 2); nT := Height - nH - 1; Canvas.Font.Color := clRed; Canvas.TextOut(nL, nT, nStr); nStr := ML(WeekNow, sMLCommon); nW := Canvas.TextWidth(nStr); nH := Canvas.TextHeight(nStr); nL := Trunc((FClockWidth - nW) / 2); nT := Trunc((Height - nH) / 2); Canvas.Font.Color := clRed; Canvas.TextOut(nL, nT, nStr); end; end; end; //------------------------------------------------------------------------------ //Date: 2010-9-8 //Parm: 索引;列表 //Desc: 在nList中创建索引为nIdx的数据项,若新创建返回true function THBEditControl.NewDataItem(var nIdx: Integer; const nList: TList): Boolean; var nItem: PBitmapDataItem; begin if (nIdx > -1) and (nIdx < nList.Count) then begin PBitmapDataItem(nList[nIdx]).FText := ''; Result := False; Exit; end; New(nItem); nIdx := nList.Add(nItem); FillChar(nItem^, SizeOf(TBitmapDataItem), #0); nItem.FFont := TFont.Create; nItem.FFont.Assign(FNormalFont); nItem.FVerAlign := 0; nItem.FHorAlign := 0; nItem.FModeEnter := '03'; nItem.FModeExit := '03'; nItem.FSpeedEnter := '05'; nItem.FSpeedExit := '05'; nItem.FKeedTime := '01'; nItem.FModeSerial := '01'; Result:= True; end; //Desc: 正常拆分模式 function THBEditControl.SpitTextNormal(const nData: TList): Boolean; var nStr: string; nItem: PBitmapDataItem; i,nIdx,nLen,nT,nH: Integer; begin Result := False; FText := TrimLeft(FText); if FText = '' then begin ClearData(nData); Exit; end; nIdx := 0; NewDataItem(nIdx, nData); nItem := nData[nIdx]; nStr := FText; while nStr <> '' do begin WrapText(nStr, nItem.FFont); nT := 0; nLen := FWraper.Lines.Count - 1; for i:=0 to nLen do begin if nItem.FText = '' then nItem.FText := FWraper.Lines[i] else nItem.FText := nItem.FText + #13#10 + FWraper.Lines[i]; System.Delete(nStr, 1, Length(FWraper.Lines[i])); if (Length(nStr) > 0) and (nStr[1] = #13) then System.Delete(nStr, 1, 1); if (Length(nStr) > 0) and (nStr[1] = #10) then System.Delete(nStr, 1, 1); Canvas.Font.Assign(nItem.FFont); nH := Canvas.TextHeight(FWraper.Lines[i]); nT := nT + nH; if i < nLen then nH := Canvas.TextHeight(FWraper.Lines[i+1]) else Break; //下一行高 if nT + nH > Height then begin Inc(nIdx); NewDataItem(nIdx, nData); nItem := nData[nIdx]; Break; end; end; end; ClearData(nData, False, nIdx+1); //清理无效数据 Result := True; end; //Desc: 返回扫描模式 function THBEditControl.ScrollMode: TScrollMode; var nIdx: Integer; nItem: PBitmapDataItem; begin Result := smNormal; for nIdx:=0 to FData.Count - 1 do begin nItem := FData[nIdx]; if nIdx = 0 then begin if (nItem.FModeEnter = '03') and (nItem.FModeSerial = '01') then Result := smHor else if (nItem.FModeEnter = '08') and (nItem.FModeSerial = '01') then Result := smVer; end else begin if not (( (Result = smHor) and (nItem.FModeEnter = '03') and (nItem.FModeSerial = '01') ) or ( (Result = smVer) and (nItem.FModeEnter = '08') and (nItem.FModeSerial = '01') )) then begin Result := smNormal; Break; end; end; end; end; //------------------------------------------------------------------------------ //Desc: 将nBmp按照nW,nH大小拆分,结果存入nData中. function SplitPicture(const nBmp: TBitmap; const nW,nH: Integer; var nData: TDynamicBitmapArray): Boolean; var nSR,nDR: TRect; nL,nT,nIdx: integer; begin nT := 0; SetLength(nData, 0); while nT < nBmp.Height do begin nL := 0; while nL < nBmp.Width do begin nIdx := Length(nData); SetLength(nData, nIdx + 1); nData[nIdx] := TBitmap.Create; nData[nIdx].Width := nW; nData[nIdx].Height := nH; nSR := Rect(nL, nT, nL + nW, nT + nH); nDR := Rect(0, 0, nW, nH); nData[nIdx].Canvas.CopyRect(nDR, nBmp.Canvas, nSR); //复制区域图片 Inc(nL, nW); end; Inc(nT, nH); end; Result := Length(nData) > 0; end; //Desc: 释放nBMPs中的对象 procedure ClearBitmapArray(var nBMPs: TDynamicBitmapArray); var nIdx: Integer; begin for nIdx:=Low(nBMPs) to High(nBMPs) do nBMPs[nIdx].Free; SetLength(nBMPs, 0); end; //Desc: 将nData中的图片按组件宽高拆成单屏图片 function THBEditControl.SplitData(const nList: TList; nData: TDynamicBitmapArray): Boolean; var i,nIdx: Integer; nSmall: TDynamicBitmapArray; nItem,nFirst: PBitmapDataItem; begin Result := False; if FData.Count < 1 then Exit; nFirst := FData[0]; for nIdx:=Low(nData) to High(nData) do begin Result := SplitPicture(nData[nIdx], TextWidth, Height, nSmall); if not Result then Exit; for i:=Low(nSmall) to High(nSmall) do begin New(nItem); nList.Add(nItem); FillChar(nItem^, SizeOf(TBitmapDataItem), #0); nItem.FBitmap := nSmall[i]; nItem.FModeEnter := nFirst.FModeEnter; nItem.FModeExit := nFirst.FModeExit; nItem.FModeSerial := nFirst.FModeSerial; nItem.FSpeedEnter := nFirst.FSpeedEnter; nItem.FSpeedExit := nFirst.FSpeedExit; nItem.FKeedTime := nFirst.FKeedTime; end; end; end; //Desc: 将FData中的数据绘制到nBMPs图片组中,每个图片是组件宽的整数倍 function THBEditControl.HorPaint(var nBMPs: TDynamicBitmapArray): Boolean; var nBmp,nTmp: TBitmap; nSR,nDR: TRect; nStr: WideString; nL,nT,nW,nH: Integer; i,j,nIdx,nLen: Integer; nItem,nFirst: PBitmapDataItem; //新大图 procedure NewBigBitmap; begin SetLength(nBMPs, nIdx+1); nBMPs[nIdx] := TBitmap.Create; nBMPs[nIdx].Height := Height; nBMPs[nIdx].Width := Trunc(2048 / TextWidth) * TextWidth; with nBMPs[nIdx].Canvas do begin Brush.Color := clBlack; FillRect(Rect(0, 0, nBMPs[nIdx].Width, nBMPs[nIdx].Height)); end; if Assigned(nItem) then begin nBMPs[nIdx].Canvas.Font.Assign(nItem.FFont); SetBkMode(nBMPs[nIdx].Canvas.Handle, TRANSPARENT); end; end; //新小图 procedure NewSmallBitmap; begin nBmp.Width := nW; nBmp.Height := Height; with nBmp.Canvas do begin Brush.Color := clBlack; FillRect(Rect(0, 0, nBmp.Width, nBmp.Height)); end; if Assigned(nItem) then begin nBmp.Canvas.Font.Assign(nItem.FFont); SetBkMode(nBmp.Canvas.Handle, TRANSPARENT); end; end; begin Result := FData.Count > 0; if not Result then Exit; nFirst := FData[0]; nItem := nil; nBmp := TBitmap.Create; try nL := 0; nIdx := 0; NewBigBitmap; for i:=0 to FData.Count -1 do begin nItem := FData[i]; nStr := nItem.FText; nLen := Length(nStr); nBMPs[nIdx].Canvas.Font.Assign(nItem.FFont); SetBkMode(nBMPs[nIdx].Canvas.Handle, TRANSPARENT); for j:=1 to nLen do begin nW := nBMPs[nIdx].Canvas.TextWidth(nStr[j]); if nFirst.FVerAlign = 0 then nT := 0 else begin nH := nBMPs[nIdx].Canvas.TextHeight(nStr[j]); if nFirst.FVerAlign = 1 then nT := Trunc((nBMPs[nIdx].Height - nH) / 2) else nT := nBMPs[nIdx].Height - nH; end; if nL + nW <= nBMPs[nIdx].Width then begin nBMPs[nIdx].Canvas.TextOut(nL, nT, nStr[j]); nL := nL + nW; if nL = nBMPs[nIdx].Width then begin nL := 0; Inc(nIdx); NewBigBitmap; end; Continue; end; //可容纳 NewSmallBitmap; nBmp.Canvas.TextOut(0, nT, nStr[j]); nBMPs[nIdx].Canvas.Draw(nL, 0, nBmp); //绘制半字 Inc(nIdx); NewBigBitmap; nL := nBMPs[nIdx].Width - nL; nSR := Rect(nL, 0, nBmp.Width, nBmp.Height); nDR := Rect(0, 0, nW - nL, nBMPs[nIdx].Height); nBMPs[nIdx].Canvas.CopyRect(nDR, nBmp.Canvas, nSR); //余下半字 nL := nW - nL; //下一字起始 end; end; nLen := Trunc(nL / TextWidth); if nL mod TextWidth <> 0 then Inc(nLen); nW := nLen * TextWidth; if nW < nBMPs[nIdx].Width then begin NewSmallBitmap; nBmp.Canvas.Draw(0, 0, nBMPs[nIdx]); nTmp := nBmp; nBmp := nBMPs[nIdx]; nBMPs[nIdx] := nTmp; end; finally nBmp.Free; end; end; //Desc: 单行水平滚动时拆分 function THBEditControl.SpitTextHor(const nData: TList): Boolean; var nBigs: TDynamicBitmapArray; begin SetLength(nBigs, 0); try Result := HorPaint(nBigs); if Result then Result := SplitData(nData, nBigs); //xxxxx finally ClearBitmapArray(nBigs); end; end; //Desc: 将FData中的数据绘制到nBMPs图片组中,每个图片是组件宽的整数倍 function THBEditControl.VerPaint(var nBMPs: TDynamicBitmapArray): Boolean; var nBmp,nTmp: TBitmap; nSR,nDR: TRect; nL,nT,nW,nH: Integer; i,j,nIdx,nLen: Integer; nItem,nFirst: PBitmapDataItem; //新大图 procedure NewBigBitmap; begin SetLength(nBMPs, nIdx+1); nBMPs[nIdx] := TBitmap.Create; nBMPs[nIdx].Width := TextWidth; nBMPs[nIdx].Height := Trunc(2048 / Height) * Height; with nBMPs[nIdx].Canvas do begin Brush.Color := clBlack; FillRect(Rect(0, 0, nBMPs[nIdx].Width, nBMPs[nIdx].Height)); end; if Assigned(nItem) then begin nBMPs[nIdx].Canvas.Font.Assign(nItem.FFont); SetBkMode(nBMPs[nIdx].Canvas.Handle, TRANSPARENT); end; end; //新小图 procedure NewSmallBitmap; begin nBmp.Height := nH; nBmp.Width := TextWidth; with nBmp.Canvas do begin Brush.Color := clBlack; FillRect(Rect(0, 0, nBmp.Width, nBmp.Height)); end; if Assigned(nItem) then begin nBmp.Canvas.Font.Assign(nItem.FFont); SetBkMode(nBmp.Canvas.Handle, TRANSPARENT); end; end; begin Result := FData.Count > 0; if not Result then Exit; nFirst := FData[0]; nItem := nil; nBmp := TBitmap.Create; try nT := 0; nIdx := 0; NewBigBitmap; for i:=0 to FData.Count -1 do begin nItem := FData[i]; WrapText(nItem.FText, nItem.FFont); nBMPs[nIdx].Canvas.Font.Assign(nItem.FFont); SetBkMode(nBMPs[nIdx].Canvas.Handle, TRANSPARENT); nLen := FWraper.Lines.Count - 1; for j:=0 to nLen do begin nH := nBMPs[nIdx].Canvas.TextHeight(FWraper.Lines[j]); if nFirst.FHorAlign = 0 then nL := 0 else begin nW := nBMPs[nIdx].Canvas.TextWidth(FWraper.Lines[j]); if nFirst.FHorAlign = 1 then nL := Trunc((nBMPs[nIdx].Width - nW) / 2) else nL := nBMPs[nIdx].Width - nW; end; if nT + nH <= nBMPs[nIdx].Height then begin nBMPs[nIdx].Canvas.TextOut(nL, nT, FWraper.Lines[j]); nT := nT + nH; if nT = nBMPs[nIdx].Height then begin nT := 0; Inc(nIdx); NewBigBitmap; end; Continue; end; //可容纳 NewSmallBitmap; nBmp.Canvas.TextOut(nL, 0, FWraper.Lines[j]); nBMPs[nIdx].Canvas.Draw(0, nT, nBmp); //绘制半字 Inc(nIdx); NewBigBitmap; nT := nBMPs[nIdx].Height - nT; nSR := Rect(0, nT, nBmp.Width, nBmp.Height); nDR := Rect(0, 0, nBMPs[nIdx].Width, nH - nT); nBMPs[nIdx].Canvas.CopyRect(nDR, nBmp.Canvas, nSR); //余下半字 nT := nH - nT; //下一字起始 end; end; nLen := Trunc(nT / Height); if nT mod Height <> 0 then Inc(nLen); nH := nLen * Height; if nH < nBMPs[nIdx].Height then begin NewSmallBitmap; nBmp.Canvas.Draw(0, 0, nBMPs[nIdx]); nTmp := nBmp; nBmp := nBMPs[nIdx]; nBMPs[nIdx] := nTmp; end; finally nBmp.Free; end; end; //Desc: 垂直滚动时拆分 function THBEditControl.SpitTextVer(const nData: TList): Boolean; var nBigs: TDynamicBitmapArray; begin SetLength(nBigs, 0); try Result := VerPaint(nBigs); if Result then Result := SplitData(nData, nBigs); //xxxxx finally ClearBitmapArray(nBigs); end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, StdCtrls, XLSReadWriteII; type TfrmMain = class(TForm) VST: TVirtualStringTree; XLS: TXLSReadWriteII; Label1: TLabel; edFilename: TEdit; Button1: TButton; Button2: TButton; Button4: TButton; dlgOpen: TOpenDialog; Button3: TButton; procedure Button1Click(Sender: TObject); procedure VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure Button2Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button3Click(Sender: TObject); private function ColToText(Col: integer): string; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} function TfrmMain.ColToText(Col: integer): string; var S: string; begin if (Col div 26) > 0 then S := Char(Ord('A') + (Col div 26) - 1) else S := ''; Result := S + Char(Ord('A') + (Col mod 26)); end; procedure TfrmMain.Button1Click(Sender: TObject); begin dlgOpen.FileName := edFilename.Text; if dlgOpen.Execute then edFilename.Text := dlgOpen.FileName; end; procedure TfrmMain.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := 0; end; procedure TfrmMain.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); begin if Column = 0 then CellText := IntToStr(Node.Index + 1) else CellText := XLS.Sheets[0].AsFmtString[Column - 1,Node.Index]; end; procedure TfrmMain.Button2Click(Sender: TObject); var i: integer; begin XLS.Filename := edFilename.Text; XLS.Read; VST.Header.Columns.Clear; with VST.Header.Columns.Add do begin Width := 50; Alignment := taRightJustify; end; for i := 0 to XLS.Sheets[0].LastCol do begin with VST.Header.Columns.Add do begin Width := 100; Text := ColToText(i); end; end; VST.RootNodeCount := XLS.Sheets[0].LastRow; end; procedure TfrmMain.Button4Click(Sender: TObject); begin XLS.Filename := edFilename.Text; XLS.Write; end; procedure TfrmMain.Button3Click(Sender: TObject); begin Close; end; end.
unit SendKey; interface uses Classes; Procedure SendText( S: String ); Procedure PostKeyEx32( key: Word; Const shift: TShiftState; specialkey: Boolean ); implementation uses Windows,sysutils; {************************************************************ * * Parameters: * key : virtual keycode of the key to send. For printable * keys this is simply the ANSI code (Ord(character)). * shift : state of the modifier keys. This is a set, so you * can set several of these keys (shift, control, alt, * mouse buttons) in tandem. The TShiftState type is * declared in the Classes Unit. * specialkey: normally this should be False. Set it to True to * specify a key on the numeric keypad, for example. * Description: * Uses keybd_event to manufacture a series of key events matching * the passed parameters. The events go to the control with focus. * Note that for characters key is always the upper-case version of * the character. Sending without any modifier keys will result in * a lower-case character, sending it with [ssShift] will result * in an upper-case character! *Created: 17.7.98 by P. Below ************************************************************} Procedure PostKeyEx32( key: Word; Const shift: TShiftState; specialkey: Boolean ); Type TShiftKeyInfo = Record shift: Byte; vkey : Byte; End; byteset = Set of 0..7; Const shiftkeys: Array [1..3] of TShiftKeyInfo = ((shift: Ord(ssCtrl); vkey: VK_CONTROL ), (shift: Ord(ssShift); vkey: VK_SHIFT ), (shift: Ord(ssAlt); vkey: VK_MENU )); Var flag: DWORD; bShift: ByteSet absolute shift; i: Integer; Begin For i := 1 To 3 Do Begin If shiftkeys[i].shift In bShift Then keybd_event( shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0), 0, 0); End; { For } If specialkey Then flag := KEYEVENTF_EXTENDEDKEY Else flag := 0; keybd_event( key, MapvirtualKey( key, 0 ), flag, 0 ); flag := flag or KEYEVENTF_KEYUP; keybd_event( key, MapvirtualKey( key, 0 ), flag, 0 ); For i := 3 DownTo 1 Do Begin If shiftkeys[i].shift In bShift Then keybd_event( shiftkeys[i].vkey, MapVirtualKey(shiftkeys[i].vkey, 0), KEYEVENTF_KEYUP, 0); End; { For } End; { PostKeyEx32 } Procedure SendText( S: String ); Procedure SendRawCharacter( ch : Char ); Var i: Integer; numStr: String; Begin numStr := Format('%4.4d',[Ord(ch)]); keybd_event( VK_MENU, MapVirtualKey(VK_MENU, 0), 0, 0); for i:= 1 to Length(numStr) do PostKeyEx32( VK_NUMPAD0 + Ord(numstr[i])-Ord('0'), [], false ); keybd_event( VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0); End; Var flags: TShiftState; vcode: word; ret : word; i, n : Integer; mask : word; Begin { SendText } For i := 1 To Length(S) Do Begin ret := VkKeyScan( S[i] ); If ret = $FFFF Then SendRawCharacter( S[i] ) Else Begin vcode := Lobyte( ret ); flags := []; mask := $100; For n := 1 To 3 Do Begin If (ret and mask) <> 0 Then Begin Case mask Of $100: Include( flags, ssShift ); $200: Include( flags, ssCtrl ); $400: Include( flags, ssAlt ); End; { Case } End; { If } mask := mask shl 1; End; { For } PostKeyEx32( vcode, flags, false ); End; { Else } End; { For } End; { SendText } end.
unit uPermissoes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList; const ImageIndexNaoPermitido = 0; ImageIndexPermitido = 1; ImageIndexGrupo = 2; type TTreeNodeExpandido = class(TTreeNode) private fCodigo: Integer; public property Codigo: Integer read fCodigo write fCodigo; end; TPermissoesEventos = class class procedure TreeViewDoubleClick(Sender: TObject); class procedure TreeViewCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); end; TPermissoes = class(TObject) private fImages: TImageList; fNodoPaiAtual: TTreeNode; fTreeView: TTreeView; procedure setImages(const Value: TImageList); procedure setTreeView(const Value: TTreeView); property NodoPaiAtual: TTreeNode read fNodoPaiAtual write fNodoPaiAtual; public procedure AdicionarNodoPai(Nome: String; Codigo: Integer); procedure AdicionarNodoFilho(Nome: String; Codigo: Integer); procedure Expandir(); function Localizar(Nome: String): TTreeNode; Constructor Create(); Destructor Destroy; override; property TreeView: TTreeView read fTreeView write setTreeView; property Images: TImageList read fImages write setImages; end; implementation uses CommCtrl; { TPermissoes } class procedure TPermissoesEventos.TreeViewCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); begin NodeClass := TTreeNodeExpandido; end; class procedure TPermissoesEventos.TreeViewDoubleClick(Sender: TObject); var NodeSelectionado: TTreeNode; P: TPoint; begin GetCursorPos(P); P := TTreeView(Sender).ScreenToClient(P); if (htOnItem in TTreeView(Sender).GetHitTestInfoAt(P.X, P.Y)) then begin NodeSelectionado := TTreeView(Sender).Selected; if (NodeSelectionado.StateIndex <> ImageIndexGrupo) then if (NodeSelectionado.StateIndex = ImageIndexNaoPermitido) then begin NodeSelectionado.StateIndex := ImageIndexPermitido; NodeSelectionado.SelectedIndex := ImageIndexPermitido; NodeSelectionado.ImageIndex := ImageIndexPermitido; end else begin NodeSelectionado.StateIndex := ImageIndexNaoPermitido; NodeSelectionado.SelectedIndex := ImageIndexNaoPermitido; NodeSelectionado.ImageIndex := ImageIndexNaoPermitido; end; end; end; procedure TPermissoes.AdicionarNodoFilho(Nome: String; Codigo: Integer); var NovoNode: TTreeNode; begin NovoNode := TreeView.Items.AddChild(NodoPaiAtual, Nome); NovoNode.StateIndex := ImageIndexNaoPermitido; NovoNode.SelectedIndex := ImageIndexNaoPermitido; NovoNode.ImageIndex := ImageIndexNaoPermitido; TTreeNodeExpandido(NovoNode).Codigo := Codigo; end; procedure TPermissoes.AdicionarNodoPai(Nome: String; Codigo: Integer); var NovoNode: TTreeNode; treeItem: TTVItem; begin NovoNode := TreeView.Items.AddChild(nil, Nome); NovoNode.StateIndex := ImageIndexGrupo; NovoNode.SelectedIndex := ImageIndexGrupo; NovoNode.ImageIndex := ImageIndexGrupo; treeItem.hItem := NovoNode.ItemId; treeItem.stateMask := TVIS_BOLD; treeItem.mask := TVIF_HANDLE or TVIF_STATE; treeItem.state := TVIS_BOLD; TreeView_SetItem(NovoNode.Handle, treeItem); NodoPaiAtual := NovoNode; end; constructor TPermissoes.Create; begin end; destructor TPermissoes.Destroy; begin TreeView := nil; Images := nil; NodoPaiAtual := nil; inherited; end; procedure TPermissoes.Expandir(); begin TreeView.FullExpand; end; function TPermissoes.Localizar(Nome: String): TTreeNode; var Node: TTreeNode; begin Result := nil; if (TreeView.Items.Count = 0) then Exit; Node := TreeView.Items[0]; while (Node <> nil) do begin if (AnsiUpperCase(Node.Text) = AnsiUpperCase(Nome)) then begin Result := Node; // if AVisible then // Result.MakeVisible; Break; end; Node := Node.GetNext; end; end; procedure TPermissoes.setImages(const Value: TImageList); begin fImages := Value; if (TreeView <> nil) and (fImages <> nil) then begin TreeView.Images := fImages; end; end; procedure TPermissoes.setTreeView(const Value: TTreeView); begin fTreeView := Value; if (fImages <> nil) and (fTreeView <> nil) then TreeView.Images := fImages; if (fTreeView <> nil) then begin TreeView.OnDblClick := TPermissoesEventos.TreeViewDoubleClick; TreeView.OnCreateNodeClass := TPermissoesEventos.TreeViewCreateNodeClass; end; end; end.
{ Copyright 2019 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2019-Dec-30 Darian Miller: Unit created for Universal Markup Editor project } unit iaWin.Utils; interface uses WinAPI.Windows, WinAPI.Messages; type TiaWinUtils = class public class procedure CloseHandle(var h:THandle); class function CreateFileIfNotExists(const pFullPathName:string):Boolean; class function GetAbsolutePath(const pFileName:string; const pBaseDirectory:string):string; class function GetFileSize(const pFileName:string):Int64; class function GetTempFileName(const pThreeCharPrefix:string='tmp'):string; class function GetTempFilePath():string; class function GetWindowsFolder():string; class function GetWindowsSystemRoot():string; class function IsValidHandle(const h:THandle):Boolean; class procedure ShellOpenDocument(const pDoc:string); class function ShowFileInExplorer(const pFileName:string):Boolean; end; implementation uses System.SysUtils, WinAPI.ShellApi, WinAPI.ShLwApi, WinAPI.ShlObj; class procedure TiaWinUtils.CloseHandle(var h:THandle); begin if TiaWinUtils.IsValidHandle(h) then begin WinAPI.Windows.CloseHandle(h); end; h := INVALID_HANDLE_VALUE; end; class function TiaWinUtils.IsValidHandle(const h:THandle):Boolean; begin Result := (h <> INVALID_HANDLE_VALUE) and (h <> 0); end; class function TiaWinUtils.GetFileSize(const pFileName:string):Int64; var vFileInfo:TWin32FileAttributeData; begin Result := -1; if GetFileAttributesEx(PWideChar(pFileName), GetFileExInfoStandard, @vFileInfo) then begin Int64Rec(Result).Lo := vFileInfo.nFileSizeLow; Int64Rec(Result).Hi := vFileInfo.nFileSizeHigh; end; end; class function TiaWinUtils.GetWindowsFolder():string; var vLen:Integer; begin Result := ''; SetLength(Result, MAX_PATH); //https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getwindowsdirectoryw vLen := WinAPI.Windows.GetWindowsDirectory(PChar(Result), MAX_PATH); if vLen > 0 then begin SetLength(Result, vLen); end else begin RaiseLastOSError(); end; end; class function TiaWinUtils.GetWindowsSystemRoot():string; var vLen:Integer; begin Result := ''; SetLength(Result, MAX_PATH); //https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemdirectoryw vLen := WinAPI.Windows.GetSystemDirectory(PChar(Result), MAX_PATH); if vLen > 0 then begin SetLength(Result, vLen); end else begin RaiseLastOSError(); end; end; class function TiaWinUtils.GetTempFilePath():string; var vLen:Integer; begin Result := ''; SetLength(Result, MAX_PATH); //https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppathw vLen := WinAPI.Windows.GetTempPath(MAX_PATH, PChar(Result)); if vLen > 0 then begin SetLength(Result, vLen); end else begin RaiseLastOSError(); end; end; class function TiaWinUtils.GetTempFileName(const pThreeCharPrefix:string='tmp'):string; var vDirectory:String; vFileName:array[0..MAX_PATH] of char; begin Result := ''; vDirectory := TiaWinUtils.GetTempFilePath(); SetLength(Result, MAX_PATH); //https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettempfilenamew if WinAPI.Windows.GetTempFileName(PChar(vDirectory), PChar(pThreeCharPrefix), 0, vFileName) <> 0 then begin Result := vFileName; end else begin RaiseLastOSError(); end; end; //From David Hefferman: https://stackoverflow.com/a/5330691/35696 class function TiaWinUtils.GetAbsolutePath(const pFileName:string; const pBaseDirectory:string):string; var Buffer: array [0..MAX_PATH-1] of Char; begin //https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathisrelativew if PathIsRelative(PChar(pFileName)) then begin Result := IncludeTrailingPathDelimiter(pBaseDirectory)+pFileName; end else begin Result := pFileName; end; //https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathcanonicalizew if PathCanonicalize(@Buffer[0], PChar(Result)) then begin Result := Buffer; end; end; class procedure TiaWinUtils.ShellOpenDocument(const pDoc:string); begin ShellExecute(0, 'open', PChar(pDoc), nil, nil, SW_SHOWNORMAL); end; class function TiaWinUtils.ShowFileInExplorer(const pFileName:string):Boolean; var IIDL: PItemIDList; begin Result := False; if FileExists(pFileName) then begin IIDL := ILCreateFromPath(PChar(pFileName)); if IIDL <> nil then begin try Result := (SHOpenFolderAndSelectItems(IIDL, 0, nil, 0) = S_OK); finally ILFree(IIDL); end; end; end; end; class function TiaWinUtils.CreateFileIfNotExists(const pFullPathName:string):Boolean; var h:THandle; begin Result := False; //check GetLastError if fail //https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew h := CreateFile(PChar(pFullPathName), FILE_APPEND_DATA, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0); if IsValidHandle(h) then begin CloseHandle(h); Result := True; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_RESOLUCAO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit EcfResolucaoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, EcfPosicaoComponentesVO; type [TEntity] [TTable('ECF_RESOLUCAO')] TEcfResolucaoVO = class(TVO) private FID: Integer; FRESOLUCAO_TELA: String; FLARGURA: Integer; FALTURA: Integer; FIMAGEM_TELA: String; FIMAGEM_MENU: String; FIMAGEM_SUBMENU: String; FHOTTRACK_COLOR: String; FITEM_STYLE_FONT_NAME: String; FITEM_STYLE_FONT_COLOR: String; FITEM_SEL_STYLE_COLOR: String; FLABEL_TOTAL_GERAL_FONT_COLOR: String; FITEM_STYLE_FONT_STYLE: String; FEDITS_COLOR: String; FEDITS_FONT_COLOR: String; FEDITS_DISABLED_COLOR: String; FEDITS_FONT_NAME: String; FEDITS_FONT_STYLE: String; FListaEcfPosicaoComponentesVO: TObjectList<TEcfPosicaoComponentesVO>; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('RESOLUCAO_TELA', 'Resolucao Tela', 160, [ldGrid, ldLookup, ldCombobox], False)] property ResolucaoTela: String read FRESOLUCAO_TELA write FRESOLUCAO_TELA; [TColumn('LARGURA', 'Largura', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Largura: Integer read FLARGURA write FLARGURA; [TColumn('ALTURA', 'Altura', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Altura: Integer read FALTURA write FALTURA; [TColumn('IMAGEM_TELA', 'Imagem Tela', 400, [ldGrid, ldLookup, ldCombobox], False)] property ImagemTela: String read FIMAGEM_TELA write FIMAGEM_TELA; [TColumn('IMAGEM_MENU', 'Imagem Menu', 400, [ldGrid, ldLookup, ldCombobox], False)] property ImagemMenu: String read FIMAGEM_MENU write FIMAGEM_MENU; [TColumn('IMAGEM_SUBMENU', 'Imagem Submenu', 400, [ldGrid, ldLookup, ldCombobox], False)] property ImagemSubmenu: String read FIMAGEM_SUBMENU write FIMAGEM_SUBMENU; [TColumn('HOTTRACK_COLOR', 'Hottrack Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property HottrackColor: String read FHOTTRACK_COLOR write FHOTTRACK_COLOR; [TColumn('ITEM_STYLE_FONT_NAME', 'Item Style Font Name', 160, [ldGrid, ldLookup, ldCombobox], False)] property ItemStyleFontName: String read FITEM_STYLE_FONT_NAME write FITEM_STYLE_FONT_NAME; [TColumn('ITEM_STYLE_FONT_COLOR', 'Item Style Font Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property ItemStyleFontColor: String read FITEM_STYLE_FONT_COLOR write FITEM_STYLE_FONT_COLOR; [TColumn('ITEM_SEL_STYLE_COLOR', 'Item Sel Style Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property ItemSelStyleColor: String read FITEM_SEL_STYLE_COLOR write FITEM_SEL_STYLE_COLOR; [TColumn('LABEL_TOTAL_GERAL_FONT_COLOR', 'Label Total Geral Font Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property LabelTotalGeralFontColor: String read FLABEL_TOTAL_GERAL_FONT_COLOR write FLABEL_TOTAL_GERAL_FONT_COLOR; [TColumn('ITEM_STYLE_FONT_STYLE', 'Item Style Font Style', 160, [ldGrid, ldLookup, ldCombobox], False)] property ItemStyleFontStyle: String read FITEM_STYLE_FONT_STYLE write FITEM_STYLE_FONT_STYLE; [TColumn('EDITS_COLOR', 'Edits Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property EditsColor: String read FEDITS_COLOR write FEDITS_COLOR; [TColumn('EDITS_FONT_COLOR', 'Edits Font Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property EditsFontColor: String read FEDITS_FONT_COLOR write FEDITS_FONT_COLOR; [TColumn('EDITS_DISABLED_COLOR', 'Edits Disabled Color', 160, [ldGrid, ldLookup, ldCombobox], False)] property EditsDisabledColor: String read FEDITS_DISABLED_COLOR write FEDITS_DISABLED_COLOR; [TColumn('EDITS_FONT_NAME', 'Edits Font Name', 160, [ldGrid, ldLookup, ldCombobox], False)] property EditsFontName: String read FEDITS_FONT_NAME write FEDITS_FONT_NAME; [TColumn('EDITS_FONT_STYLE', 'Edits Font Style', 160, [ldGrid, ldLookup, ldCombobox], False)] property EditsFontStyle: String read FEDITS_FONT_STYLE write FEDITS_FONT_STYLE; [TManyValuedAssociation('ID_ECF_RESOLUCAO', 'ID')] property ListaEcfPosicaoComponentesVO: TObjectList<TEcfPosicaoComponentesVO> read FListaEcfPosicaoComponentesVO write FListaEcfPosicaoComponentesVO; end; implementation constructor TEcfResolucaoVO.Create; begin inherited; FListaEcfPosicaoComponentesVO := TObjectList<TEcfPosicaoComponentesVO>.Create; end; destructor TEcfResolucaoVO.Destroy; begin FreeAndNil(FListaEcfPosicaoComponentesVO); inherited; end; initialization Classes.RegisterClass(TEcfResolucaoVO); finalization Classes.UnRegisterClass(TEcfResolucaoVO); end.
unit fListaCliente; interface uses Generics.Collections, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, Aurelius.Bind.Dataset, Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, Aurelius.Engine.ObjectManager, Entidades.Cadastro, StdCtrls, ExtCtrls, DBGrids, Mask, DBCtrls; type TfmClientes = class(TForm) tbObjetos: TAureliusDataset; tbObjetosSelf: TAureliusEntityField; tbObjetosId: TIntegerField; tbObjetosNome: TStringField; tbObjetosFone: TStringField; tbObjetosCelular: TStringField; tbObjetosEmail: TStringField; DataSource1: TDataSource; Panel1: TPanel; btNovo: TButton; Label4: TLabel; DBEdit4: TDBEdit; Label5: TLabel; DBEdit5: TDBEdit; Label6: TLabel; DBEdit6: TDBEdit; DBAdvGrid1: TDBAdvGrid; btEditar: TButton; btExcluir: TButton; edFilter: TEdit; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btNovoClick(Sender: TObject); procedure btEditarClick(Sender: TObject); procedure DBAdvGrid1DblClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure tbObjetosFilterRecord(DataSet: TDataSet; var Accept: Boolean); procedure edFilterChange(Sender: TObject); procedure Timer1Timer(Sender: TObject); private class var FInstance: TfmClientes; FLista: TList<TCliente>; FManager: TObjectManager; procedure RefreshLista; public class procedure Mostra; end; implementation uses Aurelius.Criteria.Base, fCliente, dConnection; {$R *.dfm} procedure TfmClientes.btEditarClick(Sender: TObject); begin if tbObjetos.Current<TCliente> <> nil then if TfmCliente.Editar(tbObjetos.Current<TCliente>.Id) then // RefreshLista; end; procedure TfmClientes.btExcluirClick(Sender: TObject); begin if tbObjetos.Current<TCliente> <> nil then if MessageDlg('Confirma a exclusão desse registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin FManager.Remove(tbObjetos.Current<TCliente>); RefreshLista; end; end; procedure TfmClientes.btNovoClick(Sender: TObject); begin if TfmCliente.Editar(Null) then RefreshLista; end; procedure TfmClientes.DBAdvGrid1DblClick(Sender: TObject); begin btEditarClick(nil); end; procedure TfmClientes.edFilterChange(Sender: TObject); begin Timer1.Enabled := false; Timer1.Enabled := true; end; procedure TfmClientes.FormCreate(Sender: TObject); begin FManager := dmConnection.CreateManager; end; procedure TfmClientes.FormDestroy(Sender: TObject); begin FLista.Free; FManager.Free; end; class procedure TfmClientes.Mostra; begin if FInstance = nil then FInstance := TfmClientes.Create(Application); FInstance.Show; FInstance.RefreshLista; end; procedure TfmClientes.RefreshLista; begin tbObjetos.Close; FLista.Free; FManager.Clear; FLista := FManager.CreateCriteria<TCliente>.AddOrder(TOrder.Asc('Nome')).List; tbObjetos.SetSourceList(FLista); tbObjetos.Open; end; procedure TfmClientes.tbObjetosFilterRecord(DataSet: TDataSet; var Accept: Boolean); var AText: string; begin AText := edFilter.Text; Accept := (AText = '') or (Pos(Uppercase(AText), Uppercase(Dataset.FieldByName('Nome').AsString)) > 0); end; procedure TfmClientes.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; tbObjetos.Filtered := false; tbObjetos.Filtered := true; end; end.
unit UManutAnuidadesRegPagto; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UnitModeloComum, WinSkinData, ExtCtrls, StdCtrls, JvEdit, JvTypedEdit, Mask, Buttons, FMTBcd, DB, DBClient, Provider, SqlExpr; type TfrmManutAnuidadesRegPagto = class(TModeloComum) Label2: TLabel; Label1: TLabel; Label3: TLabel; labDescricao: TLabel; labVencimento: TLabel; labTotal: TLabel; Bevel1: TBevel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; edDtPagto: TMaskEdit; edValorPago: TJvCurrencyEdit; Bevel2: TBevel; BtnOK: TBitBtn; BitBtn3: TBitBtn; sdsVerRecibo: TSQLDataSet; dspVerRecibo: TDataSetProvider; cdsVerRecibo: TClientDataSet; cdsVerReciboQTDE: TIntegerField; sdsGeraRecibo: TSQLDataSet; dspGeraRecibo: TDataSetProvider; cdsGeraRecibo: TClientDataSet; cdsGeraReciboRECIBO: TStringField; edrecibo: TEdit; procedure edReciboKeyPress(Sender: TObject; var Key: Char); procedure edReciboExit(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmManutAnuidadesRegPagto: TfrmManutAnuidadesRegPagto; implementation uses UFuncoes, UDMAssociado, UDMConexao; {$R *.dfm} procedure TfrmManutAnuidadesRegPagto.edReciboKeyPress(Sender: TObject; var Key: Char); begin inherited; if ((key <#47) or (key>#58)) and (key<>#8) then key := #0; end; procedure TfrmManutAnuidadesRegPagto.edReciboExit(Sender: TObject); begin inherited; If trim(edRecibo.text)='' then edRecibo.clear; end; procedure TfrmManutAnuidadesRegPagto.BtnOKClick(Sender: TObject); begin inherited; Try strtodate(edDtPagto.Text); except Erro('Data inválida. '); edDtPagto.setfocus; ModalResult := mrnone; Abort; end; if edValorPago.Value = 0 then begin Aviso('Valor pago não pode ser zero. '); edValorPago.setfocus; ModalResult := mrnone; Abort; end; if edValorPago.Value < strtofloat( stringreplace( stringreplace(labTotal.Caption,'.','',[rfReplaceAll]) ,'R$ ','',[rfReplaceAll]) )then begin if not confirma ('Valor pago é menor que o valor a pagar. '+#13 + 'Deseja continuar? ') then begin edValorPago.setfocus; ModalResult := mrnone; Abort; end; end; If edRecibo.text<>'' then begin cdsVerRecibo.close; cdsVerRecibo.Params.ParamByName('nossonumero').value := edRecibo.text; cdsVerRecibo.open; If cdsVerReciboQTDE.value > 0 then begin Aviso('Não é possível registrar este pagamento, pois já existe um recibo com este número.'); edRecibo.setfocus; ModalResult := mrnone; abort; end; end else If edRecibo.text='' then begin cdsGeraRecibo.close; cdsGeraRecibo.Open; edRecibo.text := cdsGeraReciboRECIBO.value; cdsGeraRecibo.close; end; end; procedure TfrmManutAnuidadesRegPagto.FormShow(Sender: TObject); begin inherited; edDtPagto.setfocus; end; end.
// *************************************************************************** // // Delphi MVC Framework // // Copyright (c) 2010-2017 Daniele Teti and the DMVCFramework Team // // https://github.com/danieleteti/delphimvcframework // // *************************************************************************** // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // *************************************************************************** } unit MVCFramework.MessagingController; {$I dmvcframework.inc} interface uses System.SysUtils, System.DateUtils, System.SyncObjs, MVCFramework, MVCFramework.Commons, MVCFramework.Logger, MVCFramework.TypesAliases, StompClient; type [MVCPath('/messages')] TMVCBUSController = class(TMVCController) protected function GetUniqueDurableHeader(AClientId, ATopicName: string): string; procedure InternalSubscribeUserToTopics(AClientId: string; AStompClient: IStompClient); procedure InternalSubscribeUserToTopic(AClientId: string; ATopicName: string; AStompClient: IStompClient); procedure AddTopicToUserSubscriptions(const ATopic: string); procedure RemoveTopicFromUserSubscriptions(const ATopic: string); procedure OnBeforeAction(AContext: TWebContext; const AActionNAme: string; var AHandled: Boolean); override; public [MVCHTTPMethod([httpPOST])] [MVCPath('/clients/($clientid)')] procedure SetClientID(AContext: TWebContext); [MVCPath('/subscriptions/($topicorqueue)/($name)')] [MVCHTTPMethod([httpPOST])] procedure SubscribeToTopic(AContext: TWebContext); [MVCPath('/subscriptions/($topicorqueue)/($name)')] [MVCHTTPMethod([httpDELETE])] procedure UnSubscribeFromTopic(AContext: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath] procedure ReceiveMessages(AContext: TWebContext); [MVCHTTPMethod([httpPOST])] [MVCPath('/($type)/($topicorqueue)')] procedure EnqueueMessage(AContext: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/subscriptions')] procedure CurrentlySubscribedTopics(AContext: TWebContext); end; implementation { TMVCBUSController } procedure TMVCBUSController.AddTopicToUserSubscriptions(const ATopic: string); var x: string; topics: TArray<string>; t: string; ToAdd: Boolean; begin x := Session['__subscriptions']; topics := x.Split([';']); ToAdd := true; for t in topics do if t.Equals(ATopic) then begin ToAdd := False; end; if ToAdd then begin SetLength(topics, length(topics) + 1); topics[length(topics) - 1] := ATopic; Session['__subscriptions'] := string.Join(';', topics); end; end; procedure TMVCBUSController.CurrentlySubscribedTopics(AContext: TWebContext); begin ContentType := TMVCMediaType.TEXT_PLAIN; Render(Session['__subscriptions']); end; procedure TMVCBUSController.EnqueueMessage(AContext: TWebContext); var topicname: string; queuetype: string; begin queuetype := AContext.Request.Params['type'].Trim.ToLower; if (queuetype <> 'topic') and (queuetype <> 'queue') then raise EMVCException.Create('Valid type are "queue" or "topic", got ' + queuetype); topicname := AContext.Request.Params['topicorqueue'].Trim; if topicname.IsEmpty then raise EMVCException.Create('Invalid or empty topic'); if not AContext.Request.ThereIsRequestBody then raise EMVCException.Create('Body request required'); // EnqueueMessageOnTopicOrQueue(queuetype = 'queue', '/' + queuetype + '/' + topicname, // CTX.Request.BodyAsJSONObject.Clone as TJSONObject, true); // EnqueueMessage('/queue/' + topicname, CTX.Request.BodyAsJSONObject.Clone as TJSONObject, true); Render(200, 'Message sent to topic ' + topicname); end; function TMVCBUSController.GetUniqueDurableHeader(AClientId, ATopicName: string): string; begin Result := AClientId + '___' + ATopicName.Replace('/', '_', [rfReplaceAll]); end; procedure TMVCBUSController.ReceiveMessages(AContext: TWebContext); var Stomp: IStompClient; LClientID: string; frame: IStompFrame; obj, res: TJSONObject; LFrames: TArray<IStompFrame>; arr: TJSONArray; LLastReceivedMessageTS: TDateTime; LTimeOut: Boolean; const {$IFDEF TEST} RECEIVE_TIMEOUT = 5; // seconds {$ELSE} RECEIVE_TIMEOUT = 60 * 5; // 5 minutes {$ENDIF} begin LTimeOut := False; LClientID := GetClientID; Stomp := GetNewStompClient(LClientID); try InternalSubscribeUserToTopics(LClientID, Stomp); // StartReceiving := now; LLastReceivedMessageTS := now; SetLength(LFrames, 0); while not IsShuttingDown do begin LTimeOut := False; frame := nil; Log.Info('/messages receive', ClassName); Stomp.Receive(frame, 100); if Assigned(frame) then // get 10 messages at max, and then send them to client begin LLastReceivedMessageTS := now; SetLength(LFrames, length(LFrames) + 1); LFrames[length(LFrames) - 1] := frame; Stomp.Ack(frame.MessageID); if length(LFrames) >= 10 then break; end else begin if (length(LFrames) > 0) then break; if SecondsBetween(now, LLastReceivedMessageTS) >= RECEIVE_TIMEOUT then begin LTimeOut := true; break; end; end; end; arr := TJSONArray.Create; res := TJSONObject.Create(TJSONPair.Create('messages', arr)); for frame in LFrames do begin if Assigned(frame) then begin obj := TJSONObject.ParseJSONValue(frame.GetBody) as TJSONObject; if Assigned(obj) then begin arr.AddElement(obj); end else begin Log.Error(Format ('Not valid JSON object in topic requested by user %s. The raw message is "%s"', [LClientID, frame.GetBody]), ClassName); end; end; end; // for in res.AddPair('_timestamp', FormatDateTime('yyyy-mm-dd hh:nn:ss', now)); if LTimeOut then begin res.AddPair('_timeout', TJSONTrue.Create); // Render(http_status.RequestTimeout, res); end else begin res.AddPair('_timeout', TJSONFalse.Create); // Render(http_status.OK, res); end; finally // Stomp.Disconnect; end; end; procedure TMVCBUSController.RemoveTopicFromUserSubscriptions(const ATopic: string); var x: string; topics, afterremovaltopics: TArray<string>; IndexToRemove: Integer; i: Integer; begin x := Session['__subscriptions']; topics := x.Split([';']); IndexToRemove := 0; SetLength(afterremovaltopics, length(topics)); for i := 0 to length(topics) - 1 do begin if not topics[i].Equals(ATopic) then begin afterremovaltopics[IndexToRemove] := topics[i]; Inc(IndexToRemove); end; end; if IndexToRemove <> length(ATopic) - 1 then SetLength(afterremovaltopics, length(topics) - 1); if length(afterremovaltopics) = 0 then Session['__subscriptions'] := '' else Session['__subscriptions'] := string.Join(';', afterremovaltopics); end; procedure TMVCBUSController.SetClientID(AContext: TWebContext); begin Session[CLIENTID_KEY] := AContext.Request.Params['clientid']; end; procedure TMVCBUSController.SubscribeToTopic(AContext: TWebContext); var LStomp: IStompClient; LClientID: string; LTopicName: string; LTopicOrQueue: string; begin LClientID := GetClientID; LTopicName := AContext.Request.Params['name'].ToLower; LTopicOrQueue := AContext.Request.Params['topicorqueue'].ToLower; LStomp := GetNewStompClient(LClientID); try LTopicName := '/' + LTopicOrQueue + '/' + LTopicName; InternalSubscribeUserToTopic(LClientID, LTopicName, LStomp); Render(200, 'Subscription OK for ' + LTopicName); finally // Stomp.Disconnect; end; end; procedure TMVCBUSController.InternalSubscribeUserToTopics(AClientId: string; AStompClient: IStompClient); var x, t: string; topics: TArray<string>; begin x := Session['__subscriptions']; topics := x.Split([';']); for t in topics do InternalSubscribeUserToTopic(AClientId, t, AStompClient); end; procedure TMVCBUSController.OnBeforeAction(AContext: TWebContext; const AActionNAme: string; var AHandled: Boolean); begin inherited; if not StrToBool(Config['messaging']) then begin AHandled := true; raise EMVCException.Create('Messaging extensions are not enabled'); end; AHandled := False; end; procedure TMVCBUSController.InternalSubscribeUserToTopic(AClientId, ATopicName: string; AStompClient: IStompClient); // var // LDurSubHeader: string; // LHeaders: IStompHeaders; begin raise EMVCException.Create('Not implemented'); // LHeaders := TStompHeaders.Create; // LDurSubHeader := GetUniqueDurableHeader(clientid, topicname); // LHeaders.Add(TStompHeaders.NewDurableSubscriptionHeader(LDurSubHeader)); // // if topicname.StartsWith('/topic') then // LHeaders.Add('id', clientid); //https://www.rabbitmq.com/stomp.html // // StompClient.Subscribe(topicname, amClient, LHeaders); // LogE('SUBSCRIBE TO ' + clientid + '@' + topicname + ' dursubheader:' + LDurSubHeader); // AddTopicToUserSubscriptions(topicname); end; procedure TMVCBUSController.UnSubscribeFromTopic(AContext: TWebContext); var Stomp: IStompClient; clientid: string; thename: string; s: string; begin clientid := GetClientID; thename := AContext.Request.Params['name'].ToLower; Stomp := GetNewStompClient(clientid); s := '/queue/' + thename; Stomp.Unsubscribe(s); RemoveTopicFromUserSubscriptions(s); Render(200, 'UnSubscription OK for ' + s); end; end.
unit Types; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Datentypen, die sowohl im Prozessrechner als auch im Anzeigerechner verwendet werden. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface uses RTKernel, RTTextIO; const { Standartstackgroesse fuer die Taskerzeugung } cDefaultStack = 1024; { Taskname fuer die Benutzertask } cUserTaskName = 'Benutzer'; { Taskname fuer die CPU-Task } cCPUTaskName = 'CPU'; { Parameter, die fuer die Taskerzeugung benoetigt werden } { Loggertask } cLoggerPriority = MainPriority + 4; cLoggerStack = cDefaultStack * 6; cLoggerTaskName = 'Logger'; cLoggerMailboxSlots = 10; { IPX-Sender-Task } cIPXSenderPriority = MainPriority + 5; cIPXSenderStack = cDefaultStack * 2; cIPXSenderTaskName = 'IPX Sender'; { IPX-Empfaenger-Task } cIPXReceiverPriority = MainPriority + 5; cIPXReceiverStack = cDefaultStack * 3; cIPXReceiverTaskName = 'IPX Receiver'; { Tastentask } cKeyPriority = MainPriority + 3; cKeyStack = cDefaultStack * 2; cKeyTaskName = 'Menue'; { Systemstatustask } cSystemStatusPriority = MainPriority + 4; cSystemStatusStack = cDefaultStack * 3; cSystemStatusTaskName = 'Systemstatus'; cSystemStatusMailboxSlots = 1; sSystemStatusDisplayDuration = 2; { Parameter fuer die IPX-Kommunikation } cProcessComputerNodeName = 'P2616'; cDisplayComputerNodeName = 'D2616'; cPIPXChannel = 1; cDIPXChannel = 2; cMaxIPXInConnections = 1; cMaxIPXSendRetries = 10; cIPXSendTimeout = 10; cIPXSendBuffers = 0; cIPXConnectRetries = 10; cIPXConnectTimeOut = 10; cIPXMailboxSlots = 10; cIPXReceiveBuffers = 10; { Anzahl der Spielsteine } cTokenCount = 9; { Anzahl der Quadrate im Spielfeld } cFieldSquareCount = 3; { Spielfeldbreite } cFieldWidth = cFieldSquareCount * 2 + 1; { Spielfeldhoehe } cFieldHeight = cFieldSquareCount * 2 + 1; { Farbe zum Ausgeben von Schlaginfos } cCapturePossibilityColor = LightRed; type { Spielerarten } TPlayer = (User, CPU); { Spielsteinanzahl } TTokenCount = 0..cTokenCount; { Spielsteinanzahl beider Spieler } TPlayerTokenCount = array[TPlayer] of TTokenCount; { Anzahl der Quadrate im Spielfeld } TFieldSquareCount = 0..cFieldSquareCount; { Spielfeldbreite } TFieldWidth = 0..cFieldWidth; { Spielfeldhoehe } TFieldHeight = 0..cFieldHeight; { Spielfeldposition } TFieldPos = record X: TFieldWidth; Y: TFieldHeight; end; { Besitzer einer Spielfeldposition } TOwner = (oNone, oUser, oCPU); { Eigenschaften einer Spielfeldposition } TFieldPosProperties = record { Position ist gueltig } Valid: boolean; { Besitzer } Owner: TOwner; { Spielsteintaskhandle } TokenTH: TaskHandle; end; { Spielfeld } TField = record { Anzahl gesetzter Spielsteine } PlacedTC, { Anzahl geschlagener Spielsteine } CapturedTC: TPlayerTokenCount; { Positionen } Pos: array[Low(TFieldWidth)..High(TFieldWidth) - 1, Low(TFieldHeight)..High(TFieldHeight) - 1] of TFieldPosProperties; end; { Spielsteinzustand } TTokenState = ( { Nicht gesetzt } tsNotPlaced, { Gesetzt } tsPlaced, { Geschlagen } tsCaptured, { Geklaut durch Cheaten } tsStolen); { Ziehrichtung } TDirection = (dLeft, dRight, dUp, dDown); { Anzahl der Richtungen } TDirectionCount = 0..Ord(High(TDirection)) + 1; { Ziehrichtungsmenge } TDirectionSet = set of TDirection; { Zugmoeglichkeiten } TMovePossibilities = array[TFieldWidth, TFieldHeight] of boolean; { Spielsteindaten } TTokenData = record { Spielsteintaskhandle } TokenTH: TaskHandle; { Spielfeldposition } FieldPos: TFieldPos; { Zustand } State: TTokenState; { Moegliche Ziehrichtungen } MoveDirections: TDirectionSet; { Zugmoeglichkeiten } MovePossibilities: TMovePossibilities; end; { Spielsteindaten beider Spieler } TPlayerTokenData = array[0..cTokenCount - 1] of TTokenData; { Spielerfarben } TPlayerColors = array[TPlayer] of byte; { Spielerphase } TPlayerStage = ( { Setzen } psPlace, { Normal ziehen } psMove, { Keine Zugmoeglichkeit } psCantMove, { Springen } psFly, { Schlagen } psCapture, { Keine Schlagmoeglichkeit } psCantCapture); { Spielerphasen beider Spieler } TPlayerStages = array[TPlayer] of TPlayerStage; { Nachrichttyp fuer die Loggertask } { Nachrichtenart } TLoggerMessageKind = ( { Dateinamenpraefix } lomkFilename, { Neue Datei } lomkCreateNewFile, { Debugmeldung } lomkDebug, { Logmeldung } lomkLog, { Programmende } lomkExit); { Nachricht } TLoggerMessage = record case Kind: TLoggerMessageKind of lomkFilename: ( Filename: string; ); lomkDebug, lomkLog: ( Sender: TaskHandle; Message: string; ); end; { Zugart } TMoveKind = ( { Kein Zug } mkNoMove, { Setzen } mkPlace, { Ziehen } mkMove, { Schlagen } mkCapture, { Klauen durch Cheaten } mkSteal); { Zugdaten } TMoveData = record { Zugart } Kind: TMoveKind; { Spielertaskhandle des ziehenden Spielers } PlayerTH: TaskHandle; { Quellposition } SourceFP, { Zielposition } TargetFP: TFieldPos; end; { Zugdaten eines bestimmten Spielsteins } TTokenMoveData = record { Spielsteintaskhandle } TokenTH: TaskHandle; { Zugdaten } MoveData: TMoveData; end; { Nachichttyp fuer den Prozessrechner } { Nachrichtenart } TProcessMessageKind = ( { Zugwahl des Benutzers } prmkUserMoveSelected, { Zugbestaetigung } prmkTokenMoved, { Anfrage nach Zugmoeglichkeiten } prmkGetTokenMovePossibilities, { Spielstart } prmkStartGame, { Spielende } prmkEndGame, { Programmende } prmkExit); { Zeiger auf Nachricht fuer die IPX-Kommunikation } PProcessMessage = ^TProcessMessage; { Nachricht } TProcessMessage = record case Kind: TProcessMessageKind of prmkUserMoveSelected: ( MoveData: TMoveData; ); prmkGetTokenMovePossibilities: ( TokenTH: TaskHandle; ); prmkTokenMoved: ( TokenMoveData: TTokenMoveData; ); end; { Nachrichttyp fuer den Darstellungsrechner } { Nachrichtart } TDisplayMessageKind = ( { Initialisierung } dmkInit, { Spielerfarben } dmkPlayerColors, { Aktueller Spieler } dmkCurrentPlayer, { Zugmoeglichkeiten } dmkMovePossibilities, { Spielfeld } dmkField, { Zugdaten } dmkTokenMove, { Spielerphase } dmkPlayerStage, { Programmende } dmkExit, { Spielende } dmkGameOver); { Zeiger auf Nachricht fuer die IPX-Kommunikation } PDisplayMessage = ^TDisplayMessage; { Nachricht } TDisplayMessage = record case Kind: TDisplayMessageKind of dmkPlayerColors: ( Colors: TPlayerColors; ); dmkCurrentPlayer: ( Player: TPlayer; ); dmkMovePossibilities: ( Possibilities: TMovePossibilities; ); dmkField: ( Field: TField; ); dmkTokenMove: ( TokenMoveData: TTokenMoveData; ); dmkPlayerStage: ( Stage: TPlayerStage; ); end; { Fensterposition } TWindowPosition = record FirstCol, LastCol: ColRange; FirstRow, LastRow: RowRange; end; { Fensterfarbe } TWindowColor = record FrameColor, Attribute: byte; end; { Nachrichttyp fuer die Systemstatustask } { Nachrichtart } TSystemStatusMessageKind = ( { Fensterposition } ssmkWindowPosition, { Fensterfarbe } ssmkWindowColor, { Systemstatus } ssmkSystemStatus); { Nachricht } TSystemStatusMessage = record case Kind: TSystemStatusMessageKind of ssmkWindowPosition: ( WindowPosition: TWindowPosition; ); ssmkWindowColor: ( WindowColor: TWindowColor; ); ssmkSystemStatus: ( Message: string; ); end; implementation end.
program dequeing; type LongItem2Ptr = ^LongItem2; LongItem2 = record data: longint; prev, next: LongItem2Ptr; end; LongDeque = record first, last: LongItem2Ptr; end; procedure LongDequeInit(var deque: LongDeque); begin deque.first := nil; deque.last := nil end; {add in the beginning} procedure LongDequePushFront(var deque: LongDeque; n: longint); var newItem: LongItem2Ptr; begin new(newItem); newItem^.data := n; newItem^.next := deque.first; newItem^.prev := nil; if deque.first = nil then deque.last := newItem else deque.first^.prev := newItem; deque.first := newItem; end; {add in the ending} procedure LongDequePushBack(var deque: LongDeque; n: longint); var newItem: LongItem2Ptr; begin new(newItem); newItem^.data := n; newItem^.prev := deque.last; newItem^.next := nil; if deque.last = nil then deque.first := newItem else deque.last^.next := newItem; deque.last := newItem; end; function LongDequePopFront(var deque: LongDeque; var n: longint): boolean; var poppedItem: LongItem2Ptr; begin if deque.first = nil then begin LongDequePopFront := false; exit end; n := deque.first^.data; if deque.first^.next = nil then begin dispose(deque.first); deque.first := nil; deque.last := nil end else begin poppedItem := deque.first; deque.first^.next^.prev := nil; deque.first := deque.first^.next; dispose(poppedItem) end; LongDequePopFront := true; end; function LongDequePopBack(var deque: LongDeque; var n: longint) : boolean; var poppedItem: LongItem2Ptr; begin if deque.last = nil then begin LongDequePopBack := false; exit end; n := deque.last^.data; if deque.last^.prev = nil then begin dispose(deque.first); deque.first := nil; deque.last := nil; end else begin poppedItem := deque.last; deque.last^.prev^.next := nil; deque.last := deque.last^.prev; dispose(poppedItem); end; LongDequePopBack := true; end; var deque: LongDeque; data: array [1..5] of longint; i: integer; n: longint; begin LongDequeInit(deque); for i:= 1 to 5 do data[i] := i; writeln('Pushing to end'); for i := 1 to 5 do LongDequePushBack(deque, data[i]); writeln('Poping from start'); while LongDequePopFront(deque, n) do writeln(n); writeln('Pushing to start'); for i := 1 to 5 do LongDequePushFront(deque, data[i]); writeln('Poping from back'); while LongDequePopBack(deque, n) do writeln(n); end.
PROGRAM XPrint(INPUT, OUTPUT); CONST Min = 1; MaxStringLength = 5; Max = 25; TYPE IntSet = SET OF Min .. Max; VAR Ch: CHAR; FUNCTION ConvertsCharToSet(VAR Ch:CHAR):IntSet; BEGIN CASE Ch OF 'A': ConvertsCharToSet := [2, 3, 6, 8, 11, 12, 13, 16, 18, 21, 23]; 'B': ConvertsCharToSet := [1, 2, 6, 8, 11, 12, 12, 13, 16, 18, 21, 22, 23]; 'M': ConvertsCharToSet := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25] ELSE ConvertsCharToSet := [] END END; PROCEDURE PrintCharsSet(CharsSet: IntSet; VAR Ch: CHAR); VAR Counter, CounterX, CounterY: INTEGER; BEGIN {PrintCharsSet} Counter := Min; IF CharsSet <> [] THEN BEGIN FOR CounterY := Min TO MaxStringLength DO BEGIN FOR CounterX := Min TO MaxStringLength DO BEGIN IF Counter IN CharsSet THEN WRITE(Ch) ELSE WRITE(' '); INC(Counter) END; WRITELN END END ELSE WRITELN('Symbol ''', Ch, ''' is not supported') END; {PrintCharsSet} BEGIN {XPrint} IF NOT(EOLN(INPUT)) AND NOT(EOF(INPUT)) THEN BEGIN READ(Ch); PrintCharsSet(ConvertsCharToSet(Ch), Ch) END ELSE WRITELN END. {XPrint}
//****************************************************************** // Hint: You will be using TTuple in your solution. TTuple is // declared in this unit. It will be necessary for you to add // a uses statement in the interface section of uSaddlePoints.pas. // // For more guidance as you work on this exercise, see // GETTING_STARTED.md. //****************************************************************** unit uSaddlePointsTests; interface uses DUnitX.TestFramework; type [TestFixture] TSaddlePointTests = class(TObject) public [Test] // [Ignore('Comment the "[Ignore]" statement to run the test')] procedure Readme_example; [Test] [Ignore] procedure No_saddle_point; [Test] [Ignore] procedure Saddle_point; [Test] [Ignore] procedure Another_saddle_point; [Test] [Ignore] procedure Multiple_saddle_points; [Test] [Ignore] procedure Five_by_five_matrix; end; TTuple<T1, T2> = record private fValue1: T1; fValue2: T2; public constructor Create(Value1: T1; Value2: T2); property Value1 : T1 read fValue1; property Value2 : T2 read fValue2; end; implementation uses uSaddlePoints; constructor TTuple<T1, T2>.Create(Value1: T1; Value2: T2); begin fValue1 := Value1; fValue2 := Value2; end; procedure TSaddlePointTests.Readme_example; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 3, 3); values[0,0] := 9; values[0,1] := 8; values[0,2] := 7; values[1,0] := 5; values[1,1] := 3; values[1,2] := 2; values[2,0] := 6; values[2,1] := 6; values[2,2] := 7; SaddlePoints := newSaddlePoints(values); SetLength(expected, 1); expected[0] := TTuple<integer,integer>.Create(1,0); Assert.AreEqual(expected,SaddlePoints.Calculate); end; procedure TSaddlePointTests.No_saddle_point; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 2, 2); values[0,0] := 2; values[0,1] := 1; values[1,0] := 1; values[1,1] := 2; SaddlePoints := newSaddlePoints(values); SetLength(expected, 0); Assert.AreEqual(expected,SaddlePoints.Calculate); end; procedure TSaddlePointTests.Saddle_point; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 2, 2); values[0,0] := 1; values[0,1] := 2; values[1,0] := 3; values[1,1] := 4; SaddlePoints := newSaddlePoints(values); SetLength(expected, 1); expected[0] := TTuple<integer,integer>.Create(0,1); Assert.AreEqual(expected,SaddlePoints.Calculate); end; procedure TSaddlePointTests.Another_saddle_point; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 3, 5); values[0,0] := 18; values[0,1] := 3; values[0,2] := 39; values[0,3] := 19; values[0,4] := 91; values[1,0] := 38; values[1,1] := 10; values[1,2] := 8; values[1,3] := 77; values[1,4] := 320; values[2,0] := 3; values[2,1] := 4; values[2,2] := 8; values[2,3] := 6; values[2,4] := 7; SaddlePoints := newSaddlePoints(values); SetLength(expected, 1); expected[0] := TTuple<integer,integer>.Create(2,2); Assert.AreEqual(expected,SaddlePoints.Calculate); end; procedure TSaddlePointTests.Multiple_saddle_points; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 3, 3); values[0,0] := 4; values[0,1] := 5; values[0,2] := 4; values[1,0] := 3; values[1,1] := 5; values[1,2] := 5; values[2,0] := 1; values[2,1] := 5; values[2,2] := 4; SaddlePoints := newSaddlePoints(values); SetLength(expected, 3); expected[0] := TTuple<integer,integer>.Create(0,1); expected[1] := TTuple<integer,integer>.Create(1,1); expected[2] := TTuple<integer,integer>.Create(2,1); Assert.AreEqual(expected,SaddlePoints.Calculate); end; procedure TSaddlePointTests.Five_by_five_matrix; var SaddlePoints: ISaddlePoints; values: TArray<TArray<integer>>; expected: TArray<TTuple<integer,integer>>; begin SetLength(values, 5, 5); values[0,0] := 34; values[0,1] := 21; values[0,2] := 61; values[0,3] := 41; values[0,4] := 25; values[1,0] := 14; values[1,1] := 42; values[1,2] := 60; values[1,3] := 14; values[1,4] := 31; values[2,0] := 54; values[2,1] := 45; values[2,2] := 55; values[2,3] := 42; values[2,4] := 23; values[3,0] := 33; values[3,1] := 15; values[3,2] := 61; values[3,3] := 31; values[3,4] := 35; values[4,0] := 21; values[4,1] := 52; values[4,2] := 63; values[4,3] := 13; values[4,4] := 23; SaddlePoints := newSaddlePoints(values); SetLength(expected, 1); expected[0] := TTuple<integer,integer>.Create(2,2); Assert.AreEqual(expected, SaddlePoints.Calculate); end; initialization TDUnitX.RegisterTestFixture(TSaddlePointTests); end.
unit IWBSCustomControl; interface uses System.Classes, System.SysUtils, System.StrUtils, Data.db, IWControl, IWRenderContext, IWHTMLTag, IWXMLTag, IWDBCommon, IWDBStdCtrls, IWBSCommon; type TIWBSCustomControl = class(TIWCustomControl, IIWBSComponent) private FMainID: string; FOldCss: string; FOldDisabled: boolean; FOldReadOnly: boolean; FOldStyle: string; FOldVisible: boolean; FAsyncRefreshControl: boolean; FCustomAsyncEvents: TOwnedCollection; FCustomRestEvents: TOwnedCollection; FTabStop: boolean; FScript: TStringList; FScriptParams: TIWBSScriptParams; FStyle: TStringList; FOnRenderAsync: TNotifyEvent; function RenderHTMLTag(AContext: TIWCompContext): string; procedure SetScript(const AValue: TStringList); procedure SetScriptParams(const AValue: TIWBSScriptParams); function GetStyle: TStringList; procedure SetStyle(const AValue: TStringList); procedure OnScriptChange(ASender : TObject); procedure OnStyleChange(ASender : TObject); function GetCustomAsyncEvents: TOwnedCollection; procedure SetCustomAsyncEvents(const Value: TOwnedCollection); function GetCustomRestEvents: TOwnedCollection; procedure SetCustomRestEvents(const Value: TOwnedCollection); function GetScript: TStringList; function GetScriptParams: TIWBSScriptParams; protected {$hints off} function get_HasTabOrder: Boolean; override; function RenderAsync(AContext: TIWCompContext): TIWXMLTag; override; function RenderCSSClass(AComponentContext: TIWCompContext): string; override; function RenderHTML(AContext: TIWCompContext): TIWHTMLTag; override; procedure RenderScripts(AComponentContext: TIWCompContext); override; function RenderStyle(AContext: TIWCompContext): string; override; protected {$hints on} property ActiveCss: string read FOldCss; property ActiveStyle: string read FOldStyle; procedure InternalRenderAsync(const AHTMLName: string; AContext: TIWCompContext); virtual; procedure InternalRenderCss(var ACss: string); virtual; procedure InternalRenderHTML(const AHTMLName: string; AContext: TIWCompContext; var AHTMLTag: TIWHTMLTag); virtual; procedure InternalRenderScript(AContext: TIWCompContext; const AHTMLName: string; AScript: TStringList); virtual; procedure InternalRenderStyle(AStyle: TStringList); virtual; function InputSelector: string; virtual; function InputSuffix: string; virtual; function IsReadOnly: boolean; virtual; function IsDisabled: boolean; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Force a full refresh of the control during an Async call. // Usually there is no need to use this method, only if some property change during async calls is not reflected. procedure AsyncRefreshControl; // Remove a control from html flow. You should execute this when destroying a control durinc async calls before Freeing // if you are destroying a region is enought to execute this in that region, you don't need to execute it in each child control. procedure AsyncRemoveControl; function IsStoredCustomAsyncEvents: Boolean; function IsStoredCustomRestEvents: Boolean; published property CustomAsyncEvents: TOwnedCollection read GetCustomAsyncEvents write SetCustomAsyncEvents stored IsStoredCustomAsyncEvents; property CustomRestEvents: TOwnedCollection read GetCustomRestEvents write SetCustomRestEvents stored IsStoredCustomRestEvents; property Enabled; property ExtraTagParams; property FriendlyName; property Script: TStringList read GetScript write SetScript; property ScriptEvents; property ScriptParams: TIWBSScriptParams read GetScriptParams write SetScriptParams; property Style: TStringList read GetStyle write SetStyle; property TabStop: boolean read FTabStop write FTabStop default False; property TabOrder; property OnAsyncClick; property OnAsyncDoubleClick; property OnAsyncChange; property OnAsyncEnter; property OnAsyncExit; property OnAsyncKeyDown; property OnAsyncKeyUp; property OnAsyncKeyPress; property OnAsyncMouseDown; property OnAsyncMouseMove; property OnAsyncMouseOver; property OnAsyncMouseOut; property OnAsyncMouseUp; // this event is fired after HTMLTag is created property OnHTMLtag; // this event is fired after component is updated during async calls property OnRenderAsync: TNotifyEvent read FOnRenderAsync write FOnRenderAsync; end; TIWBSCustomDbControl = class(TIWBSCustomControl, IIWBSComponent) private FDataLink: TIWDataLink; FDataField: string; FDataSource: TDataSource; FMaxLength: Integer; procedure SetDataField(const AValue: string); procedure SetDataSource(const Value: TDataSource); procedure SetMaxLength(const AValue:integer); protected procedure CheckData(AContext: TIWCompContext); virtual; property MaxLength: Integer read FMaxLength write SetMaxLength; procedure Notification(AComponent: TComponent; AOperation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderAsync(AContext: TIWCompContext): TIWXMLTag; override; function RenderHTML(AContext: TIWCompContext): TIWHTMLTag; override; published property DataSource: TDataSource read FDataSource write SetDataSource; property DataField: string read FDataField write SetDataField; end; implementation uses IW.Common.RenderStream, IWBaseHTMLInterfaces, IWForm, IWBSScriptEvents, IWBSGlobal, IWBSUtils, IWBSCustomEvents; {$region 'TIWBSCustomControl'} constructor TIWBSCustomControl.Create(AOwner: TComponent); begin inherited; FAsyncRefreshControl := True; FCustomAsyncEvents := nil; FCustomRestEvents := nil; FMainID := ''; FTabStop := False; FScript := TStringList.Create; FScript.OnChange := OnScriptChange; FScriptParams := TIWBSScriptParams.Create; FScriptParams.OnChange := OnScriptChange; FStyle := TStringList.Create; FStyle.OnChange := OnStyleChange; FStyle.NameValueSeparator := ':'; end; destructor TIWBSCustomControl.Destroy; begin FreeAndNil(FCustomAsyncEvents); FreeAndNil(FCustomRestEvents); FreeAndNil(FScript); FreeAndNil(FScriptParams); FreeAndNil(FStyle); inherited; end; procedure TIWBSCustomControl.AsyncRefreshControl; begin FAsyncRefreshControl := True; Invalidate; end; procedure TIWBSCustomControl.AsyncRemoveControl; begin TIWBSCommon.AsyncRemoveControl(HTMLName); end; function TIWBSCustomControl.get_HasTabOrder: Boolean; begin Result := FTabStop and gIWBSEnableTabIndex; end; function TIWBSCustomControl.GetCustomAsyncEvents: TOwnedCollection; begin if FCustomAsyncEvents = nil then FCustomAsyncEvents := TOwnedCollection.Create(Self, TIWBSCustomAsyncEvent); Result := FCustomAsyncEvents; end; function TIWBSCustomControl.GetCustomRestEvents: TOwnedCollection; begin if FCustomRestEvents = nil then FCustomRestEvents := TOwnedCollection.Create(Self, TIWBSCustomRestEvent); Result := FCustomRestEvents; end; procedure TIWBSCustomControl.SetCustomAsyncEvents(const Value: TOwnedCollection); begin FCustomAsyncEvents.Assign(Value); end; procedure TIWBSCustomControl.SetCustomRestEvents(const Value: TOwnedCollection); begin FCustomRestEvents.Assign(Value); end; function TIWBSCustomControl.IsStoredCustomAsyncEvents: boolean; begin Result := (FCustomAsyncEvents <> nil) and (FCustomAsyncEvents.Count > 0); end; function TIWBSCustomControl.IsStoredCustomRestEvents: boolean; begin Result := (FCustomRestEvents <> nil) and (FCustomRestEvents.Count > 0); end; procedure TIWBSCustomControl.OnScriptChange( ASender : TObject ); begin AsyncRefreshControl; end; procedure TIWBSCustomControl.SetScript(const AValue: TStringList); begin FScript.Assign(AValue); end; procedure TIWBSCustomControl.OnStyleChange( ASender : TObject ); begin Invalidate; end; procedure TIWBSCustomControl.SetScriptParams(const AValue: TIWBSScriptParams); begin FScriptParams.Assign(AValue); end; function TIWBSCustomControl.GetScript: TStringList; begin Result := FScript; end; function TIWBSCustomControl.GetScriptParams: TIWBSScriptParams; begin Result := FScriptParams; end; function TIWBSCustomControl.GetStyle: TStringList; begin Result := FStyle; end; procedure TIWBSCustomControl.SetStyle(const AValue: TStringList); begin FStyle.Assign(AValue); end; procedure TIWBSCustomControl.InternalRenderAsync(const AHTMLName: string; AContext: TIWCompContext); begin // end; procedure TIWBSCustomControl.InternalRenderCss(var ACss: string); begin // end; procedure TIWBSCustomControl.InternalRenderHTML(const AHTMLName: string; AContext: TIWCompContext; var AHTMLTag: TIWHTMLTag); begin // end; procedure TIWBSCustomControl.InternalRenderScript(AContext: TIWCompContext; const AHTMLName: string; AScript: TStringList); begin // end; procedure TIWBSCustomControl.InternalRenderStyle(AStyle: TStringList); begin // end; function TIWBSCustomControl.IsReadOnly: boolean; begin Result := False; end; function TIWBSCustomControl.IsDisabled: boolean; begin Result := not Enabled; end; function TIWBSCustomControl.InputSelector: string; begin Result := ''; end; function TIWBSCustomControl.InputSuffix: string; begin Result := ''; end; function TIWBSCustomControl.RenderAsync(AContext: TIWCompContext): TIWXMLTag; var xHTMLName: string; xInputSelector: string; LParentContainer: IIWBaseHTMLComponent; LParentSl: string; LHtmlTag: string; begin Result := nil; xHTMLName := HTMLName; if FAsyncRefreshControl then begin // get base container if ParentContainer.InterfaceInstance is TIWForm then LParentSl := 'body' else begin LParentContainer := BaseHTMLComponentInterface(ParentContainer.InterfaceInstance); if LParentContainer <> nil then LParentSl := '#'+LParentContainer.HTMLName else Exit; end; LHtmlTag := RenderHtmlTag(AContext); AContext.WebApplication.CallBackResponse.AddJavaScriptToExecuteAsCDATA('AsyncRenderControl("'+xHTMLName+'", "'+LParentSl+'", "'+IWBSTextToJsParamText(LHtmlTag)+'");') end else begin if InputSelector <> '' then xInputSelector := FMainID+InputSelector else xInputSelector := xHTMLName+InputSuffix; SetAsyncClass(AContext, xHTMLName, RenderCSSClass(AContext), FOldCss); SetAsyncDisabled(AContext, xInputSelector, IsDisabled, FOldDisabled); SetAsyncReadOnly(AContext, xInputSelector, IsReadOnly, FOldReadOnly); SetAsyncStyle(AContext, xHTMLName, RenderStyle(AContext), FOldStyle); SetAsyncVisible(AContext, FMainID, Visible, FOldVisible); InternalRenderAsync(xHTMLName, AContext); end; if Assigned(FOnRenderAsync) then FOnRenderAsync(Self); if Assigned(gIWBSOnRenderAsync) then gIWBSOnRenderAsync(Self, xHTMLName); end; function TIWBSCustomControl.RenderCSSClass(AComponentContext: TIWCompContext): string; begin Result := Css; InternalRenderCss(Result); end; function TIWBSCustomControl.RenderHTML(AContext: TIWCompContext): TIWHTMLTag; begin Result := nil; FOldCss := RenderCSSClass(AContext); FOldDisabled := IsDisabled; FOldReadOnly := IsReadOnly; FOldStyle := RenderStyle(AContext); FOldVisible := Visible; InternalRenderHTML(HTMLName, AContext, Result); if Result = nil then raise Exception.Create('HTML tag not created'); IWBSRenderScript(Self, AContext, Result); FMainID := Result.Params.Values['id']; FAsyncRefreshControl := False; end; function TIWBSCustomControl.RenderHTMLTag(AContext: TIWCompContext): string; var LBuffer: TIWRenderStream; LTag: TIWHTMLTag; begin LTag := RenderHTML(AContext); try if not Visible then TIWBSCommon.SetNotVisible(LTag.Params); LBuffer := TIWRenderStream.Create(True, True); try RenderHTML(AContext).Render(LBuffer); Result := LBuffer.AsString; finally LBuffer.Free; end; finally LTag.Free; end; end; procedure TIWBSCustomControl.RenderScripts(AComponentContext: TIWCompContext); begin // end; function TIWBSCustomControl.RenderStyle(AContext: TIWCompContext): string; begin Result := TIWBSCommon.RenderStyle(Self); end; {$endregion} {$region 'TIWBSCustomDbControl'} constructor TIWBSCustomDbControl.Create(AOwner: TComponent); begin inherited; FDataLink := nil; FDataField := ''; end; destructor TIWBSCustomDbControl.Destroy; begin FreeAndNil(FDataLink); inherited; end; procedure TIWBSCustomDbControl.Notification(AComponent: TComponent; AOperation: TOperation); begin inherited Notification(AComponent, AOperation); if AOperation = opRemove then if FDatasource = AComponent then SetDataSource(nil); end; procedure TIWBSCustomDbControl.SetDataField(const AValue: string); var xFld: TField; begin if not SameText(AValue, FDataField) then begin FDataField := AValue; MaxLength := 0; if FDataField <> '' then begin xFld := GetDataSourceField(FDataSource, FDataField); if Assigned(xFld) and (xFld is TStringField) then MaxLength := TStringField(xFld).Size; end; Invalidate; end; end; procedure TIWBSCustomDbControl.SetDataSource(const Value: TDataSource); begin if Value <> FDataSource then begin FDataSource := Value; if Value = nil then begin FDataField := ''; FreeAndNil(FDataLink); end else begin if FDataLink = nil then FDataLink := TIWDataLink.Create(Self); FDataLink.DataSource := FDataSource; end; Invalidate; end; end; procedure TIWBSCustomDbControl.SetMaxLength(const AValue:integer); begin if FMaxLength <> AValue then begin FMaxLength := AValue; AsyncRefreshControl; end; end; procedure TIWBSCustomDbControl.CheckData(AContext: TIWCompContext); begin // end; function TIWBSCustomDbControl.RenderAsync(AContext: TIWCompContext): TIWXMLTag; begin CheckData(AContext); Result := inherited; end; function TIWBSCustomDbControl.RenderHTML(AContext: TIWCompContext): TIWHTMLTag; begin CheckData(AContext); Result := inherited; end; {$endregion} end.
unit PasIdHttpServerEx; interface uses IdHTTPServer, PasRequestProcessor, System.Generics.Collections, IdContext, IdCustomHTTPServer, System.SysUtils; type TIdHttpServerEx = class(TIdHTTPServer) protected FChainList: TObjectList<TRequestProcessor>; procedure commandDispatcher(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override; procedure DoCommandOther(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override; public constructor Create; destructor Destroy; // 注册新处理器,并返回该处理器的引用计数 function registerProcessor(processor: TRequestProcessor): Boolean; // 移除指定处理器,并返回该处理器的引用计数 function removeProcessor(processor: TRequestProcessor): Boolean; overload; function removeProcessor(processorClassName: string): Boolean; overload; procedure Free; end; implementation uses CnDebug; constructor TIdHttpServerEx.Create; begin inherited Create; //Self.processorLinkList := TObjectDictionary<TRequestProcessor, Integer>.Create(); Self.FChainList := TObjectList<TRequestProcessor>.Create(); end; destructor TIdHttpServerEx.Destroy; begin Self.FChainList.Free; inherited; end; {*------------------------------------------------------------------------------ 注册一个处理器 @param processor 处理器 @return 注册结果 -------------------------------------------------------------------------------} function TIdHttpServerEx.registerProcessor(processor: TRequestProcessor): Boolean; var pro: TRequestProcessor; refCount: Integer; step: Integer; begin CnDebugger.TraceEnter('registerProcessor', Self.ClassName); if processor = nil then begin CnDebugger.TraceMsg('Null Pointer'); raise Exception.Create('Null Pointer'); end; //for pro in Self.processorLinkList.Keys do for step := 0 to Self.FChainList.Count - 1 do begin pro := Self.FChainList.Items[step]; if pro.ClassName.Equals(processor.ClassName) then begin CnDebugger.TraceMsg('Processor exsit'); if pro <> processor then begin CnDebugger.TraceMsg('Free Input Processor'); processor.Free; end; //processor := pro; // 传入对象已存在,且不为之前的对象,则释放新对象,沿用旧的对象 processor := nil; Break; end; end; // if processor <> nil then begin Self.FChainList.Add(processor); CnDebugger.TraceMsg('Register:' + processor.ClassName); Result := True; end else begin CnDebugger.TraceMsg('Skip Register'); Result := False end; CnDebugger.TraceLeave('registerProcessor', Self.ClassName); end; function TIdHttpServerEx.removeProcessor(processor: TRequestProcessor): Boolean; begin if processor = nil then begin CnDebugger.TraceMsg('removeProcessor(TRequestProcessor) -> Null Pointer'); raise Exception.Create('Null Pointer'); end; Result := Self.removeProcessor(processor.ClassName); end; function TIdHttpServerEx.removeProcessor(processorClassName: string): Boolean; var pro: TRequestProcessor; regCount: Integer; step: Integer; begin CnDebugger.TraceEnter('removeProcessor', Self.ClassName); CnDebugger.TraceMsg('remove:' + processorClassName); //for pro in Self.processorLinkList.Keys do for step := 0 to Self.FChainList.Count - 1 do begin pro := Self.FChainList.Items[step]; if pro.ClassName.Equals(processorClassName) then begin CnDebugger.TraceMsg('Find Processor'); Break; end; pro := nil; end; if (pro <> nil) and pro.ClassName.Equals(processorClassName) then begin Self.FChainList.Remove(pro); FreeAndNil(pro); Result := True; end else begin Result := False; end; CnDebugger.TraceMsg('Result :' + BoolToStr(Result)); CnDebugger.TraceLeave('removeProcessor', Self.ClassName); end; procedure TIdHttpServerEx.commandDispatcher(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var eachProcessor: TRequestProcessor; uri, action: string; begin CnDebugger.TraceMsgWithTag('Enter:CommandDispatcher', Self.ClassName); uri := ARequestInfo.uri; action := ARequestInfo.Params.Values['action']; // 遍历 for eachProcessor in Self.FChainList do begin if eachProcessor.requested(uri, action) then begin CnDebugger.TraceMsg('Processor Invoked:' + eachProcessor.ClassName); if not eachProcessor.onCommand(AContext, ARequestInfo, AResponseInfo) then Break; end; end; CnDebugger.TraceMsgWithTag('Leave:CommandDispatcher', Self.ClassName); end; procedure TIdHttpServerEx.DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin Self.commandDispatcher(AContext, ARequestInfo, AResponseInfo); end; procedure TIdHttpServerEx.DoCommandOther(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin Self.commandDispatcher(AContext, ARequestInfo, AResponseInfo); end; procedure TIdHttpServerEx.Free; var processor: TRequestProcessor; begin // release processor for processor in Self.FChainList do begin Self.FChainList.Remove(processor); //processor.Free; end; // release list Self.FChainList.Free; inherited Free; end; end.
// IShellLink descriptions code came from https://github.com/jrsoftware/issrc/blob/master/Examples/CodeAutomation2.iss // procedure CreateShortcut(AtPath: string; ToPath: string; RunAsAdministrator: boolean); const CLSID_ShellLink = '{00021401-0000-0000-C000-000000000046}'; const // IShellLinkDataList::GetFlags()/SetFlags() SLDF_HAS_ID_LIST = $00000001; // Shell link saved with ID list SLDF_HAS_LINK_INFO = $00000002; // Shell link saved with LinkInfo SLDF_HAS_NAME = $00000004; SLDF_HAS_RELPATH = $00000008; SLDF_HAS_WORKINGDIR = $00000010; SLDF_HAS_ARGS = $00000020; SLDF_HAS_ICONLOCATION = $00000040; SLDF_UNICODE = $00000080; // the strings are unicode SLDF_FORCE_NO_LINKINFO = $00000100; // don't create a LINKINFO (make a dumb link) SLDF_HAS_EXP_SZ = $00000200; // the link contains expandable env strings SLDF_RUN_IN_SEPARATE = $00000400; // Run the 16-bit target exe in a separate VDM/WOW SLDF_HAS_LOGO3ID = $00000800; // this link is a special Logo3/MSICD link SLDF_HAS_DARWINID = $00001000; // this link is a special Darwin link SLDF_RUNAS_USER = $00002000; // Run this link as a different user SLDF_HAS_EXP_ICON_SZ = $00004000; // contains expandable env string for icon path SLDF_NO_PIDL_ALIAS = $00008000; // don't ever resolve to a logical location SLDF_FORCE_UNCNAME = $00010000; // make GetPath() prefer the UNC name to the local name SLDF_RUN_WITH_SHIMLAYER = $00020000; // Launch the target of this link w/ shim layer active SLDF_RESERVED = $80000000; // Reserved-- so we can use the low word as an index value in the future type IShellLinkW = interface(IUnknown) '{000214F9-0000-0000-C000-000000000046}' procedure Dummy; procedure Dummy2; procedure Dummy3; function GetDescription(pszName: String; cchMaxName: Integer): HResult; function SetDescription(pszName: String): HResult; function GetWorkingDirectory(pszDir: String; cchMaxPath: Integer): HResult; function SetWorkingDirectory(pszDir: String): HResult; function GetArguments(pszArgs: String; cchMaxPath: Integer): HResult; function SetArguments(pszArgs: String): HResult; function GetHotkey(var pwHotkey: Word): HResult; function SetHotkey(wHotkey: Word): HResult; function GetShowCmd(out piShowCmd: Integer): HResult; function SetShowCmd(iShowCmd: Integer): HResult; function GetIconLocation(pszIconPath: String; cchIconPath: Integer; out piIcon: Integer): HResult; function SetIconLocation(pszIconPath: String; iIcon: Integer): HResult; function SetRelativePath(pszPathRel: String; dwReserved: DWORD): HResult; function Resolve(Wnd: HWND; fFlags: DWORD): HResult; function SetPath(pszFile: String): HResult; end; IShellLinkDataList = interface(IUnknown) '{45E2B4AE-B1C3-11D0-B92F-00A0C90312E1}' function AddDataBlock(pDataBlock: cardinal): HResult; function CopyDataBlock(dwSig: DWORD; var ppDataBlock: cardinal): HResult; function RemoveDataBlock(dwSig: DWORD): HResult; function GetFlags(var pdwFlags: DWORD): HResult; function SetFlags(dwFlags: DWORD): HResult; end; IPersist = interface(IUnknown) '{0000010C-0000-0000-C000-000000000046}' function GetClassID(var classID: TGUID): HResult; end; IPersistFile = interface(IPersist) '{0000010B-0000-0000-C000-000000000046}' function IsDirty: HResult; function Load(pszFileName: String; dwMode: Longint): HResult; function Save(pszFileName: String; fRemember: BOOL): HResult; function SaveCompleted(pszFileName: String): HResult; function GetCurFile(out pszFileName: String): HResult; end; procedure CreateShortcut(AtPath, ToPath, IconPath, WorkingDirectoryPath: string; RunAsAdministrator: boolean); var Obj: IUnknown; SL: IShellLinkW; PF: IPersistFile; DL: IShellLinkDataList; Flags: DWORD; begin Obj := CreateComObject(StringToGuid(CLSID_ShellLink)); SL := IShellLinkW(Obj); OleCheck(SL.SetPath(ToPath)); OleCheck(SL.SetWorkingDirectory(WorkingDirectoryPath)); OleCheck(Sl.SetIconLocation(IconPath, 0)); if RunAsAdministrator then begin DL := IShellLinkDataList(Obj); OleCheck(DL.GetFlags(Flags)); OleCheck(Dl.SetFlags(Flags or SLDF_RUNAS_USER)); end; PF := IPersistFile(Obj); OleCheck(PF.Save(AtPath, True)); end;
unit aOPCTCPSource_V31; interface uses Classes, SysUtils, aOPCSource, aOPCTCPSource_V30, uDCObjects, uUserMessage, aCustomOPCSource, aCustomOPCTCPSource; type TaOPCTCPSource_V31 = class(TaOPCTCPSource_V30) public constructor Create(aOwner: TComponent); override; function GetCards: string; procedure AddCard(aCardNo: string); procedure DelCard(aCardNo: string); procedure AddSum(aCardNo: string; aSum: Double); end; implementation { TaOPCTCPSource_V31 } procedure TaOPCTCPSource_V31.AddCard(aCardNo: string); begin LockAndDoCommandFmt('AddCard %s', [aCardNo]); end; procedure TaOPCTCPSource_V31.AddSum(aCardNo: string; aSum: Double); begin LockAndDoCommandFmt('AddSum %s;%s', [aCardNo, FloatToStr(aSum, OpcFS)]); end; constructor TaOPCTCPSource_V31.Create(aOwner: TComponent); begin inherited Create(aOwner); ProtocolVersion := 31; end; procedure TaOPCTCPSource_V31.DelCard(aCardNo: string); begin LockAndDoCommandFmt('DelCard %s', [aCardNo]); end; function TaOPCTCPSource_V31.GetCards: string; begin Result := LockAndGetStringsCommand('GetCards'); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; ComboBox1: TComboBox; ListBox1: TListBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure AppMessage(var Msg: TMsg; var Handled: Boolean); public { Public declarations } end; const SC_SIZE = $F012; var Form1: TForm1; implementation uses WinProcs, Registry; {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var iTemp: Integer; r: TRegIniFile; begin (* Open the key in the registry where we store all the positions *) r := TRegIniFile.Create('Resize Test'); (* Loop through all the components on a form *) for iTemp := 0 to ComponentCount - 1 do (* Get the position of all controls *) if Components[iTemp] is TControl then with Components[iTemp] as TControl do begin left := r.readinteger(Name, 'Left', left); top := r.readinteger(Name, 'Top', top); (* Make there cursors crosses *) cursor := crCross; end; (* Release the registry object *) r.free; (* Use our own message handler for all message sent to the application *) Application.OnMessage := AppMessage; end; procedure TForm1.FormDestroy(Sender: TObject); var iTemp: Integer; r: TRegIniFile; begin (* As in the form create loop through all the components But this time write the left and top properties to the registry *) r := TRegIniFile.Create('Resize Test'); for iTemp := 0 to ComponentCount - 1 do if Components[iTemp] is TControl then with Components[iTemp] as TControl do begin r.writeinteger(Name, 'Left', left); r.writeinteger(Name, 'Top', top); end; r.free; end; procedure TForm1.AppMessage(var Msg: TMsg; var Handled: Boolean); begin (* Only do anything if the left mouse button is pressed *) if Msg.message = wm_LBUTTONDOWN then begin (* Release the mouse capture *) WinProcs.ReleaseCapture; (* Send a message to the control under the mouse to go into move mode *) postmessage(Msg.hwnd, WM_SysCommand, SC_SIZE, 0); (* Say we have handled this message *) Handled := true; end; end; end. { Fone : http://www.delphi-central.com/movecontrun.aspx }
PROGRAM CountReverse(INPUT, OUTPUT); USES Count3; PROCEDURE MoveWindow(VAR F1: TEXT; VAR W1, W2, W3: CHAR); BEGIN {MoveWindow} W1 := W2; W2 := W3; READ(F1, W3) END; {MoveWindow} PROCEDURE CountingReverses(VAR F1: TEXT); VAR W1, W2, W3: CHAR; BEGIN {CountingReverses} IF NOT(EOLN(F1)) THEN BEGIN READ(W2); IF NOT(EOLN(F1)) THEN READ(W3); Start; WHILE NOT(EOLN(F1)) DO BEGIN MoveWindow(F1, W1, W2, W3); IF ((W2 < W1) AND (W2 < W3)) OR ((W2 > W1) AND (W2 > W3)) THEN Bump END; END; END; {CountingReverses} PROCEDURE PrintNumberOfRevers; VAR X1, X10, X100, Overflow: CHAR; BEGIN {PrintNumberOfRevers} GetValue(X1, X10, X100, Overflow); IF Overflow <> Count3.No THEN BEGIN WRITELN('Количество реверсов: ', X100, X10, X1) END ELSE WRITELN('Слишком большое количество реверсов') END; {PrintNumberOfRevers} BEGIN {CountReverse} CountingReverses(INPUT); PrintNumberOfRevers END.{CountReverse}
unit CustomizeTableColumns; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Grids, Vcl.Buttons, ActnList, ValEdit, Vcl.Themes, DB, MemDS, DBAccess, Ora, Vcl.ExtCtrls, BCDialogs.Dlg, System.Actions, Vcl.ComCtrls, Vcl.ToolWin, BCControls.ToolBar, Vcl.ImgList, BCControls.ImageList; type TCustomizeTableColumnsDialog = class(TDialog) ActionList: TActionList; BottomPanel: TPanel; CancelButton: TButton; ClientPanel: TPanel; ColumnsQuery: TOraQuery; MoveDownAction: TAction; MoveUpAction: TAction; OKAction: TAction; OKButton: TButton; Separator1Panel: TPanel; Separator2Panel: TPanel; ValueListEditor: TValueListEditor; ImageList: TBCImageList; ToolBar: TBCToolBar; MoveUpToolButton: TToolButton; MoveDownToolButton: TToolButton; procedure FormDestroy(Sender: TObject); procedure MoveDownActionExecute(Sender: TObject); procedure MoveUpActionExecute(Sender: TObject); procedure OKActionExecute(Sender: TObject); procedure ValueListEditorClick(Sender: TObject); procedure ValueListEditorDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Private declarations } FInMouseClick: Boolean; FSchemaParam: string; FTableName: string; procedure FillValueList; procedure WriteIniFile; public { Public declarations } function Open(OraSession: TOraSession; SchemaParam: string; TableName: string): Boolean; end; function GetTableColumns(SchemaParam: string; TableName: string): string; function CustomizeTableColumnsDialog: TCustomizeTableColumnsDialog; implementation {$R *.dfm} uses Winapi.UxTheme, System.Math, BigIni, BCCommon.StyleUtils, BCCommon.FileUtils, BCCommon.StringUtils; const TXT_MARG: TPoint = (x: 4; y: 2); BTN_WIDTH = 12; CELL_PADDING = 4; var FCustomizeTableColumnsrDialog: TCustomizeTableColumnsDialog; function CustomizeTableColumnsDialog: TCustomizeTableColumnsDialog; begin if not Assigned(FCustomizeTableColumnsrDialog) then Application.CreateForm(TCustomizeTableColumnsDialog, FCustomizeTableColumnsrDialog); Result := FCustomizeTableColumnsrDialog; SetStyledFormSize(Result); end; procedure TCustomizeTableColumnsDialog.FormDestroy(Sender: TObject); begin FCustomizeTableColumnsrDialog := nil; end; procedure TCustomizeTableColumnsDialog.MoveDownActionExecute(Sender: TObject); begin if ValueListEditor.Row < ValueListEditor.RowCount - 1 then begin ValueListEditor.Strings.Exchange(ValueListEditor.Row - 1, ValueListEditor.Row); ValueListEditor.Row := ValueListEditor.Row + 1; end; end; procedure TCustomizeTableColumnsDialog.MoveUpActionExecute(Sender: TObject); begin if ValueListEditor.Row - 1 > 0 then begin ValueListEditor.Strings.Exchange(ValueListEditor.Row - 1, ValueListEditor.Row - 2); ValueListEditor.Row := ValueListEditor.Row - 1; end; end; procedure TCustomizeTableColumnsDialog.ValueListEditorClick(Sender: TObject); var where: TPoint; ACol, ARow: integer; Rect, btnRect: TRect; s: TSize; begin //Again, check to avoid recursion: if not FInMouseClick then begin FInMouseClick := true; try //Get clicked coordinates and cell: where := Mouse.CursorPos; where := ValueListEditor.ScreenToClient(where); ValueListEditor.MouseToCell(where.x, where.y, ACol, ARow); if ARow > 0 then begin //Get buttonrect for clicked cell: //btnRect := GetBtnRect(ACol, ARow, false); s.cx := GetSystemMetrics(SM_CXMENUCHECK); s.cy := GetSystemMetrics(SM_CYMENUCHECK); Rect := ValueListEditor.CellRect(ACol, ARow); btnRect.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; btnRect.Bottom := btnRect.Top + s.cy; btnRect.Left := Rect.Left + CELL_PADDING; btnRect.Right := btnRect.Left + s.cx; InflateRect(btnrect, 2, 2); //Allow 2px 'error-range'... //Check if clicked inside buttonrect: if PtInRect(btnRect, where) then if ACol = 1 then begin if ValueListEditor.Cells[ACol, ARow] = 'True' then ValueListEditor.Cells[ACol, ARow] := 'False' else ValueListEditor.Cells[ACol, ARow] := 'True' end; end; finally FInMouseClick := false; end; end; end; procedure TCustomizeTableColumnsDialog.ValueListEditorDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var h: HTHEME; s: TSize; r, header, LRect: TRect; LStyles: TCustomStyleServices; LColor: TColor; LDetails: TThemedElementDetails; function Checked(ARow: Integer): Boolean; begin if ValueListEditor.Cells[1, ARow] = 'True' then Result := True else Result := False end; begin LStyles := StyleServices; if ARow = 0 then begin if not LStyles.GetElementColor(LStyles.GetElementDetails(thHeaderItemNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); header := Rect; if Assigned(TStyleManager.ActiveStyle) then if TStyleManager.ActiveStyle.Name <> 'Windows' then Dec(header.Left, 1); Inc(header.Right, 1); Inc(header.Bottom, 1); ValueListEditor.Canvas.Brush.Color := LStyles.GetSystemColor(ValueListEditor.FixedColor); ValueListEditor.Canvas.Font.Color := LColor; ValueListEditor.Canvas.FillRect(header); ValueListEditor.Canvas.Brush.Style := bsClear; if UseThemes then begin LStyles.DrawElement(ValueListEditor.Canvas.Handle, StyleServices.GetElementDetails(thHeaderItemNormal), header); LDetails := LStyles.GetElementDetails(thHeaderItemNormal); Inc(header.Left, 4); Dec(header.Right, 1); Dec(header.Bottom, 1); if ACol = 0 then LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], header, [tfSingleLine, tfVerticalCenter]) else LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], header, [tfCenter, tfSingleLine, tfVerticalCenter]); end; end; if (ARow > 0) then begin if not LStyles.GetElementColor(LStyles.GetElementDetails(tgCellNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); //get and set the backgroun color ValueListEditor.Canvas.Brush.Color := LStyles.GetStyleColor(scListView); ValueListEditor.Canvas.Font.Color := LColor; if UseThemes and (gdSelected in State) then begin ValueListEditor.Canvas.Brush.Color := LStyles.GetSystemColor(clHighlight); ValueListEditor.Canvas.Font.Color := LStyles.GetSystemColor(clHighlightText); end else if not UseThemes and (gdSelected in State) then begin ValueListEditor.Canvas.Brush.Color := clHighlight; ValueListEditor.Canvas.Font.Color := clHighlightText; end; ValueListEditor.Canvas.FillRect(Rect); ValueListEditor.Canvas.Brush.Style := bsClear; // draw selected if UseThemes and (gdSelected in State) then begin LRect := Rect; Dec(LRect.Left, 1); Inc(LRect.Right, 2); LDetails := LStyles.GetElementDetails(tgCellSelected); LStyles.DrawElement(ValueListEditor.Canvas.Handle, LDetails, LRect); end; s.cx := GetSystemMetrics(SM_CXMENUCHECK); s.cy := GetSystemMetrics(SM_CYMENUCHECK); if (ACol = 1) and UseThemes then begin h := OpenThemeData(ValueListEditor.Handle, 'BUTTON'); if h <> 0 then try GetThemePartSize(h, ValueListEditor.Canvas.Handle, BP_CHECKBOX, CBS_CHECKEDNORMAL, nil, TS_DRAW, s); r.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; r.Bottom := r.Top + s.cy; r.Left := Rect.Left + CELL_PADDING; r.Right := r.Left + s.cx; if Checked(ARow) then LDetails := LStyles.GetElementDetails(tbCheckBoxcheckedNormal) else LDetails := LStyles.GetElementDetails(tbCheckBoxUncheckedNormal); LStyles.DrawElement(ValueListEditor.Canvas.Handle, LDetails, r); finally CloseThemeData(h); end; end else if (ACol = 1) then begin r.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; r.Bottom := r.Top + s.cy; r.Left := Rect.Left + CELL_PADDING; r.Right := r.Left + s.cx; DrawFrameControl(ValueListEditor.Canvas.Handle, r, DFC_BUTTON, IfThen(Checked(ARow), DFCS_CHECKED, DFCS_BUTTONCHECK)); end; LRect := Rect; Inc(LRect.Left, 4); if (gdSelected in State) then LDetails := LStyles.GetElementDetails(tgCellSelected) else LDetails := LStyles.GetElementDetails(tgCellNormal); if not LStyles.GetElementColor(LDetails, ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); ValueListEditor.Canvas.Font.Color := LColor; if (ACol = 1) then begin Inc(LRect.Left, 20); LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], LRect, [tfSingleLine, tfVerticalCenter, tfEndEllipsis]) end else LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], LRect, [tfSingleLine, tfVerticalCenter]); end; end; function GetTableColumns(SchemaParam: string; TableName: string): string; var i: Integer; TreeObjects: TStrings; Value: string; ColumnAdded: Boolean; begin { read from ini } TreeObjects := TStringList.Create; try with TBigIniFile.Create(GetINIFilename) do try ReadSectionValues('CustomizeTableColumns_' + EncryptString(SchemaParam + '.' + TableName), TreeObjects); finally Free; end; Result := ''; ColumnAdded := False; for i := 0 to TreeObjects.Count - 1 do begin Value := DecryptString(System.Copy(TreeObjects.Strings[i], Pos('=', TreeObjects.Strings[i]) + 1, Length(TreeObjects.Strings[i]))); if Value = 'True' then begin if ColumnAdded then Result := Result + ', ' ; Result := Result + DecryptString(System.Copy(TreeObjects.Strings[i], 0, Pos('=', TreeObjects.Strings[i]) - 1)); ColumnAdded := True; end; end; finally TreeObjects.Free; end; end; procedure TCustomizeTableColumnsDialog.FillValueList; var i: Integer; TreeObjects: TStrings; begin { read from ini } TreeObjects := TStringList.Create; try with TBigIniFile.Create(GetINIFilename) do try ReadSectionValues('CustomizeTableColumns_' + EncryptString(FSchemaParam + '.' + FTableName), TreeObjects); finally Free; end; if TreeObjects.Count = 0 then with ColumnsQuery do try ParamByName('P_TABLE_NAME').AsString := FTableName; ParamByName('P_OWNER').AsString := FSchemaParam; Open; while not Eof do begin TreeObjects.Add(EncryptString(FieldByName('COLUMN_NAME').AsString) + '=' + EncryptString('True')); Next; end; finally Close; end; ValueListEditor.Strings.Clear; for i := 0 to TreeObjects.Count - 1 do ValueListEditor.Strings.Add(//Common.DecryptString(TreeObjects.Strings[i])); DecryptString(System.Copy(TreeObjects.Strings[i], 0, Pos('=', TreeObjects.Strings[i]) - 1)) + '=' + DecryptString(System.Copy(TreeObjects.Strings[i], Pos('=', TreeObjects.Strings[i]) + 1, Length(TreeObjects.Strings[i])))); finally TreeObjects.Free; end; end; procedure TCustomizeTableColumnsDialog.WriteIniFile; var i: Integer; Section: string; // WriteIni: Boolean; begin with TBigIniFile.Create(GetINIFilename) do try Section := 'CustomizeTableColumns_' + EncryptString(FSchemaParam + '.' + FTableName); EraseSection(Section); { check if there's need to write ini } {WriteIni := False; for i := 1 to ValueListEditor.RowCount - 1 do if ValueListEditor.Values[ValueListEditor.Keys[i]] = 'False' then WriteIni := True; if WriteIni then } for i := 1 to ValueListEditor.RowCount - 1 do WriteString(Section, EncryptString(ValueListEditor.Keys[i]), EncryptString(ValueListEditor.Values[ValueListEditor.Keys[i]])); finally Free; end; end; procedure TCustomizeTableColumnsDialog.OKActionExecute(Sender: TObject); begin WriteIniFile; ModalResult := mrOk; end; function TCustomizeTableColumnsDialog.Open(OraSession: TOraSession; SchemaParam: string; TableName: string): Boolean; begin FInMouseClick := False; FSchemaParam := SchemaParam; FTableName := TableName; ColumnsQuery.Session := OraSession; FillValueList; Result := ShowModal = mrOk; end; end.
unit Panelclk; { This is just a simple Panel Clock. It is descended from type TTimerPanel, and on each timer tick, if enabled, updates it's caption to reflect the current time, displayed according to the value of the DisplayMask. Caption is not published (it is protected in the base class) so that it can't be fiddled with by external means. Credit where credit is due: The idea for this component came from a training course on Delphi given to me by an outside company that I can't recall the name of (I'll gladly credit them if I can remember their names). The basic functionality existed in an object that we created during the class. I recoded it however, to descend from my TTimerPanel base class instead, and recoded and supplemented the functionality. The idea and original implementation is theirs. The actual implementation and specific code is mine. Anyone that wants to challenge the legal rights of this is more than welcome to try and get 50% of the royalties I receive from this object. Since it's being released by me free of charge, be aware that 50% of nothing means a lot of legal bills. :) Released into the public domain, November 1995. Author: Gary D. Foster Date: 11/9/95 Change Log: * 11/10/95 -- Gary D. Foster Moved DisplayTime and SetDisplayMask from private to protected status and changed them to virtual. } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Timerpnl; type TPanelClock = class(TTimerPanel) private FDisplayMask: String; protected procedure DisplayTime(Sender: TObject); virtual; procedure SetDisplayMask(Value: String); virtual; public constructor Create(AOwner: TComponent); override; published property DisplayMask: String read FDisplayMask write SetDisplayMask; end; implementation procedure TPanelClock.DisplayTime(Sender: TObject); begin if Enabled then Caption := FormatDateTime(FDisplayMask, Now); end; procedure TPanelClock.SetDisplayMask(Value: String); begin FDisplayMask := Value; end; constructor TPanelClock.Create(AOwner: TComponent); begin inherited Create(AOwner); SetDisplayMask('hh:mm:ss'); ClockDriver.OnTimer := DisplayTime; end; end.
unit uTaskManager; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Generics.Collections, uJsonClass, uGlobal, ManSoy.Encode, ManSoy.Global, uDToolServer, uCommand ; type TTaskManager = class private FCS: TRTLCriticalSection; FItems: TObjectDictionary<string,TOrderItem>; function GetCount: Integer; function GetItem(AKey: string): TOrderItem; procedure SetItem(AKey: string; const Value: TOrderItem); public constructor Create; destructor Destroy; override; procedure Add(AOrderItem: TOrderItem); procedure Del(AKey: string); procedure DelByOrderNo(AOrderNo: string); procedure DelQueueByOrderNo(AOrderNo: string); procedure DelByKey(AKey: string); function GetMasterOrderItem(AOrderItem: TOrderItem): TOrderItem; overload; function GetMasterOrderItem(AOrderNo: string; AMasterRoleName: string): TOrderItem; overload; /// <remarks> /// 获取同一个订单低下的任务还有多少个, IsBusy: 0: 不判断IsBusy 1:IsBusy=True 2:IsBusy=False /// </remarks> function GetSameTaskCount(AOrderNo: string; AIsBusy: Integer = 0): Integer; /// <remarks> /// 设置子号信息 /// </remarks> function SetRoleStep(AChildInfo: string; AConnID: DWORD): Boolean; function SetMasterRecRoleName(ACmd: string; AConnID: DWORD): Boolean; function ClearRecvRoleName(ACmd: string; AConnID: DWORD): Boolean; function GetCanSendTask(ATaskType: TTaskType = tt发货): TOrderItem; function ContainsKey(AKey: string): Boolean; function EndChildTask(AOrderNo: string): Boolean; property Count: Integer read GetCount; property Items[AKey: string]: TOrderItem read GetItem write SetItem; end; TConnItem = class private FConnID: Integer; FGroupName: string; FOrderItem: TOrderItem; FState: TSendMachineState; FRoleStep: TRoleStep; FInterval: DWORD; //FLogMsg: string; FSuspend: Boolean; FIsAbnormal: Boolean; FLogMsgs: TStrings; FIsMain: Boolean; public constructor Create; destructor Destroy; override; property ConnID: Integer read FConnID write FConnID; /// <remarks> /// 发货机编号 /// </remarks> property GroupName: string read FGroupName write FGroupName; /// <remarks> /// 当前任务实体 /// </remarks> property OrderItem: TOrderItem read FOrderItem write FOrderItem; /// <remarks> /// 发货机状态 /// </remarks> property State: TSendMachineState read FState write FState; /// <remarks> /// 角色执行到哪一步了 /// </remarks> property RoleStep: TRoleStep read FRoleStep write FRoleStep; /// <remarks> /// 当前任务耗时 /// </remarks> property Interval: DWORD read FInterval write FInterval; //property LogMsg: string read FLogMsg write FLogMsg; /// <remarks> /// 任务暂停标记 /// </remarks> property Suspend: Boolean read FSuspend write FSuspend; /// <remarks> /// 发货机异常中断 /// </remarks> property IsAbnormal: Boolean read FIsAbnormal write FIsAbnormal default False; /// <remarks> /// 发货机日志记录 /// </remarks> property LogMsgs: TStrings read FLogMsgs write FLogMsgs; /// <remarks> /// 如果是分仓任务的话, 标记是不是主号 /// </remarks> //property IsMain: Boolean read FIsMain write FIsMain; end; TConnManager = class private FCS: TRTLCriticalSection; FItems: TObjectDictionary<string,TConnItem>; function GetCount: Integer; function GetItem(AKey: string): TConnItem; procedure SetItem(AKey: string; const Value: TConnItem); public constructor Create; destructor Destroy; override; procedure Add(AConnItem: TConnItem); procedure Del(AKey: string); function GetFreeMachine: TConnItem; function GetFreeCount: Integer; function GetGroupName(AConnID: DWORD): string; function GetMasterConnItem(AConnItem: TConnItem): TConnItem; overload; function GetMasterConnItem(AOrderNo: string): TConnItem; overload; function GetTargerConnItem(ATargetRoleName:string; AOrderNo:string): TConnItem; function GetConnOrderInfo(AGroupName: string): string; function GetConnItem(AOrderNo: string; ARoleName: string): TConnItem; function SuspendTask(AGroupName: string): Boolean; function ReStartTask(AGroupName: string): Boolean; function StopTask(AGroupName: string): Boolean; function SuspendAllTask: Boolean; function ReStartAllTask: Boolean; function StopAllTask(AOrderNo: string): Boolean; function ReSetRoleStep(AConnID: DWORD; AGroupName: string; ARoleName: string; ATargetRoleName: string; ARoleStep: TRoleStep): Boolean; function RetRoleStep(AConnID: DWORD; AGroupName: string): Boolean; function RetTargetRoleStep(AConnID: DWORD; AGroupName: string; ARoleName: string; ATargetRoleName: string): Boolean; function RetRecvRoleName(AConnId: DWORD; AGroupName: string; AMasterRoleName: string): Boolean; function ClearLog(AGroupName: string): Boolean; function ClearAllLog: Boolean; function LogoutAll: Boolean; function ReBootAll: Boolean; function ShutdownAll: Boolean; property Count: Integer read GetCount; property Items[AKey: string]: TConnItem read GetItem write SetItem; end; var TaskManager: TTaskManager; ConnManager: TConnManager; function DispatchOrder(ATaskType: TTaskType): Boolean; function AddConnItem(AConnID: DWORD; AGroupName: string): Boolean; function DelConnItem(AConnID: DWORD; AGroupName: string): Boolean; /// <remarks> /// 发货机发货完成(失败)时调用 /// </remarks> function EndTask(AGroupName: string; AKey: string): Boolean; function SuspendTask(AGroupName: string): Boolean; //function SetTaskLog(AJson: string): Boolean; function SetTaskState(AJson: string): Boolean; function AddOrder(AJson: string): Boolean; implementation function DispatchOrder(ATaskType: TTaskType): Boolean; var iFreeCount: Integer; vConnItem: TConnItem; vOrderItem: TOrderItem; vRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(CS_OP_Task); try if GSharedInfo.TaskType = ttNormal then Exit; try vOrderItem := TaskManager.GetCanSendTask(ATaskType); if vOrderItem = nil then Exit; vConnItem := ConnManager.GetFreeMachine; if vConnItem = nil then Exit; vConnItem.OrderItem := vOrderItem; vConnItem.State := sms繁忙; vConnItem.RoleStep := rsNormal; vConnItem.Interval := GetTickCount; vConnItem.LogMsgs.Add('开始处理任务'); vOrderItem.isBusy := True; for vRoleItem in vOrderItem.roles do vRoleItem.taskState := Integer(tsStart); SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(vOrderItem.key)); SendMessage(GSharedInfo.MainFormHandle, WM_UPDATE_CONN_UI, 0, LParam(vConnItem.GroupName)); except on E: Exception do AddLogMsg('分配订单异常: %s', [E.Message]); end; finally LeaveCriticalSection(CS_OP_Task); end; end; function AddConnItem(AConnID: DWORD; AGroupName: string): Boolean; var vConnItem: TConnItem; vOrderItem: TOrderItem; begin Result := False; EnterCriticalSection(CS_OP_Task); try try if AGroupName = '' then Exit; if ConnManager.Items[AGroupName] <> nil then begin { TODO : 通知发货机,已经有一个同名的存在了 } uCommand.Cmd_RetConn(ConsoleSvr.Server, AConnID, False); Exit; end; vConnItem := TConnItem.Create; vConnItem.ConnID := AConnID; vConnItem.GroupName := AGroupName; ConnManager.Add(vConnItem); SendMessage(GSharedInfo.MainFormHandle, WM_ADD_SEND_MACHINE, 0, LParam(vConnItem)); uCommand.Cmd_RetConn(ConsoleSvr.Server, AConnID, True); except on E: Exception do AddLogMsg('添加发货机异常: %s', [E.Message]); end; finally LeaveCriticalSection(CS_OP_Task); end; end; function DelConnItem(AConnID: DWORD; AGroupName: string): Boolean; var vConnItem: TConnItem; vOrderItem: TOrderItem; begin Result := False; EnterCriticalSection(CS_OP_Task); try try if AGroupName = '' then Exit; if ConnManager.Items[AGroupName] = nil then begin Exit; end; SendMessage(GSharedInfo.MainFormHandle, WM_DEL_SEND_MACHINE, 0, LParam(vConnItem.GroupName)); ConnManager.Del(AGroupName); except on E: Exception do AddLogMsg('删除发货机异常: %s', [E.Message]); end; finally LeaveCriticalSection(CS_OP_Task); end; end; function EndTask(AGroupName: string; AKey: string): Boolean; var vConnItem, vMasterConnItem: TConnItem; vOrderItem, vMasterOrderItem: TOrderItem; iCount: Integer; vRoleItem, vMasterRoleItem: TRoleItem; begin EnterCriticalSection(CS_OP_Task); try try if AGroupName = '' then Exit; vConnItem := ConnManager.Items[AGroupName]; if vConnItem = nil then Exit; vOrderItem := vConnItem.OrderItem; if vOrderItem = nil then Exit; if vOrderItem.key = AKey then begin if vOrderItem.taskType = Integer(tt分仓) then begin { TODO : 在这里处理分仓,任务结束逻辑 } //--子号的话先查看一下有没有相同的子号(接收来自同一个库存角色)存在, 如果没有,就将主号的状态设置为finished for vRoleItem in vOrderItem.roles do begin if vRoleItem.isMain then begin TaskManager.EndChildTask(vOrderItem.orderNo); end else begin vMasterConnItem := ConnManager.GetMasterConnItem(vOrderItem.orderNo); if vMasterConnItem = nil then Continue; vMasterOrderItem := vMasterConnItem.OrderItem; if vMasterOrderItem = nil then Continue; iCount := TaskManager.GetSameTaskCount(vOrderItem.orderNo); if iCount <= 1 then begin vMasterConnItem.RoleStep := rsFinished; end; for vMasterRoleItem in vMasterOrderItem.roles do begin if vRoleItem.receiptRole <> vMasterRoleItem.role then Continue; AddLogMsg('子号角色:%s', [vMasterRoleItem.receiptRole], True); vMasterRoleItem.receiptRole := ''; SendMessage(GSharedInfo.MainFormHandle, WM_UPDATE_CONN_UI, 0, LPARAM(vMasterConnItem.GroupName)); AddLogMsg('子号角色:%s', [vMasterRoleItem.receiptRole], True); end; end; end; end; TaskManager.Del(vOrderItem.key); vConnItem.OrderItem := nil; vConnItem.State := sms空闲; vConnItem.RoleStep := rsNormal; vConnItem.Suspend := False; //vConnItem.LogMsg := ''; SendMessage(GSharedInfo.MainFormHandle, WM_UPDATE_CONN_UI, 0, LPARAM(AGroupName)); end; ConsoleSvr.RetCmdOk(vConnItem.ConnID); except end; finally LeaveCriticalSection(CS_OP_Task); end; end; function SuspendTask(AGroupName: string): Boolean; var vConnItem: TConnItem; vOrderItem: TOrderItem; begin EnterCriticalSection(CS_OP_Task); try try if AGroupName = '' then Exit; vConnItem := ConnManager.Items[AGroupName]; if vConnItem = nil then Exit; if vConnItem.OrderItem = nil then Exit; if vConnItem.State <> sms空闲 then Exit; vConnItem.Suspend := True; SendMessage(GSharedInfo.MainFormHandle, WM_UPDATE_CONN_UI, 0, LPARAM(AGroupName)); except end; finally LeaveCriticalSection(CS_OP_Task) end; end; function SetTaskState(AJson: string): Boolean; var vStateItem: TStatusItem; vConnItem: TConnItem; vOrderItem: TOrderItem; vRoleItem: TRoleItem; begin Result := False; if AJson = '' then Exit; EnterCriticalSection(CS_OP_Task); try try AJson := ManSoy.Encode.Base64ToStr(AJson); //AddLogMsg(AJson, [], True); if not TSerizalizes.AsType<TStatusItem>(AJson, vStateItem) then Exit; if vStateItem = nil then Exit; try if vStateItem.groupName = '' then Exit; vConnItem := ConnManager.Items[vStateItem.groupName]; if vConnItem = nil then Exit; {$IFNDEF _MS_DEBUG} vOrderItem := vConnItem.OrderItem; if vOrderItem = nil then Exit; {$ENDIF} if vStateItem.reason <> '' then vConnItem.LogMsgs.Add(ManSoy.Encode.Base64ToStr(vStateItem.reason)); {$IFNDEF _MS_DEBUG} for vRoleItem in vOrderItem.roles do begin if vRoleItem.rowId = vStateItem.rowId then begin if vStateItem.state <> 100 then vRoleItem.taskState := vStateItem.state; if (vStateItem.state = Integer(tsSuspend)) and (not vConnItem.Suspend) then begin vConnItem.Suspend := True; end; if vStateItem.reason <> '' then vRoleItem.logMsg := ManSoy.Encode.Base64ToStr(vStateItem.reason); end; end; {$ENDIF} // TODO :: 按时屏蔽SendMessage消息 SendMessage(GSharedInfo.MainFormHandle, WM_UPDATE_CONN_UI, 0, LPARAM(vStateItem.groupName)); finally FreeAndNil(vStateItem); end; except end; finally LeaveCriticalSection(CS_OP_Task) end; end; function AddOrder(AJson: string): Boolean; var sJson: string; vOrders: TArray<TOrderItem>; vOrderItem: TOrderItem; begin EnterCriticalSection(CS_OP_Task); try try sJson := AJson; //MessageBox(0, PWideChar(sJson), 0, 0); if not TSerizalizes.AsType<TArray<TOrderItem>>(sJson, vOrders) then Exit; if Length(vOrders) = 0 then Exit; for vOrderItem in vOrders do begin if TaskManager.ContainsKey(vOrderItem.key) then Continue; TaskManager.Add(vOrderItem); //--提交状态 SendMessage(GSharedInfo.MainFormHandle, WM_ADD_ORDER, 0, LPARAM(vOrderItem)); end; except end; finally LeaveCriticalSection(CS_OP_Task) end; end; { TTaskManager } function TTaskManager.ContainsKey(AKey: string): Boolean; begin EnterCriticalSection(FCS); try Result := FItems.ContainsKey(AKey); finally LeaveCriticalSection(FCS); end; end; constructor TTaskManager.Create; begin FItems := TObjectDictionary<string,TOrderItem>.Create([doOwnsValues]); InitializeCriticalSection(FCS); end; destructor TTaskManager.Destroy; begin FItems.Free; DeleteCriticalSection(FCS); inherited; end; function TTaskManager.EndChildTask(AOrderNo: string): Boolean; var vOrderItem: TOrderItem; I: Integer; bDoing: Boolean; begin EnterCriticalSection(FCS); try for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = AOrderNo then begin for I := Low(vOrderItem.roles) to High(vOrderItem.roles) do begin if vOrderItem.roles[I].isMain then Continue; if vOrderItem.isBusy then begin bDoing := ConnManager.GetConnItem(vOrderItem.orderNo, vOrderItem.roles[i].role) <> nil; if bDoing then Continue; end; vOrderItem.roles[I].taskState := Integer(tsFail); vOrderItem.roles[I].logMsg := '主号退出, 任务失败'; uCommand.PostState(vOrderItem, I, '', GConsoleSet.StateInterface); SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(vOrderItem.key)); FItems.Remove(vOrderItem.key); end; end; end; finally LeaveCriticalSection(FCS); end; end; procedure TTaskManager.Add(AOrderItem: TOrderItem); begin EnterCriticalSection(FCS); try if ContainsKey(AOrderItem.key) then Exit; FItems.AddOrSetValue(AOrderItem.key, AOrderItem); finally LeaveCriticalSection(FCS); end; end; procedure TTaskManager.Del(AKey: string); var sKey: string; I: Integer; begin EnterCriticalSection(FCS); try SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(AKey)); FItems.Remove(AKey); finally LeaveCriticalSection(FCS); end; end; procedure TTaskManager.DelByOrderNo(AOrderNo: string); var vOrderItem: TOrderItem; I: Integer; begin EnterCriticalSection(FCS); try for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = AOrderNo then begin for I := Low(vOrderItem.roles) to High(vOrderItem.roles) do begin vOrderItem.roles[I].taskState := Integer(tsFail); vOrderItem.roles[I].logMsg := '人为终止任务'; uCommand.PostState(vOrderItem, I, '', GConsoleSet.StateInterface); end; SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(vOrderItem.key)); FItems.Remove(vOrderItem.key); end; end; finally LeaveCriticalSection(FCS); end; end; procedure TTaskManager.DelQueueByOrderNo(AOrderNo: string); var vOrderItem: TOrderItem; I: Integer; begin EnterCriticalSection(FCS); try for vOrderItem in FItems.Values do begin if vOrderItem.isBusy then Continue; if vOrderItem.orderNo = AOrderNo then begin for I := Low(vOrderItem.roles) to High(vOrderItem.roles) do begin vOrderItem.roles[I].taskState := Integer(tsFail); vOrderItem.roles[I].logMsg := '人为终止任务'; uCommand.PostState(vOrderItem, I, '', GConsoleSet.StateInterface); end; SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(vOrderItem.key)); FItems.Remove(vOrderItem.key); end; end; finally LeaveCriticalSection(FCS); end; end; procedure TTaskManager.DelByKey(AKey: string); var vOrderItem: TOrderItem; I: Integer; begin EnterCriticalSection(FCS); try if Count = 0 then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.key = AKey then begin for I := Low(vOrderItem.roles) to High(vOrderItem.roles) do begin vOrderItem.roles[I].taskState := Integer(tsFail); vOrderItem.roles[I].logMsg := '人为终止任务'; uCommand.PostState(vOrderItem, I, '', GConsoleSet.StateInterface); end; SendMessage(GSharedInfo.MainFormHandle, WM_DEL_ORDER, 0, LPARAM(vOrderItem.key)); FItems.Remove(vOrderItem.key); end; end; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetCanSendTask(ATaskType: TTaskType): TOrderItem; var sKey: string; vOrderItem: TOrderItem; begin Result := nil; EnterCriticalSection(FCS); try for vOrderItem in FItems.Values do begin if vOrderItem.isBusy then Continue; if ATaskType = tt分仓 then begin //--并且已经有两个子号在线上, 则不能上号 if GetSameTaskCount(vOrderItem.orderNo, 1) >= 2 then Continue; if (not vOrderItem.roles[0].isMain) then begin //--如果主号还没上号,则不能上号 if ConnManager.GetMasterConnItem(vOrderItem.orderNo) = nil then Continue; end else begin if ConnManager.GetFreeCount < 2 then Continue; end; end; Result := vOrderItem; Break; end; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetCount: Integer; begin Result := 0; EnterCriticalSection(FCS); try Result := FItems.Count; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetItem(AKey: string): TOrderItem; begin Result := nil; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AKey) then Exit; Result := FItems.Items[AKey]; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetMasterOrderItem(AOrderNo, AMasterRoleName: string): TOrderItem; var vOrderItem: TOrderItem; vRoleItem: TRoleItem; begin EnterCriticalSection(FCS); Result := nil; try if FItems.Count = 0 then Exit; if AOrderNo = '' then Exit; if AMasterRoleName = '' then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = '' then Continue; if vOrderItem.orderNo <> AOrderNo then Continue; for vRoleItem in vOrderItem.roles do begin if not vRoleItem.isMain then Continue; if (vRoleItem.role = AMasterRoleName) then begin Result := vOrderItem; Exit; end; end; end; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetMasterOrderItem(AOrderItem: TOrderItem): TOrderItem; var vOrderItem: TOrderItem; begin Result := nil; EnterCriticalSection(FCS); try if FItems.Count = 0 then Exit; if AOrderItem = nil then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = '' then Continue; if (vOrderItem.orderNo = AOrderItem.orderNo) and (vOrderItem.roles[0].isMain) then begin Result := vOrderItem; Exit; end; end; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.GetSameTaskCount(AOrderNo: string; AIsBusy: Integer): Integer; var vOrderItem: TOrderItem; begin Result := 0; EnterCriticalSection(FCS); try if FItems.Count = 0 then Exit; if AOrderNo = '' then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = '' then Continue; if (vOrderItem.OrderNo = AOrderNo) and (not vOrderItem.roles[0].isMain) then begin if (AIsBusy = 0) then begin Result := Result + 1; end else if AIsBusy = 1 then begin if vOrderItem.isBusy then begin Result := Result + 1; end; end else if AIsBusy = 2 then begin if not vOrderItem.isBusy then begin Result := Result + 1; end; end; end; end; finally LeaveCriticalSection(FCS); end; end; function TTaskManager.SetRoleStep(AChildInfo: string; AConnID: DWORD): Boolean; var vLst: TStrings; sGroupName, sRoleName: string; vRoleStep: TRoleStep; vConnItem, vMasterConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); vLst := TStringList.Create; try vLst.Delimiter := ','; vLst.DelimitedText := AChildInfo; if vLst.Count = 0 then Exit; sGroupName := vLst.Values['GroupName']; sRoleName := vLst.Values['RoleName']; vRoleStep := TRoleStep(StrToIntDef(vLst.Values['RoleStep'], 0)); vConnItem := ConnManager.Items[sGroupName]; if (vConnItem = nil) then Exit; vConnItem.RoleStep := vRoleStep; Result := True; finally //--通知子号, 修改完成了 ConsoleSvr.RetCmdOk(AConnID); FreeAndNil(vLst); LeaveCriticalSection(FCS); end; end; procedure TTaskManager.SetItem(AKey: string; const Value: TOrderItem); begin EnterCriticalSection(FCS); try FItems.AddOrSetValue(AKey, Value); finally LeaveCriticalSection(FCS); end; end; function TTaskManager.SetMasterRecRoleName(ACmd: string; AConnID: DWORD): Boolean; var vLst: TStrings; sGroupName, sOrderNo, sRoleName, sMasterRoleName: string; vConnItem: TConnItem; vOrderItem: TOrderItem; vIsMain: Boolean; vRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(FCS); vLst := TStringList.Create; try vLst.Delimiter := ','; vLst.DelimitedText := ACmd; if vLst.Count = 0 then Exit; sGroupName := vLst.Values['GroupName']; sOrderNo := vLst.Values['OrderNo']; sRoleName := vLst.Values['RecvRoleName']; sMasterRoleName := vLst.Values['MasterRoleName']; if sOrderNo = '' then Exit; if sRoleName = '' then Exit; if sMasterRoleName = '' then Exit; if FItems.Count = 0 then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = '' then Continue; if vOrderItem.orderNo <> sOrderNo then Continue; for vRoleItem in vOrderItem.roles do begin if not vRoleItem.isMain then Continue; if vRoleItem.role <> sMasterRoleName then Continue; if vRoleItem.receiptRole = '' then begin AddLogMsg('设置对方加色完成MasterRole[%s]RecvRole[%s]', [sMasterRoleName, sRoleName], True); vRoleItem.receiptRole := sRoleName; end; Result := True; Exit; end; end; finally //--通知子号, 修改完成了 ConsoleSvr.RetCmdOk(AConnID); FreeAndNil(vLst); LeaveCriticalSection(FCS); end; end; function TTaskManager.ClearRecvRoleName(ACmd: string; AConnID: DWORD): Boolean; var vLst: TStrings; sGroupName, sOrderNo, sRoleName: string; vConnItem: TConnItem; vOrderItem: TOrderItem; vIsMain: Boolean; vRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(FCS); vLst := TStringList.Create; try vLst.Delimiter := ','; vLst.DelimitedText := ACmd; if vLst.Count = 0 then Exit; sGroupName := vLst.Values['GroupName']; sOrderNo := vLst.Values['OrderNo']; sRoleName := vLst.Values['RoleName']; if sOrderNo = '' then Exit; if sRoleName = '' then Exit; if FItems.Count = 0 then Exit; for vOrderItem in FItems.Values do begin if vOrderItem.orderNo = '' then Continue; if vOrderItem.orderNo <> sOrderNo then Continue; for vRoleItem in vOrderItem.roles do begin //if not vRoleItem.isMain then Continue; if vRoleItem.role <> sRoleName then Continue; vRoleItem.receiptRole := ''; Result := True; Exit; end; end; finally //--通知子号, 修改完成了 ConsoleSvr.RetCmdOk(AConnID); FreeAndNil(vLst); LeaveCriticalSection(FCS); end; end; { TConnItem } constructor TConnItem.Create; begin FConnID := 0; FGroupName := ''; FOrderItem := nil; FState := sms空闲; FInterval := 0; Suspend := False; FLogMsgs := TStringList.Create; end; destructor TConnItem.Destroy; begin FreeAndNil(FLogMsgs); inherited; end; { TConnManager } constructor TConnManager.Create; begin InitializeCriticalSection(FCS); FItems := TObjectDictionary<string,TConnItem>.Create([doOwnsValues]); end; destructor TConnManager.Destroy; begin FItems.Free; DeleteCriticalSection(FCS); inherited; end; procedure TConnManager.Add(AConnItem: TConnItem); begin SetItem(AConnItem.GroupName, AConnItem); end; procedure TConnManager.Del(AKey: string); var sKey: string; begin EnterCriticalSection(FCS); try if not FItems.ContainsKey(AKey) then Exit; FItems.Remove(AKey); finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetConnOrderInfo(AGroupName: string): string; var vConnitem: TConnItem; begin EnterCriticalSection(FCS); try vConnItem := ConnManager.Items[AGroupName]; if vConnItem = nil then Exit; if vConnItem.OrderItem = nil then Exit; Result := TSerizalizes.AsJSON<TOrderItem>(vConnItem.OrderItem); finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetConnItem(AOrderNo: string; ARoleName: string): TConnItem; var sKey: string; vConnItem: TConnItem; vOrderItem: TOrderItem; vRoleItem: TRoleItem; begin Result := nil; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin vOrderItem := vConnItem.OrderItem; if vOrderItem = nil then Continue; if vOrderItem.orderNo <> AOrderNo then Continue; for vRoleItem in vOrderItem.roles do begin if vRoleItem.role <> ARoleName then Continue; Result := vConnItem; Exit; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetCount: Integer; begin EnterCriticalSection(FCS); try Result := FItems.Count; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetFreeCount: Integer; var sKey: string; vConnItem: TConnItem; begin Result := 0; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State = sms空闲 then begin Result := Result + 1; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetFreeMachine: TConnItem; var sKey: string; vConnItem: TConnItem; begin Result := nil; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State = sms空闲 then begin Result := vConnItem; Break; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetGroupName(AConnID: DWORD): string; var vConnItem: TConnItem; begin Result := ''; EnterCriticalSection(FCS); try if FItems.Count = 0 then Exit; for vConnItem in FItems.Values do begin if AConnID = vConnItem.ConnID then begin Result := vConnItem.GroupName; Exit; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetMasterConnItem(AConnItem: TConnItem): TConnItem; var vConnItem: TConnItem; begin Result := nil; EnterCriticalSection(FCS); try if FItems.Count = 0 then Exit; if AConnItem = nil then Exit; if AConnItem.OrderItem = nil then Exit; for vConnItem in FItems.Values do begin if vConnItem.OrderItem = nil then Continue; if (vConnItem.OrderItem.orderNo = AConnItem.OrderItem.orderNo) and (vConnItem.OrderItem.roles[0].isMain) then begin Result := vConnItem; Exit; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetMasterConnItem(AOrderNo: string): TConnItem; var vConnItem: TConnItem; begin Result := nil; EnterCriticalSection(FCS); try if FItems.Count = 0 then Exit; if AOrderNo = '' then Exit; for vConnItem in FItems.Values do begin if vConnItem.OrderItem = nil then Continue; if (vConnItem.OrderItem.orderNo = AOrderNo) and (vConnItem.OrderItem.roles[0].isMain) then begin Result := vConnItem; Exit; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetTargerConnItem(ATargetRoleName:string; AOrderNo:string): TConnItem; var vConnItem: TConnItem; vRoleItem: TRoleItem; begin Result := nil; EnterCriticalSection(FCS); try AddLogMsg('RoleName:%s AOrderNo:%s', [ATargetRoleName, AOrderNo], True); if FItems.Count = 0 then Exit; if ATargetRoleName = '' then Exit; if AOrderNo = '' then Exit; for vConnItem in FItems.Values do begin if vConnItem.OrderItem = nil then Continue; if vConnItem.OrderItem.orderNo <> AOrderNo then Continue; for vRoleItem in vConnItem.OrderItem.roles do begin if (vRoleItem.role = ATargetRoleName) then begin AddLogMsg('已找到的对方连接[%s]', [vConnItem.GroupName], True); Result := vConnItem; Exit; end; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.GetItem(AKey: string): TConnItem; begin Result := nil; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AKey) then Exit; Result := FItems.Items[AKey]; finally LeaveCriticalSection(FCS); end; end; procedure TConnManager.SetItem(AKey: string; const Value: TConnItem); begin EnterCriticalSection(FCS); try FItems.AddOrSetValue(AKey, Value); finally LeaveCriticalSection(FCS); end; end; function TConnManager.ReSetRoleStep(AConnID: DWORD; AGroupName: string; ARoleName: string; ATargetRoleName: string; ARoleStep: TRoleStep): Boolean; var vConnItem, vTargetConnItem: TConnItem; vRoleItem, vTargetRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; vConnItem := FItems[AGroupName]; if vConnItem = nil then begin //--没有找到对应的连接 AddLogMsg('没有找到发货机[%s]', [AGroupName], True); Exit; end; for vTargetConnItem in FItems.Values do begin if vTargetConnItem.State <> sms繁忙 then Continue; if vTargetConnItem.OrderItem = nil then Continue; for vRoleItem in vConnItem.OrderItem.roles do begin if vRoleItem.role <> ARoleName then Continue; for vTargetRoleItem in vTargetConnItem.OrderItem.roles do begin if vTargetRoleItem.role <> ATargetRoleName then Continue; vTargetConnItem.RoleStep := ARoleStep; vConnItem.RoleStep := ARoleStep; ConsoleSvr.RetCmdOk(AConnID); Result := True; AddLogMsg('重置步骤成功[%d]', [Integer(ARoleStep)], True); Exit; end; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.RetRoleStep(AConnID: DWORD; AGroupName: string): Boolean; var vConnItem, vTargetConnItem: TConnItem; vRoleItem, vTargetRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; vConnItem := FItems[AGroupName]; if vConnItem = nil then begin ConsoleSvr.RetRoleStep(AConnID, rsNormal); Exit; end; ConsoleSvr.RetRoleStep(AConnID, vConnItem.RoleStep); Result := True; finally LeaveCriticalSection(FCS); end; end; function TConnManager.RetTargetRoleStep(AConnID: DWORD; AGroupName: string; ARoleName: string; ATargetRoleName: string): Boolean; var vConnItem, vTargetConnItem: TConnItem; vRoleItem, vTargetRoleItem: TRoleItem; begin Result := False; EnterCriticalSection(FCS); try AddLogMsg('GroupName:%s RoleName:%s TargetRoleName:%s', [AGroupName, ARoleName, ATargetRoleName]); vConnItem := FItems[AGroupName]; if vConnItem = nil then begin ConsoleSvr.RetRoleStep(AConnID, rsNormal); Exit; end; if ATargetRoleName = '' then begin ConsoleSvr.RetRoleStep(AConnID, rsNormal); Exit; end; for vRoleItem in vConnItem.OrderItem.roles do begin if vRoleItem.role <> ARoleName then Continue; //if vRoleItem.receiptRole <> ATargetRoleName then Continue; vTargetConnItem := GetTargerConnItem(vRoleItem.receiptRole, vConnItem.OrderItem.orderNo); if (vTargetConnItem = nil) or (vTargetConnItem.OrderItem = nil) then begin AddLogMsg('1--GroupName:%s RoleName:%s TargetRoleName:%s', [AGroupName, ARoleName, ATargetRoleName]); ConsoleSvr.RetRoleStep(AConnID, rs对方任务失败); if vRoleItem.isMain then vRoleItem.receiptRole := ''; Exit; end; for vTargetRoleItem in vTargetConnItem.OrderItem.roles do begin if (vTargetRoleItem.role = ATargetRoleName) and (vTargetRoleItem.receiptRole = ARoleName) then begin ConsoleSvr.RetRoleStep(AConnID, vTargetConnItem.RoleStep); Result := True; Exit; end; if (vTargetRoleItem.role = ATargetRoleName) then begin ConsoleSvr.RetRoleStep(AConnID, rsNormal); Result := True; Exit; end; end; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.RetRecvRoleName(AConnId: DWORD; AGroupName: string; AMasterRoleName: string): Boolean; var vConnItem: TConnItem; vRoleItem: TRoleItem; sRecRoleName: string; begin Result := False; EnterCriticalSection(FCS); try sRecRoleName := '___Error___'; if not FItems.ContainsKey(AGroupName) then begin ConsoleSvr.RetRecvRoleName(AConnID, sRecRoleName); Exit; end; vConnItem := FItems[AGroupName]; if vConnItem = nil then begin ConsoleSvr.RetRoleStep(AConnID, rsNormal); Exit; end; if vConnItem.State <> sms繁忙 then begin ConsoleSvr.RetRecvRoleName(AConnID, sRecRoleName); Exit; end; if vConnItem.OrderItem = nil then begin ConsoleSvr.RetRecvRoleName(AConnID, sRecRoleName); Exit; end; for vRoleItem in vConnItem.OrderItem.roles do begin if not vRoleItem.isMain then Continue; if vRoleItem.role = AMasterRoleName then begin sRecRoleName := vRoleItem.receiptRole; Break; end; end; ConsoleSvr.RetRecvRoleName(AConnID, sRecRoleName); Result := True; finally LeaveCriticalSection(FCS); end; end; function TConnManager.SuspendTask(AGroupName: string): Boolean; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; if FItems[AGroupName].State <> sms繁忙 then Exit; Result := ConsoleSvr.SuspendTask(FItems[AGroupName].ConnID, AGroupName); FItems[AGroupName].Suspend := True; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ReStartTask(AGroupName: string): Boolean; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; if FItems[AGroupName].State <> sms繁忙 then Exit; Result := ConsoleSvr.ResumeTask(FItems[AGroupName].ConnID, AGroupName); FItems[AGroupName].Suspend := False; finally LeaveCriticalSection(FCS); end; end; function TConnManager.StopTask(AGroupName: string): Boolean; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; if FItems[AGroupName].State <> sms繁忙 then Exit; Result := ConsoleSvr.StopTask(FItems[AGroupName].ConnID, AGroupName); finally LeaveCriticalSection(FCS); end; end; function TConnManager.SuspendAllTask: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State <> sms繁忙 then Continue; Result := ConsoleSvr.SuspendTask(vConnItem.ConnID, vConnItem.GroupName); vConnItem.Suspend := True; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ReStartAllTask: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin Result := ConsoleSvr.ResumeTask(vConnItem.ConnID, vConnItem.GroupName); vConnItem.Suspend := False; end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.StopAllTask(AOrderNo: string): Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State <> sms繁忙 then Continue; if vConnItem.OrderItem = nil then Continue; if vConnItem.OrderItem.orderNo <> AOrderNo then Continue; Result := ConsoleSvr.StopTask(vConnItem.ConnID, vConnItem.GroupName); end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ClearLog(AGroupName: string): Boolean; begin Result := False; EnterCriticalSection(FCS); try if not FItems.ContainsKey(AGroupName) then Exit; FItems[AGroupName].LogMsgs.Clear; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ClearAllLog: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do vConnItem.LogMsgs.Clear; finally LeaveCriticalSection(FCS); end; end; function TConnManager.LogoutAll: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State = sms繁忙 then Continue; Result := ConsoleSvr.LogOff(vConnItem.ConnID, vConnItem.GroupName); end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ReBootAll: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State = sms繁忙 then Continue; Result := ConsoleSvr.ReBoot(vConnItem.ConnID, vConnItem.GroupName); end; finally LeaveCriticalSection(FCS); end; end; function TConnManager.ShutdownAll: Boolean; var vConnItem: TConnItem; begin Result := False; EnterCriticalSection(FCS); try for vConnItem in FItems.Values do begin if vConnItem.State = sms繁忙 then Continue; Result := ConsoleSvr.Shutdown(vConnItem.ConnID, vConnItem.GroupName); end; finally LeaveCriticalSection(FCS); end; end; initialization TaskManager := TTaskManager.Create(); ConnManager := TConnManager.Create(); finalization TaskManager.Free; ConnManager.Free; end.
UNIT game; INTERFACE USES crt, sysutils, constants, structures; PROCEDURE ajouterPion(VAR g : grille; pionAAjouter : pion; x,y : INTEGER); FUNCTION remplirGrille(): grille; PROCEDURE initPioche(nbrCouleurs, nbrFormes, nbrTuiles : INTEGER); PROCEDURE shufflePioche; FUNCTION creerMain: tabPion; PROCEDURE removePionFromMain(VAR main : tabPion; p : pion); PROCEDURE echangerPion(VAR main : tabPion; p : pion); FUNCTION piocher : pion; FUNCTION getPiocheSize : INTEGER; FUNCTION maxPiocheSize : INTEGER; FUNCTION copyGrille(a : grille) : grille; PROCEDURE log(text : STRING); PROCEDURE redimensionnerGrille(VAR g : grille); FUNCTION copyMain(main : tabPion) : tabPion; FUNCTION copyTabPos(main : tabPos) : tabPos; PROCEDURE delayy(s : INTEGER); IMPLEMENTATION VAR globalPioche : typePioche; globalIndexPioche : INTEGER; gNbrCouleurs, gNbrFormes, gNbrTuiles : INTEGER; // on bloque le terminal pour une durée s PROCEDURE delayy(s : INTEGER); BEGIN delay(s); END; // on copie la grille pour pouvoir faire les test necessaire au placement des pions FUNCTION copyGrille(a : grille) : grille; VAR i, j : INTEGER; newGrille : grille; BEGIN setLength(newGrille, length(a), length(a)); FOR i := 0 TO length(a) - 1 DO BEGIN FOR j := 0 TO length(a) - 1 DO BEGIN newGrille[i, j] := a[i, j]; END; END; copyGrille := newGrille; END; PROCEDURE log(text : STRING); BEGIN writeln(text); readln(); END; //on determine la taille de la pioche en fonction du nombre de forme et de couleur FUNCTION getPiocheSize : INTEGER; BEGIN getPiocheSize := gNbrFormes * gNbrTuiles * gNbrCouleurs - globalIndexPioche; END; FUNCTION maxPiocheSize : INTEGER; BEGIN maxPiocheSize := gNbrFormes * gNbrTuiles * gNbrCouleurs; END; // procedure qui permet d'echanger un pion de notre main et le remettre dans la pioche PROCEDURE echangerPion(VAR main : tabPion; p : pion); VAR i, rand : INTEGER; tmp : pion; BEGIN IF globalIndexPioche + 1 < gNbrCouleurs * gNbrFormes * gNbrTuiles - 1 THEN BEGIN FOR i := 0 TO length(main) - 1 DO BEGIN IF (main[i].couleur = p.couleur) AND (main[i].forme = p.forme)THEN BEGIN rand := random(gNbrCouleurs * gNbrFormes * gNbrTuiles - 1 - globalIndexPioche); tmp := main[i]; main[i] := globalPioche[rand]; globalPioche[rand] := tmp; END; END; END; END; // on initialise la pioche PROCEDURE initPioche(nbrCouleurs, nbrFormes, nbrTuiles : INTEGER); VAR piocheIndex, i, j, k : INTEGER; BEGIN setLength(globalPioche, nbrCouleurs * nbrFormes * nbrTuiles); piocheIndex := 0; gNbrFormes := nbrFormes; gNbrTuiles := nbrTuiles; gNbrCouleurs := nbrCouleurs; globalIndexPioche := 0; // génération des pions en fonction des paramètres de départ FOR i := 0 TO nbrTuiles - 1 DO BEGIN FOR j := 1 TO nbrFormes DO BEGIN FOR k := 1 TO nbrCouleurs DO BEGIN globalPioche[piocheIndex].couleur := k; globalPioche[piocheIndex].forme := j; inc(piocheIndex); END; END; END; END; // cela permet de mettre un pion dans la pioche et en prendre un autre PROCEDURE swap(a,b : INTEGER); VAR tmp : pion; BEGIN tmp := globalPioche[a]; globalPioche[a] := globalPioche[b]; globalPioche[b] := tmp; END; // on copie la main pour pouvoir faire les test necessaire au placement de plusieurs pions FUNCTION copyMain(main : tabPion) : tabPion; VAR i : INTEGER; tmp : tabPion; BEGIN setLength(tmp, length(main)); FOR i := 0 TO length(main) - 1 DO tmp[i] := main[i]; copyMain := tmp; END; // on copie les positions des pions a placer FUNCTION copyTabPos(main : tabPos) : tabPos; VAR i : INTEGER; tmp : tabPos; BEGIN setLength(tmp, length(main)); FOR i := 0 TO length(main) - 1 DO tmp[i] := main[i]; copyTabPos := tmp; END; // ici on enleve de la main le pion que l'on a placé PROCEDURE swapLastMain(VAR main : tabPion; a: INTEGER); VAR tmp : pion; BEGIN tmp := main[a]; main[a] := main[length(main) - 1]; main[length(main) - 1] := tmp; END; // on melange la pioche PROCEDURE shufflePioche; VAR i : INTEGER; BEGIN Randomize; FOR i := 0 TO (length(globalPioche) - 1) * 3 DO BEGIN swap(random(length(globalPioche) - 1), random(length(globalPioche) - 1)); END; END; // on agrandit la grille de 1 par 1 PROCEDURE redimensionnerGrille(VAR g : grille); VAR tmpGrille : grille; i, j : INTEGER; BEGIN tmpGrille := copyGrille(g); setLength(g, length(g) + 2, length(g) + 2); FOR i := 0 TO length(tmpGrille) - 1 DO BEGIN FOR j := 0 TO length(tmpGrille) - 1 DO BEGIN g[i + 1, j + 1] := PION_NULL; g[i + 1, j + 1] := tmpGrille[i,j]; END; END; END; // on ajoute le pion en verifiant que le selector donne une position dans la grille PROCEDURE ajouterPion(VAR g : grille; pionAAjouter : pion; x,y : INTEGER); BEGIN IF (x <= 1) OR (y <= 1) OR (y >= length(g) - 1) OR (x >= length(g) - 1) THEN BEGIN redimensionnerGrille(g); IF (x <= 1) AND (y <= 1) THEN g[x + 1, y + 1] := pionAAjouter ELSE BEGIN IF (x <= 1) THEN g[x + 1, y + 1] := pionAAjouter; IF (y <= 1) THEN g[x + 1, y + 1] := pionAAjouter; END; IF (y >= length(g) - 3) AND (x >= length(g) - 3) THEN g[x + 1, y + 1] := pionAAjouter ELSE BEGIN IF (y >= length(g) - 3) THEN g[x + 1, y + 1] := pionAAjouter; IF (x >= length(g) - 3) THEN g[x + 1, y + 1] := pionAAjouter; END; END ELSE BEGIN g[x,y] := pionAAjouter; END; END; // on initie la grille avec des pions vide FUNCTION remplirGrille(): grille; VAR i , j : INTEGER; g : grille; BEGIN setLength(g, 20, 20); FOR i := 0 TO 20 -1 DO BEGIN FOR j := 0 TO 20 -1 DO BEGIN g[i,j].couleur := COULEUR_NULL; g[i,j].forme := FORME_NULL; END; END; remplirGrille := g; END; FUNCTION removeFromArray(main : tabPion; i : INTEGER) : tabPion; BEGIN swapLastMain(main, i); setLength(main, length(main) - 1); removeFromArray := main; END; // on enleve un pion de la main PROCEDURE removePionFromMain(VAR main : tabPion; p : pion); VAR i, indexToRemove : INTEGER; BEGIN FOR i := 0 TO length(main) - 1 DO BEGIN IF (p.couleur = main[i].couleur) and (p.forme = main[i].forme) THEN indexToRemove := i; END; main := removeFromArray(main, indexToRemove); END; //permet de mettre un autre pion dans la main FUNCTION piocher : pion; BEGIN IF globalIndexPioche < gNbrCouleurs * gNbrFormes * gNbrTuiles THEN BEGIN inc(globalIndexPioche); piocher := globalPioche[globalIndexPioche]; END ELSE piocher := PION_NULL; END; // on creer la main en piochant a chaque tour de boucle FUNCTION creerMain: tabPion; VAR main : tabPion; i : INTEGER; BEGIN setLength(main, 6); FOR i := 0 TO 5 DO main[i] := piocher; creerMain := main; END; END.
{ DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(DBEBr Framework) @created(20 Jul 2016) @author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>) } unit dbebr.driver.wire.mongodb; interface uses DB, Classes, SysUtils, DBClient, Variants, StrUtils, Math, /// MongoDB mongoWire, bsonTools, JsonDoc, MongoWireConnection, // DBEBr dbebr.driver.connection, dbebr.factory.interfaces; type TMongoDBQuery = class(TCustomClientDataSet) private FConnection: TMongoWireConnection; FCollection: String; procedure SetConnection(AConnection: TMongoWireConnection); function GetSequence(AMongoCampo: string): Int64; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Find(ACommandText: String); property Collection: String read FCollection write FCollection; end; // Classe de conexão concreta com dbExpress TDriverMongoWire = class(TDriverConnection) protected FConnection: TMongoWireConnection; // FScripts: TStrings; procedure CommandUpdateExecute(const ACommandText: String; const AParams: TParams); procedure CommandInsertExecute(const ACommandText: String; const AParams: TParams); procedure CommandDeleteExecute(const ACommandText: String; const AParams: TParams); public constructor Create(const AConnection: TComponent; const ADriverName: TDriverName); override; destructor Destroy; override; procedure Connect; override; procedure Disconnect; override; procedure ExecuteDirect(const ASQL: string); override; procedure ExecuteDirect(const ASQL: string; const AParams: TParams); override; procedure ExecuteScript(const ASQL: string); override; procedure AddScript(const ASQL: string); override; procedure ExecuteScripts; override; function IsConnected: Boolean; override; function InTransaction: Boolean; override; function CreateQuery: IDBQuery; override; function CreateResultSet(const ASQL: String): IDBResultSet; override; function ExecuteSQL(const ASQL: string): IDBResultSet; override; end; TDriverQueryMongoWire = class(TDriverQuery) private FConnection: TMongoWireConnection; FCommandText: string; protected procedure SetCommandText(ACommandText: string); override; function GetCommandText: string; override; public constructor Create(AConnection: TMongoWireConnection); destructor Destroy; override; procedure ExecuteDirect; override; function ExecuteQuery: IDBResultSet; override; end; TDriverResultSetMongoWire = class(TDriverResultSet<TMongoDBQuery>) public constructor Create(ADataSet: TMongoDBQuery); override; destructor Destroy; override; function NotEof: Boolean; override; function GetFieldValue(const AFieldName: string): Variant; overload; override; function GetFieldValue(const AFieldIndex: Integer): Variant; overload; override; function GetFieldType(const AFieldName: string): TFieldType; overload; override; function GetField(const AFieldName: string): TField; override; end; implementation uses ormbr.utils, ormbr.bind, ormbr.mapping.explorer, ormbr.rest.json, ormbr.mapping.rttiutils, ormbr.objects.helper; { TDriverMongoWire } constructor TDriverMongoWire.Create(const AConnection: TComponent; const ADriverName: TDriverName); begin inherited; FConnection := AConnection as TMongoWireConnection; FDriverName := ADriverName; // FScripts := TStrings.Create; end; destructor TDriverMongoWire.Destroy; begin // FScripts.Free; FConnection := nil; inherited; end; procedure TDriverMongoWire.Disconnect; begin inherited; FConnection.Connected := False; end; procedure TDriverMongoWire.ExecuteDirect(const ASQL: string); begin inherited; try FConnection.RunCommand(ASQL); except on E: Exception do raise Exception.Create(E.Message); end; end; procedure TDriverMongoWire.ExecuteDirect(const ASQL: string; const AParams: TParams); var LCommand: string; begin LCommand := TUtilSingleton .GetInstance .ParseCommandNoSQL('command', ASQL); if LCommand = 'insert' then CommandInsertExecute(ASQL, Aparams) else if LCommand = 'update' then CommandUpdateExecute(ASQL, AParams) else if LCommand = 'delete' then CommandDeleteExecute(ASQL, AParams); end; procedure TDriverMongoWire.ExecuteScript(const ASQL: string); begin inherited; try FConnection.RunCommand(ASQL); except on E: Exception do raise Exception.Create(E.Message); end; end; procedure TDriverMongoWire.ExecuteScripts; var LFor: Integer; begin inherited; // try // for LFor := 0 to FScripts.Count -1 do // FConnection.RunCommand(FScripts[LFor]); // finally // FScripts.Clear; // end; end; function TDriverMongoWire.ExecuteSQL(const ASQL: string): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQueryMongoWire.Create(FConnection); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; procedure TDriverMongoWire.AddScript(const ASQL: string); begin inherited; // FScripts.Add(ASQL); end; procedure TDriverMongoWire.CommandInsertExecute(const ACommandText: String; const AParams: TParams); var LDoc: IJSONDocument; LQuery: String; LCollection: String; LUtil: IUtilSingleton; begin LUtil := TUtilSingleton.GetInstance; LCollection := LUtil.ParseCommandNoSQL('collection', ACommandText); LQuery := LUtil.ParseCommandNoSQL('json', ACommandText); LDoc := JSON(LQuery); try FConnection .MongoWire .Insert(LCollection, LDoc); except raise EMongoException.Create('MongoWire: não foi possível inserir o Documento'); end; end; procedure TDriverMongoWire.CommandUpdateExecute(const ACommandText: String; const AParams: TParams); var LDocQuery: IJSONDocument; LDocFilter: IJSONDocument; LFilter: String; LQuery: String; LCollection: String; LUtil: IUtilSingleton; begin LUtil := TUtilSingleton.GetInstance; LCollection := LUtil.ParseCommandNoSQL('collection', ACommandText); LFilter := LUtil.ParseCommandNoSQL('filter', ACommandText); LQuery := LUtil.ParseCommandNoSQL('json', ACommandText); LDocQuery := JSON(LQuery); LDocFilter := JSON(LFilter); try FConnection .MongoWire .Update(LCollection, LDocFilter, LDocQuery); except raise EMongoException.Create('MongoWire: não foi possível alterar o Documento'); end; end; procedure TDriverMongoWire.CommandDeleteExecute(const ACommandText: String; const AParams: TParams); var LDoc: IJSONDocument; LQuery: String; LCollection: String; LUtil: IUtilSingleton; begin LUtil := TUtilSingleton.GetInstance; LCollection := LUtil.ParseCommandNoSQL('collection', ACommandText); LQuery := LUtil.ParseCommandNoSQL('json', ACommandText); LDoc := JSON(LQuery); try FConnection .MongoWire .Delete(LCollection, LDoc); except raise EMongoException.Create('MongoWire: não foi possível remover o Documento'); end; end; procedure TDriverMongoWire.Connect; begin inherited; FConnection.Connected := True; end; function TDriverMongoWire.InTransaction: Boolean; begin Result := False; end; function TDriverMongoWire.IsConnected: Boolean; begin inherited; Result := FConnection.Connected = True; end; function TDriverMongoWire.CreateQuery: IDBQuery; begin Result := TDriverQueryMongoWire.Create(FConnection); end; function TDriverMongoWire.CreateResultSet(const ASQL: String): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQueryMongoWire.Create(FConnection); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; { TDriverDBExpressQuery } constructor TDriverQueryMongoWire.Create(AConnection: TMongoWireConnection); begin FConnection := AConnection; end; destructor TDriverQueryMongoWire.Destroy; begin inherited; end; function TDriverQueryMongoWire.ExecuteQuery: IDBResultSet; var LUtil: IUtilSingleton; LResultSet: TMongoDBQuery; LObject: TObject; begin LUtil := TUtilSingleton.GetInstance; LResultSet := TMongoDBQuery.Create(nil); LResultSet.SetConnection(FConnection); LResultSet.Collection := LUTil.ParseCommandNoSQL('collection', FCommandText); LObject := TMappingExplorer .GetInstance .Repository .FindEntityByName('T' + LResultSet.Collection).Create; TBind.Instance .SetInternalInitFieldDefsObjectClass(LResultSet, LObject); LResultSet.CreateDataSet; LResultSet.LogChanges := False; try try LResultSet.Find(FCommandText); except on E: Exception do begin LResultSet.Free; raise Exception.Create(E.Message); end; end; Result := TDriverResultSetMongoWire.Create(LResultSet); if LResultSet.RecordCount = 0 then Result.FetchingAll := True; finally LObject.Free; end; end; function TDriverQueryMongoWire.GetCommandText: string; begin Result := FCommandText; end; procedure TDriverQueryMongoWire.SetCommandText(ACommandText: string); begin inherited; FCommandText := ACommandText; end; procedure TDriverQueryMongoWire.ExecuteDirect; begin try FConnection.RunCommand(FCommandText); except on E: Exception do raise Exception.Create(E.Message); end; end; { TDriverResultSetMongoWire } constructor TDriverResultSetMongoWire.Create(ADataSet: TMongoDBQuery); begin FDataSet := ADataSet; inherited; end; destructor TDriverResultSetMongoWire.Destroy; begin FDataSet.Free; inherited; end; function TDriverResultSetMongoWire.GetFieldValue(const AFieldName: string): Variant; var LField: TField; begin LField := FDataSet.FieldByName(AFieldName); Result := GetFieldValue(LField.Index); end; function TDriverResultSetMongoWire.GetField(const AFieldName: string): TField; begin Result := FDataSet.FieldByName(AFieldName); end; function TDriverResultSetMongoWire.GetFieldType(const AFieldName: string): TFieldType; begin Result := FDataSet.FieldByName(AFieldName).DataType; end; function TDriverResultSetMongoWire.GetFieldValue(const AFieldIndex: Integer): Variant; begin if AFieldIndex > FDataSet.FieldCount - 1 then Exit(Variants.Null); if FDataSet.Fields[AFieldIndex].IsNull then Result := Variants.Null else Result := FDataSet.Fields[AFieldIndex].Value; end; function TDriverResultSetMongoWire.NotEof: Boolean; begin if not FFirstNext then FFirstNext := True else FDataSet.Next; Result := not FDataSet.Eof; end; { TMongoDBQuery } constructor TMongoDBQuery.Create(AOwner: TComponent); begin inherited; end; destructor TMongoDBQuery.Destroy; begin inherited; end; procedure TMongoDBQuery.Find(ACommandText: String); var LDocQuery: IJSONDocument; LDocRecord: IJSONDocument; LDocFields: IJSONDocument; LQuery: TMongoWireQuery; LUtil: IUtilSingleton; LObject: TObject; LFilter: string; begin LUtil := TUtilSingleton.GetInstance; LFilter := LUtil.ParseCommandNoSQL('filter', ACommandText, '{}'); LDocQuery := JSON(LFilter); LDocFields := JSON('{_id:0}'); LDocRecord := JSON; LQuery := TMongoWireQuery.Create(FConnection.MongoWire); DisableControls; try LQuery.Query(FCollection, LDocQuery, LDocFields); while LQuery.Next(LDocRecord) do begin LObject := TMappingExplorer .GetInstance .Repository .FindEntityByName('T' + FCollection).Create; LObject.MethodCall('Create', []); try TORMBrJson .JsonToObject(LDocRecord.ToString, LObject); /// <summary> /// Popula do dataset usado pelo ORMBr /// </summary> Append; TBind.Instance .SetPropertyToField(LObject, Self); Post; finally LObject.Free; end; end; finally LQuery.Free; First; EnableControls; end; end; function TMongoDBQuery.GetSequence(AMongoCampo: string): Int64; //Var // LDocD, LChave, LDocR: IJSONDocument; // LJsonObj: TJSONObject; // LField, LComandSave, LComandModify: TStringBuilder; // LCollectionSeq, sCollectionField: string; // LRetorno: Int64; begin // LField := TStringBuilder.Create; // LComandSave := TStringBuilder.Create; // LComandModify := TStringBuilder.Create; // LJsonObj := TJSONObject.Create; // try // LComandSave.clear; // LComandModify.clear; // LField.clear; // LField.Append('_id_').Append(AnsiLowerCase( AMongoCampo )); // // LCollectionSeq := '_sequence'; // sCollectionField := '_id'; // // LComandSave.Append('{ findAndModify: "') // .Append(LCollectionSeq) // .Append('", query: { ') // .Append(sCollectionField) // .Append(': "') // .Append(FCollection) // .Append('" }, update: {') // .Append(sCollectionField) // .Append(': "') // .Append(FCollection) // .Append('", ') // .Append(LField.ToString) // .Append(': 0 }, upsert:true }'); // // LComandModify.Append('{ findAndModify: "') // .Append(LCollectionSeq) // .Append('", query: { ') // .Append(sCollectionField) // .Append(': "') // .Append(FCollection) // .Append('" }, update: { $inc: { ') // .Append(LField.ToString) // .Append(': 1 } }, new:true }'); // LJsonObj.AddPair(sCollectionField, TJSONString.Create(FCollection)); // LChave := LJsonObj.ToJSON; // try // LDocD := FConnection.FMongoWire.Get(LCollectionSeq, LChave); // LRetorno := StrToInt64(VarToStr(LDocD[LField.ToString])); // except // LDocD := JsonToBson(LComandSave.ToString); // LDocR := FConnection.FMongoWire.RunCommand(LDocD); // end; // try // LDocD := JsonToBson(LComandModify.ToString); // LDocR := FConnection.FMongoWire.RunCommand(LDocD); // Result := StrToInt(VarToStr(BSON(LDocR['value'])[LField.ToString])); // except // Result := -1; // raise EMongoException.Create('Mongo: não foi possível gerar o AutoIncremento.'); // end; // finally // LField.Free; // LComandSave.Free; // LComandModify.Free; // LJsonObj.Free; // end; end; procedure TMongoDBQuery.SetConnection(AConnection: TMongoWireConnection); begin FConnection := AConnection; end; end.
{ Created by BGRA Controls Team Dibo, Circular, lainz (007) and contributors. For detailed information see readme.txt Site: https://sourceforge.net/p/bgra-controls/ Wiki: http://wiki.lazarus.freepascal.org/BGRAControls Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit BGRAKnob; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, BGRAGradients, BGRABitmap, BGRABitmapTypes; type TBGRAKnobPositionType = (kptLineSquareCap, kptLineRoundCap, kptFilledCircle, kptHollowCircle); TBGRAKnobValueChangedEvent = procedure(Sender: TObject; Value: single) of object; { TBGRAKnob } TBGRAKnob = class(TGraphicControl) private { Private declarations } FPhong: TPhongShading; FCurveExponent: single; FKnobBmp: TBGRABitmap; FKnobColor: TColor; FAngularPos: single; FPositionColor: TColor; FPositionMargin: single; FPositionOpacity: byte; FPositionType: TBGRAKnobPositionType; FPositionWidth: single; FSettingAngularPos: boolean; FUsePhongLighting: boolean; FMinValue, FMaxValue: single; FOnKnobValueChange: TBGRAKnobValueChangedEvent; FStartFromBottom: boolean; procedure CreateKnobBmp; function GetLightIntensity: integer; function GetValue: single; procedure SetCurveExponent(const AValue: single); procedure SetLightIntensity(const AValue: integer); procedure SetStartFromBottom(const AValue: boolean); procedure SetValue(AValue: single); procedure SetMaxValue(AValue: single); procedure SetMinValue(AValue: single); procedure SetPositionColor(const AValue: TColor); procedure SetPositionMargin(AValue: single); procedure SetPositionOpacity(const AValue: byte); procedure SetPositionType(const AValue: TBGRAKnobPositionType); procedure SetPositionWidth(const AValue: single); procedure SetUsePhongLighting(const AValue: boolean); procedure UpdateAngularPos(X, Y: integer); procedure SetKnobColor(const AValue: TColor); protected { Protected declarations } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; procedure MouseMove(Shift: TShiftState; X, Y: integer); override; procedure Paint; override; procedure Resize; override; function ValueCorrection(var AValue: single): boolean; virtual; overload; function ValueCorrection: boolean; virtual; overload; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; public { Streaming } procedure SaveToFile(AFileName: string); procedure LoadFromFile(AFileName: string); procedure OnFindClass({%H-}Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); published { Published declarations } property Anchors; property CurveExponent: single read FCurveExponent write SetCurveExponent; property KnobColor: TColor read FKnobColor write SetKnobColor; property LightIntensity: integer read GetLightIntensity write SetLightIntensity; property PositionColor: TColor read FPositionColor write SetPositionColor; property PositionWidth: single read FPositionWidth write SetPositionWidth; property PositionOpacity: byte read FPositionOpacity write SetPositionOpacity; property PositionMargin: single read FPositionMargin write SetPositionMargin; property PositionType: TBGRAKnobPositionType read FPositionType write SetPositionType; property UsePhongLighting: boolean read FUsePhongLighting write SetUsePhongLighting; property MinValue: single read FMinValue write SetMinValue; property MaxValue: single read FMaxValue write SetMaxValue; property Value: single read GetValue write SetValue; property OnValueChanged: TBGRAKnobValueChangedEvent read FOnKnobValueChange write FOnKnobValueChange; property StartFromBottom: boolean read FStartFromBottom write SetStartFromBottom; end; procedure Register; implementation uses Math; procedure Register; begin {$I icons\bgraknob_icon.lrs} RegisterComponents('BGRA Controls', [TBGRAKnob]); end; { TBGRAKnob } procedure TBGRAKnob.CreateKnobBmp; var tx, ty: integer; h: single; d2: single; v: TPointF; p: PBGRAPixel; center: TPointF; yb: integer; xb: integer; mask: TBGRABitmap; Map: TBGRABitmap; BGRAKnobColor: TBGRAPixel; begin tx := ClientWidth; ty := ClientHeight; if (tx = 0) or (ty = 0) then exit; FreeAndNil(FKnobBmp); FKnobBmp := TBGRABitmap.Create(tx, ty); center := PointF((tx - 1) / 2, (ty - 1) / 2); BGRAKnobColor := KnobColor; if UsePhongLighting then begin //compute knob height map Map := TBGRABitmap.Create(tx, ty); for yb := 0 to ty - 1 do begin p := map.ScanLine[yb]; for xb := 0 to tx - 1 do begin //compute vector between center and current pixel v := PointF(xb, yb) - center; //scale down to unit circle (with 1 pixel margin for soft border) v.x /= tx / 2 + 1; v.y /= ty / 2 + 1; //compute squared distance with scalar product d2 := v * v; //interpolate as quadratic curve and apply power function if d2 > 1 then h := 0 else h := power(1 - d2, FCurveExponent); p^ := MapHeightToBGRA(h, 255); Inc(p); end; end; //antialiased border mask := TBGRABitmap.Create(tx, ty, BGRABlack); Mask.FillEllipseAntialias(center.x, center.y, tx / 2, ty / 2, BGRAWhite); map.ApplyMask(mask); Mask.Free; FPhong.Draw(FKnobBmp, Map, 30, 0, 0, BGRAKnobColor); Map.Free; end else begin FKnobBmp.FillEllipseAntialias(center.x, center.y, tx / 2, ty / 2, BGRAKnobColor); end; end; function TBGRAKnob.GetLightIntensity: integer; begin Result := round(FPhong.LightSourceIntensity); end; function TBGRAKnob.GetValue: single; begin Result := FAngularPos * 180 / Pi; if Result < 0 then Result += 360; Result := 270 - Result; if Result < 0 then Result += 360; end; procedure TBGRAKnob.SetCurveExponent(const AValue: single); begin if FCurveExponent = AValue then exit; FCurveExponent := AValue; FreeAndNil(FKnobBmp); Invalidate; end; procedure TBGRAKnob.SetKnobColor(const AValue: TColor); begin if FKnobColor = AValue then exit; FKnobColor := AValue; FreeAndNil(FKnobBmp); Invalidate; end; procedure TBGRAKnob.SetLightIntensity(const AValue: integer); begin if AValue <> FPhong.LightSourceIntensity then begin FPhong.LightSourceIntensity := AValue; FreeAndNil(FKnobBmp); Invalidate; end; end; procedure TBGRAKnob.SetStartFromBottom(const AValue: boolean); begin if FStartFromBottom = AValue then exit; FStartFromBottom := AValue; Invalidate; end; procedure TBGRAKnob.SetValue(AValue: single); var NewAngularPos: single; begin ValueCorrection(AValue); NewAngularPos := 3 * Pi / 2 - AValue * Pi / 180; if NewAngularPos > Pi then NewAngularPos -= 2 * Pi; if NewAngularPos < -Pi then NewAngularPos += 2 * Pi; if NewAngularPos <> FAngularPos then begin FAngularPos := NewAngularPos; Invalidate; end; end; procedure TBGRAKnob.SetMaxValue(AValue: single); begin if AValue < 0 then AValue := 0; if AValue > 360 then AValue := 360; if FMaxValue = AValue then exit; FMaxValue := AValue; if FMinValue > FMaxValue then FMinValue := FMaxValue; if ValueCorrection then Invalidate; end; procedure TBGRAKnob.SetMinValue(AValue: single); begin if AValue < 0 then AValue := 0; if AValue > 360 then AValue := 360; if FMinValue = AValue then exit; FMinValue := AValue; if FMaxValue < FMinValue then FMaxValue := FMinValue; if ValueCorrection then Invalidate; end; procedure TBGRAKnob.SetPositionColor(const AValue: TColor); begin if FPositionColor = AValue then exit; FPositionColor := AValue; Invalidate; end; procedure TBGRAKnob.SetPositionMargin(AValue: single); begin if FPositionMargin = AValue then exit; FPositionMargin := AValue; Invalidate; end; procedure TBGRAKnob.SetPositionOpacity(const AValue: byte); begin if FPositionOpacity = AValue then exit; FPositionOpacity := AValue; Invalidate; end; procedure TBGRAKnob.SetPositionType(const AValue: TBGRAKnobPositionType); begin if FPositionType = AValue then exit; FPositionType := AValue; Invalidate; end; procedure TBGRAKnob.SetPositionWidth(const AValue: single); begin if FPositionWidth = AValue then exit; FPositionWidth := AValue; Invalidate; end; procedure TBGRAKnob.SetUsePhongLighting(const AValue: boolean); begin if FUsePhongLighting = AValue then exit; FUsePhongLighting := AValue; FreeAndNil(FKnobBmp); Invalidate; end; procedure TBGRAKnob.UpdateAngularPos(X, Y: integer); var FPreviousPos, Sign: single; begin FPreviousPos := FAngularPos; if FStartFromBottom then Sign := 1 else Sign := -1; FAngularPos := ArcTan2((-Sign) * (Y - ClientHeight / 2) / ClientHeight, Sign * (X - ClientWidth / 2) / ClientWidth); ValueCorrection; Invalidate; if (FPreviousPos <> FAngularPos) and Assigned(FOnKnobValueChange) then FOnKnobValueChange(Self, Value); end; procedure TBGRAKnob.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited MouseDown(Button, Shift, X, Y); if Button = mbLeft then begin FSettingAngularPos := True; UpdateAngularPos(X, Y); end; end; procedure TBGRAKnob.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited MouseUp(Button, Shift, X, Y); if Button = mbLeft then FSettingAngularPos := False; end; procedure TBGRAKnob.MouseMove(Shift: TShiftState; X, Y: integer); begin inherited MouseMove(Shift, X, Y); if FSettingAngularPos then UpdateAngularPos(X, Y); end; procedure TBGRAKnob.Paint; var Bmp: TBGRABitmap; Center, Pos: TPointF; PosColor: TBGRAPixel; PosLen: single; begin if (ClientWidth = 0) or (ClientHeight = 0) then exit; if FKnobBmp = nil then begin CreateKnobBmp; if FKnobBmp = nil then Exit; end; Bmp := TBGRABitmap.Create(ClientWidth, ClientHeight); Bmp.BlendImage(0, 0, FKnobBmp, boLinearBlend); //draw current position PosColor := ColorToBGRA(ColorToRGB(FPositionColor), FPositionOpacity); Center := PointF(ClientWidth / 2, ClientHeight / 2); Pos.X := Cos(FAngularPos) * (ClientWidth / 2); Pos.Y := -Sin(FAngularPos) * (ClientHeight / 2); if not FStartFromBottom then Pos := -Pos; PosLen := sqrt(Pos * Pos); Pos := Pos * ((PosLen - PositionMargin - FPositionWidth) / PosLen); Pos := Center + Pos; case PositionType of kptLineSquareCap: begin Bmp.LineCap := pecSquare; Bmp.DrawLineAntialias(Center.X, Center.Y, Pos.X, Pos.Y, PosColor, FPositionWidth); end; kptLineRoundCap: begin Bmp.LineCap := pecRound; Bmp.DrawLineAntialias(Center.X, Center.Y, Pos.X, Pos.Y, PosColor, FPositionWidth); end; kptFilledCircle: begin Bmp.FillEllipseAntialias(Pos.X, Pos.Y, FPositionWidth, FPositionWidth, PosColor); end; kptHollowCircle: begin Bmp.EllipseAntialias(Pos.X, Pos.Y, FPositionWidth * 2 / 3, FPositionWidth * 2 / 3, PosColor, FPositionWidth / 3); end; end; Bmp.Draw(Canvas, 0, 0, False); Bmp.Free; end; procedure TBGRAKnob.Resize; begin inherited Resize; if (FKnobBmp <> nil) and ((ClientWidth <> FKnobBmp.Width) or (ClientHeight <> FKnobBmp.Height)) then FreeAndNil(FKnobBmp); end; function TBGRAKnob.ValueCorrection(var AValue: single): boolean; begin if AValue < MinValue then begin AValue := MinValue; Result := True; end else if AValue > MaxValue then begin AValue := MaxValue; Result := True; end else Result := False; end; function TBGRAKnob.ValueCorrection: boolean; var LValue: single; begin LValue := Value; Result := ValueCorrection(LValue); if Result then Value := LValue; end; constructor TBGRAKnob.Create(AOwner: TComponent); begin inherited Create(AOwner); with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); FPhong := TPhongShading.Create; FPhong.LightPositionZ := 100; FPhong.LightSourceIntensity := 300; FPhong.NegativeDiffusionFactor := 0.8; FPhong.AmbientFactor := 0.5; FPhong.DiffusionFactor := 0.6; FKnobBmp := nil; FCurveExponent := 0.2; FKnobColor := clBtnFace; FPositionColor := clBtnText; FPositionOpacity := 192; FPositionWidth := 4; FPositionMargin := 4; FPositionType := kptLineSquareCap; FUsePhongLighting := True; FOnKnobValueChange := nil; FStartFromBottom := True; FMinValue := 30; FMaxValue := 330; end; destructor TBGRAKnob.Destroy; begin FPhong.Free; FKnobBmp.Free; inherited Destroy; end; procedure TBGRAKnob.SaveToFile(AFileName: string); var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try WriteComponentAsTextToStream(AStream, Self); AStream.SaveToFile(AFileName); finally AStream.Free; end; end; procedure TBGRAKnob.LoadFromFile(AFileName: string); var AStream: TMemoryStream; begin AStream := TMemoryStream.Create; try AStream.LoadFromFile(AFileName); ReadComponentFromTextStream(AStream, TComponent(Self), @OnFindClass); finally AStream.Free; end; end; procedure TBGRAKnob.OnFindClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); begin if CompareText(AClassName, 'TBGRAKnob') = 0 then ComponentClass := TBGRAKnob; end; end.
unit TelaCadastraConsulta_p; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FMTBcd, StdCtrls, Mask, DBCtrls, Buttons, ExtCtrls, DB, SqlExpr, Provider, DBClient, JvExButtons, JvBitBtn; type TTelaCadastraConsulta = class(TForm) dsAgenda: TDataSource; cdsAgenda: TClientDataSet; cdsAgendaCDAGENDA_VETERINARIA: TIntegerField; cdsAgendaCDVETERINARIO: TIntegerField; cdsAgendaDATA: TDateField; cdsAgendaHORA: TTimeField; cdsAgendaCDPROCEDIMENTO: TIntegerField; cdsAgendaCDMASCOTE: TIntegerField; cdsAgendaVETERINARIO: TStringField; cdsAgendaPROCEDIMENTO: TStringField; cdsAgendaPACIENTE: TStringField; cdsAgendaCLIENTE: TStringField; cdsAgendaOBSERVACOES: TStringField; dspAgenda: TDataSetProvider; qAgenda: TSQLQuery; qAgendaCDAGENDA_VETERINARIA: TIntegerField; qAgendaCDVETERINARIO: TIntegerField; qAgendaDATA: TDateField; qAgendaHORA: TTimeField; qAgendaCDPROCEDIMENTO: TIntegerField; qAgendaCDMASCOTE: TIntegerField; qAgendaVETERINARIO: TStringField; qAgendaPROCEDIMENTO: TStringField; qAgendaPACIENTE: TStringField; qAgendaCLIENTE: TStringField; qAgendaOBSERVACOES: TStringField; qVet: TSQLQuery; dspVet: TDataSetProvider; cdsVet: TClientDataSet; cdsVetCDVETERINARIO: TIntegerField; cdsVetNOME: TStringField; cdsVetCRMV: TStringField; dsVet: TDataSource; Label1: TLabel; DBEdit1: TDBEdit; Label3: TLabel; DBEdit3: TDBEdit; Label4: TLabel; DBEdit4: TDBEdit; Label7: TLabel; Label8: TLabel; Label11: TLabel; DBEdit11: TDBEdit; qProc: TSQLQuery; dspProc: TDataSetProvider; cdsProc: TClientDataSet; dsProc: TDataSource; cdsProcCDPROCEDIMENTO: TIntegerField; dblVeterinario: TDBLookupComboBox; Label2: TLabel; dblCliente: TDBLookupComboBox; qCliente: TSQLQuery; dspCliente: TDataSetProvider; cdsCliente: TClientDataSet; dsCliente: TDataSource; qMascote: TSQLQuery; dspMascote: TDataSetProvider; cdsMascote: TClientDataSet; dsMascote: TDataSource; cdsClienteCDCLIENTE: TIntegerField; cdsClienteNOME: TStringField; cdsClienteAPELIDO: TStringField; cdsMascoteCDMASCOTE: TIntegerField; cdsMascoteCDRACA: TIntegerField; cdsMascoteCDTIPO: TIntegerField; cdsMascoteCDCLIENTE: TIntegerField; cdsMascoteNOME: TStringField; cdsMascoteCOR: TStringField; cdsMascoteNASCIMENTO: TDateField; cdsMascoteOBS: TBlobField; cdsMascoteDATA_CADASTRO: TDateField; dblMascote: TDBLookupComboBox; Label5: TLabel; dblProcedimento: TDBLookupComboBox; pnlBotoes: TPanel; BitBtnIncluir: TBitBtn; BitBtnExcluir: TBitBtn; BitBtnCancelar: TBitBtn; BitBtnAlterar: TBitBtn; BitBtnGravar: TBitBtn; BitBtnSair: TBitBtn; BitBtnRelatorios: TJvBitBtn; cdsProcDESCRICAO: TStringField; procedure BitBtnSairClick(Sender: TObject); procedure BitBtnIncluirClick(Sender: TObject); procedure BitBtnExcluirClick(Sender: TObject); procedure BitBtnGravarClick(Sender: TObject); procedure BitBtnAlterarClick(Sender: TObject); procedure CancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var TelaCadastraConsulta: TTelaCadastraConsulta; implementation uses DMPrincipal_p, Principal_p, Funcoes_p; {$R *.dfm} procedure TTelaCadastraConsulta.BitBtnAlterarClick(Sender: TObject); begin InsertState(TelaCadastraConsulta); cdsAgenda.Edit; end; procedure TTelaCadastraConsulta.BitBtnExcluirClick(Sender: TObject); begin BrowseState(TelaCadastraConsulta); if cdsAgenda.IsEmpty then begin Application.MessageBox('Não Existem Registros para Exclusão', 'Aviso.',MB_OK ); end else begin if Application.MessageBox('Deseja Realmente Excluir este Registro ?','Confirmar Exclusão.',MB_YESNO) = mrYes then begin cdsAgenda.Delete; cdsAgenda.ApplyUpdates(0); end; end; end; procedure TTelaCadastraConsulta.BitBtnGravarClick(Sender: TObject); begin BrowseState(TelaCadastraConsulta); if cdsAgenda.State = dsInsert then begin cdsAgendaCDAGENDA_VETERINARIA.AsInteger := Gerar_id('GEN_AGENDA_VETERINARIA_ID'); end; cdsAgenda.Post; cdsAgenda.ApplyUpdates(0); end; procedure TTelaCadastraConsulta.BitBtnIncluirClick(Sender: TObject); begin InsertState(TelaCadastraConsulta); cdsAgenda.Insert; dblCliente.SetFocus; end; procedure TTelaCadastraConsulta.BitBtnSairClick(Sender: TObject); begin Close; end; procedure TTelaCadastraConsulta.CancelarClick(Sender: TObject); begin BrowseState(TelaCadastraConsulta); cdsAgenda.Cancel; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFE_FORMA_PAGAMENTO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfeFormaPagamentoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, NfceTipoPagamentoVO; type [TEntity] [TTable('NFE_FORMA_PAGAMENTO')] TNfeFormaPagamentoVO = class(TVO) private FID: Integer; FID_NFE_CABECALHO: Integer; FID_NFCE_TIPO_PAGAMENTO: Integer; FFORMA: String; FVALOR: Extended; FCNPJ_OPERADORA_CARTAO: String; FBANDEIRA: String; FNUMERO_AUTORIZACAO: String; FESTORNO: String; FNfceTipoPagamentoVO: TNfceTipoPagamentoVO; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_NFE_CABECALHO', 'Id Nfe Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfeCabecalho: Integer read FID_NFE_CABECALHO write FID_NFE_CABECALHO; [TColumn('ID_NFCE_TIPO_PAGAMENTO', 'Id Tipo Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfceTipoPagamento: Integer read FID_NFCE_TIPO_PAGAMENTO write FID_NFCE_TIPO_PAGAMENTO; [TColumn('FORMA', 'Forma', 16, [ldGrid, ldLookup, ldCombobox], False)] property Forma: String read FFORMA write FFORMA; [TColumn('VALOR', 'Valor', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Valor: Extended read FVALOR write FVALOR; [TColumn('CNPJ_OPERADORA_CARTAO', 'Cnpj Operadora Cartao', 112, [ldGrid, ldLookup, ldCombobox], False)] property CnpjOperadoraCartao: String read FCNPJ_OPERADORA_CARTAO write FCNPJ_OPERADORA_CARTAO; [TColumn('BANDEIRA', 'Bandeira', 16, [ldGrid, ldLookup, ldCombobox], False)] property Bandeira: String read FBANDEIRA write FBANDEIRA; [TColumn('NUMERO_AUTORIZACAO', 'Numero Autorizacao', 160, [ldGrid, ldLookup, ldCombobox], False)] property NumeroAutorizacao: String read FNUMERO_AUTORIZACAO write FNUMERO_AUTORIZACAO; [TColumn('ESTORNO', 'Estorno', 8, [ldGrid, ldLookup, ldCombobox], False)] property Estorno: String read FESTORNO write FESTORNO; [TAssociation('ID', 'ID_NFCE_TIPO_PAGAMENTO')] property NfceTipoPagamentoVO: TNfceTipoPagamentoVO read FNfceTipoPagamentoVO write FNfceTipoPagamentoVO; end; implementation constructor TNfeFormaPagamentoVO.Create; begin inherited; FNfceTipoPagamentoVO := TNfceTipoPagamentoVO.Create; end; destructor TNfeFormaPagamentoVO.Destroy; begin FreeAndNil(FNfceTipoPagamentoVO); inherited; end; initialization Classes.RegisterClass(TNfeFormaPagamentoVO); finalization Classes.UnRegisterClass(TNfeFormaPagamentoVO); end.
procedure OutputInteger(N:integer); var neg: integer; begin if n<0 then neg:=-1 else neg:=1; n:=abs(n); if n<10 then begin if neg=-1 then write('-'); write(chr(n+ord('0'))) end else begin OutputInteger(neg*(n div 10)); OutputInteger(n mod 10) end; end;
{ Renames a CK-defined property. This alters Papyrus data on an object, which is an entirely different thing from altering the Papyrus script itself. Created by DavidJCobb. } Unit CobbSingleRenamePapyrusProperty; Uses 'Skyrim - Papyrus Resource Library'; Uses 'CobbTES5EditUtil'; var rePropRegex: TPerlRegEx; sScriptTarget: String; sPropertyOldName: String; sPropertyNewName: String; Function Initialize: integer; Var slResult: TStringList; Begin rePropRegex := TPerlRegEx.Create; rePropRegex.Options := [preCaseLess, preMultiLine, preSingleLine]; rePropRegex.RegEx := '^[\w\[\]]+\sProperty\s(\w+)(.*?)$'; rePropRegex.Study; slResult := PromptFor3Strings('Options', 'Modify property on what script? (Leave blank to modify properties on all found scripts; be careful when doing that!)', 'What CK-defined property do you want to rename?', 'What name should we give the property?'); If slResult.Count = 0 Then Begin Result := 1; Exit; End Else Begin sScriptTarget := slResult[0]; sPropertyOldName := slResult[1]; sPropertyNewName := slResult[2]; End; End; Function Process(aeForm: IInterface) : Integer; Var eVMAD: IInterface; eScripts: IInterface; iCurrentScript: Integer; eCurrentScript: IInterface; Begin If ElementType(aeForm) = etMainRecord Then eVMAD := ElementBySignature(aeForm, 'VMAD'); If Assigned(eVMAD) Then Begin If sScriptTarget <> '' Then Begin RenamePropertyOnScript(GetScript(aeForm, sScriptTarget) , sPropertyOldName, sPropertyNewName); End Else Begin // // Manually loop through all scripts. // eScripts := ElementByPath(eVMAD, 'Data\Scripts'); If Signature(aeForm) = 'QUST' Then eScripts := ElementByPath(eVMAD, 'Data\Quest VMAD\Scripts'); For iCurrentScript := 0 To ElementCount(eScripts) - 1 Do Begin eCurrentScript := ElementByIndex(eScripts, iCurrentScript); RenamePropertyOnScript(eCurrentScript, sPropertyOldName, sPropertyNewName); End; End; End; End; End.
unit DibFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DibWnd, uDrawBorder, DibImage; type TTDibFrame = class(TFrame) procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } UIList : UIImageList; DDList : DibDataList; DIList : DibImageList; procedure Clear(); // procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMOnPaint(var Message: TWMPaint); message WM_PAINT; public { Public declarations } procedure SetBorderImage(pImageList : PUIImageList); end; implementation {$R *.dfm} procedure TTDibFrame.Clear; begin if (DIList.Top <> nil) then DIList.Top.Destroy; if (DIList.LeftTop <> nil) then DIList.LeftTop.Destroy; if (DIList.RightTop <> nil) then DIList.RightTop.Destroy; if (DIList.Left <> nil) then DIList.Left.Destroy; if (DIList.Right <> nil) then DIList.Right.Destroy; if (DIList.LeftBottom <> nil) then DIList.LeftBottom.Destroy; if (DIList.Bottom <> nil) then DIList.Bottom.Destroy; if (DIList.RightBottom <> nil) then DIList.RightBottom.Destroy; ZeroMemory(@DDList, sizeof(DDList)); end; procedure TTDibFrame.FormDestroy(Sender: TObject); begin Clear(); end; procedure FillSolidRect(DC : HDC; lpRect : PRECT; clr : COLORREF ); begin Windows.SetBkColor(DC, clr); Windows.ExtTextOut(DC, 0, 0, ETO_OPAQUE, lpRect, nil, 0, nil); end; procedure TTDibFrame.FormPaint(Sender: TObject); var dstRect: TRect; DC : HDC; begin DstRect := Self.GetClientRect; DC := Windows.GetDC(Self.Handle); DrawImageListToWnd(DC, @dstRect, @DDList); dstRect.Left := DDList.Left.lpbi.bmiHeader.biWidth; dstRect.Top := DDList.Top.lpbi.bmiHeader.biHeight; dstRect.Right := dstRect.Right - DDList.Right.lpbi.bmiHeader.biWidth; dstRect.Bottom := dstRect.Bottom - DDList.Bottom.lpbi.bmiHeader.biHeight; // Canvas.FillRect(dstRect); dstRect.Right := 200; dstRect.Bottom := 200; FillSolidRect(DC, @dstRect, RGB(255, 0, 0)); Windows.ReleaseDC(Self.Handle, DC); end; procedure TTDibFrame.FormResize(Sender: TObject); begin Invalidate(); end; procedure TTDibFrame.SetBorderImage(pImageList: PUIImageList); begin UIList := pImageList^; Clear(); DIList.LeftTop := TDibImage.Create(); DIList.Top := TDibImage.Create(); DIList.RightTop := TDibImage.Create(); DIList.Left := TDibImage.Create(); DIList.Right := TDibImage.Create(); DIList.LeftBottom := TDibImage.Create(); DIList.Bottom := TDibImage.Create(); DIList.RightBottom := TDibImage.Create(); DIList.LeftTop .Load (PWideChar(UIList.LeftTop )); DIList.Top .Load (PWideChar(UIList.Top )); DIList.RightTop .Load (PWideChar(UIList.RightTop )); DIList.Left .Load (PWideChar(UIList.Left )); DIList.Right .Load (PWideChar(UIList.Right )); DIList.LeftBottom .Load (PWideChar(UIList.LeftBottom )); DIList.Bottom .Load (PWideChar(UIList.Bottom )); DIList.RightBottom .Load (PWideChar(UIList.RightBottom )); DDList.LeftTop.lpbi := DIList.LeftTop .GetBitmapInfo(); DDList.Top.lpbi := DIList.Top .GetBitmapInfo(); DDList.RightTop.lpbi := DIList.RightTop .GetBitmapInfo(); DDList.Left.lpbi := DIList.Left .GetBitmapInfo(); DDList.Right.lpbi := DIList.Right .GetBitmapInfo(); DDList.LeftBottom.lpbi := DIList.LeftBottom .GetBitmapInfo(); DDList.Bottom.lpbi := DIList.Bottom .GetBitmapInfo(); DDList.RightBottom.lpbi := DIList.RightBottom .GetBitmapInfo(); DDList.LeftTop.lpBits := DIList.LeftTop .GetBits( ); DDList.Top.lpBits := DIList.Top .GetBits( ); DDList.RightTop.lpBits := DIList.RightTop .GetBits( ); DDList.Left.lpBits := DIList.Left .GetBits( ); DDList.Right.lpBits := DIList.Right .GetBits( ); DDList.LeftBottom.lpBits := DIList.LeftBottom .GetBits( ); DDList.Bottom.lpBits := DIList.Bottom .GetBits( ); DDList.RightBottom.lpBits := DIList.RightBottom .GetBits( ); Invalidate(); end; procedure TTDibFrame.WMOnPaint(var Message: TWMPaint); var dstRect: TRect; DC: HDC; PS: TPaintStruct; begin DstRect := Self.GetClientRect; DC := BeginPaint(Handle, PS); DrawImageListToWnd(DC, @dstRect, @DDList); dstRect.Left := DDList.Left.lpbi.bmiHeader.biWidth; dstRect.Top := DDList.Top.lpbi.bmiHeader.biHeight; dstRect.Right := dstRect.Right - DDList.Right.lpbi.bmiHeader.biWidth; dstRect.Bottom := dstRect.Bottom - DDList.Bottom.lpbi.bmiHeader.biHeight; // Canvas.FillRect(dstRect); FillSolidRect(DC, @dstRect, RGB(255, 255, 255)); EndPaint(Handle, PS); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Math; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$ifdef Delphi2009AndUp} {$warn DUPLICATE_CTOR_DTOR off} {$endif} {$undef UseDouble} {$ifdef UseDouble} {$define NonSIMD} {$endif} {-$define NonSIMD} {$ifdef NonSIMD} {$undef SIMD} {$else} {$ifdef cpu386} {$if not (defined(Darwin) or defined(CompileForWithPIC))} {$define SIMD} {$ifend} {$endif} {$ifdef cpux64} {$define SIMD} {$endif} {$endif} {$warnings off} interface uses SysUtils, Classes, Math, PasVulkan.Types, Vulkan; const EPSILON={$ifdef UseDouble}1e-14{$else}1e-5{$endif}; // actually {$ifdef UseDouble}1e-16{$else}1e-7{$endif}; but we are conservative here SPHEREEPSILON=EPSILON; AABBEPSILON=EPSILON; MAX_SCALAR={$ifdef UseDouble}1.7e+308{$else}3.4e+28{$endif}; DEG2RAD=PI/180.0; RAD2DEG=180.0/PI; OnePI=PI; HalfPI=PI*0.5; TwoPI=PI*2.0; OneOverPI=1.0/PI; OneOverHalfPI=1.0/HalfPI; OneOverTwoPI=1.0/TwoPI; SQRT_0_DOT_5=0.70710678118; SupraEngineFPUPrecisionMode:TFPUPrecisionMode={$ifdef cpu386}pmExtended{$else}{$ifdef cpux64}pmExtended{$else}pmDouble{$endif}{$endif}; SupraEngineFPUExceptionMask:TFPUExceptionMask=[exInvalidOp,exDenormalized,exZeroDivide,exOverflow,exUnderflow,exPrecision]; type PpvScalar=^TpvScalar; TpvScalar={$ifdef UseDouble}TpvDouble{$else}TpvFloat{$endif}; PpvClipRect=^TpvClipRect; TpvClipRect=array[0..3] of TpvInt32; PpvFloatClipRect=^TpvFloatClipRect; TpvFloatClipRect=array[0..3] of TpvFloat; PPpvIntPoint=^PpvIntPoint; PpvIntPoint=^TpvIntPoint; TpvIntPoint=record public x,y:TpvInt32; end; PpvVector2=^TpvVector2; TpvVector2=record public constructor Create(const aX:TpvScalar); overload; constructor Create(const aX,aY:TpvScalar); overload; class function InlineableCreate(const aX:TpvScalar):TpvVector2; overload; inline; static; class function InlineableCreate(const aX,aY:TpvScalar):TpvVector2; overload; inline; static; class operator Implicit(const aScalar:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const aScalar:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const aLeft,aRight:TpvVector2):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const aLeft,aRight:TpvVector2):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc(const aValue:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Dec(const aValue:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvVector2): TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvVector2;const b:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative(const aValue:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Positive(const aValue:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} private {$i PasVulkan.Math.TpvVector2.Swizzle.Definitions.inc} private function GetComponent(const aIndex:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} public function Perpendicular:TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function Length:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function SquaredLength:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Normalize:TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const aToVector:TpvVector2):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Dot(const aWithVector:TpvVector2):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Cross(const aVector:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function Lerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; function Sqlerp(const aB,aC,aD:TpvVector2;const aTime:TpvScalar):TpvVector2; function Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector2):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Rotate(const aAngle:TpvScalar):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Rotate(const aCenter:TpvVector2;const aAngle:TpvScalar):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} property Components[const aIndex:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; case TpvUInt8 of 0:(RawComponents:array[0..1] of TpvScalar); 1:(x,y:TpvScalar); 2:(u,v:TpvScalar); 3:(s,t:TpvScalar); 4:(r,g:TpvScalar); end; PpvVector3=^TpvVector3; TpvVector3=record public constructor Create(const aX:TpvScalar); overload; constructor Create(const aX,aY,aZ:TpvScalar); overload; constructor Create(const aXY:TpvVector2;const aZ:TpvScalar=0.0); overload; class function InlineableCreate(const aX:TpvScalar):TpvVector3; overload; inline; static; class function InlineableCreate(const aX,aY,aZ:TpvScalar):TpvVector3; overload; inline; static; class function InlineableCreate(const aXY:TpvVector2;const aZ:TpvScalar=0.0):TpvVector3; overload; inline; static; class operator Implicit(const a:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvVector3):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvVector3):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator IntDivide(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvVector3;const b:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Positive(const a:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} private {$i PasVulkan.Math.TpvVector3.Swizzle.Definitions.inc} private function GetComponent(const aIndex:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} public function Flip:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Perpendicular:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function OneUnitOrthogonalVector:TpvVector3; function Length:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function SquaredLength:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Normalize:TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function DistanceTo({$ifdef fpc}constref{$else}const{$endif} aToVector:TpvVector3):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Abs:TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Dot({$ifdef fpc}constref{$else}const{$endif} aWithVector:TpvVector3):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function AngleTo(const aToVector:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Cross({$ifdef fpc}constref{$else}const{$endif} aOtherVector:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Lerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; function Sqlerp(const aB,aC,aD:TpvVector3;const aTime:TpvScalar):TpvVector3; function Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function RotateX(const aAngle:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function RotateY(const aAngle:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function RotateZ(const aAngle:TpvScalar):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function ProjectToBounds(const aMinVector,aMaxVector:TpvVector3):TpvScalar; property Components[const aIndex:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; case TpvUInt8 of 0:(RawComponents:array[0..2] of TpvScalar); 1:(x,y,z:TpvScalar); 2:(r,g,b:TpvScalar); 3:(s,t,p:TpvScalar); 4:(Pitch,Yaw,Roll:TpvScalar); 6:(Vector2:TpvVector2); end; PpvVector4=^TpvVector4; TpvVector4=record public constructor Create(const aX:TpvScalar); overload; constructor Create(const aX,aY,aZ,aW:TpvScalar); overload; constructor Create(const aXY:TpvVector2;const aZ:TpvScalar=0.0;const aW:TpvScalar=1.0); overload; constructor Create(const aXYZ:TpvVector3;const aW:TpvScalar=1.0); overload; class function InlineableCreate(const aX:TpvScalar):TpvVector4; overload; inline; static; class function InlineableCreate(const aX,aY,aZ,aW:TpvScalar):TpvVector4; overload; inline; static; class function InlineableCreate(const aXY:TpvVector2;const aZ:TpvScalar=0.0;const aW:TpvScalar=0.0):TpvVector4; overload; inline; static; class function InlineableCreate(const aXYZ:TpvVector3;const aW:TpvScalar=0.0):TpvVector4; overload; inline; static; class operator Implicit(const a:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvVector4):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvVector4):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvVector4): TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator IntDivide(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvVector4;const b:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Positive(const a:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} private {$i PasVulkan.Math.TpvVector4.Swizzle.Definitions.inc} private function GetComponent(const aIndex:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} public function Flip:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Perpendicular:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Length:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function SquaredLength:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Normalize:TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function DistanceTo({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Abs:TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Dot({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function AngleTo(const b:TpvVector4):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Cross({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Lerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; function Sqlerp(const aB,aC,aD:TpvVector4;const aTime:TpvScalar):TpvVector4; function Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector4):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function RotateX(const aAngle:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function RotateY(const aAngle:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function RotateZ(const aAngle:TpvScalar):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Rotate(const aAngle:TpvScalar;const aAxis:TpvVector3):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function ProjectToBounds(const aMinVector,aMaxVector:TpvVector4):TpvScalar; public property Components[const aIndex:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; case TpvUInt8 of 0:(RawComponents:array[0..3] of TpvScalar); 1:(x,y,z,w:TpvScalar); 2:(r,g,b,a:TpvScalar); 3:(s,t,p,q:TpvScalar); 5:(Vector2:TpvVector2); 6:(Vector3:TpvVector3); end; TpvVector2Helper=record helper for TpvVector2 public const Null:TpvVector2=(x:0.0;y:0.0); Origin:TpvVector2=(x:0.0;y:0.0); XAxis:TpvVector2=(x:1.0;y:0.0); YAxis:TpvVector2=(x:0.0;y:1.0); AllAxis:TpvVector2=(x:1.0;y:1.0); public {$i PasVulkan.Math.TpvVector2Helper.Swizzle.Definitions.inc} end; TpvVector3Helper=record helper for TpvVector3 public const Null:TpvVector3=(x:0.0;y:0.0;z:0.0); Origin:TpvVector3=(x:0.0;y:0.0;z:0.0); XAxis:TpvVector3=(x:1.0;y:0.0;z:0.0); YAxis:TpvVector3=(x:0.0;y:1.0;z:0.0); ZAxis:TpvVector3=(x:0.0;y:0.0;z:1.0); AllAxis:TpvVector3=(x:1.0;y:1.0;z:1.0); public {$i PasVulkan.Math.TpvVector3Helper.Swizzle.Definitions.inc} end; TpvVector4Helper=record helper for TpvVector4 public const Null:TpvVector4=(x:0.0;y:0.0;z:0.0;w:0.0); Origin:TpvVector4=(x:0.0;y:0.0;z:0.0;w:0.0); XAxis:TpvVector4=(x:1.0;y:0.0;z:0.0;w:0.0); YAxis:TpvVector4=(x:0.0;y:1.0;z:0.0;w:0.0); ZAxis:TpvVector4=(x:0.0;y:0.0;z:1.0;w:0.0); WAxis:TpvVector4=(x:0.0;y:0.0;z:0.0;w:1.0); AllAxis:TpvVector4=(x:1.0;y:1.0;z:1.0;w:1.0); public {$i PasVulkan.Math.TpvVector4Helper.Swizzle.Definitions.inc} end; PpvHalfFloatVector2=^TpvHalfFloatVector2; TpvHalfFloatVector2=record public case TpvUInt8 of 0:(RawComponents:array[0..1] of TpvHalfFloat); 1:(x,y:TpvHalfFloat); 2:(r,g:TpvHalfFloat); 3:(s,t:TpvHalfFloat); end; PpvHalfFloatVector3=^TpvHalfFloatVector3; TpvHalfFloatVector3=record public case TpvUInt8 of 0:(RawComponents:array[0..2] of TpvHalfFloat); 1:(x,y,z:TpvHalfFloat); 2:(r,g,b:TpvHalfFloat); 3:(s,t,p:TpvHalfFloat); 5:(Vector2:TpvHalfFloatVector2); end; PpvHalfFloatVector4=^TpvHalfFloatVector4; TpvHalfFloatVector4=record public case TpvUInt8 of 0:(RawComponents:array[0..3] of TpvHalfFloat); 1:(x,y,z,w:TpvHalfFloat); 2:(r,g,b,a:TpvHalfFloat); 3:(s,t,p,q:TpvHalfFloat); 5:(Vector2:TpvHalfFloatVector2); 6:(Vector3:TpvHalfFloatVector3); end; PpvPackedTangentSpace=^TpvPackedTangentSpace; TpvPackedTangentSpace=record x,y,z,w:TpvUInt8; end; PpvNormalizedSphericalCoordinates=^TpvNormalizedSphericalCoordinates; TpvNormalizedSphericalCoordinates=record Longitude:TpvScalar; Latitude:TpvScalar; end; TpvVector2Array=array of TpvVector2; TpvVector3Array=array of TpvVector3; TpvVector4Array=array of TpvVector4; PpvVector3s=^TpvVector3s; TpvVector3s=array[0..$ff] of TpvVector3; PPpvVector3s=^TPpvVector3s; TPpvVector3s=array[0..$ff] of PpvVector3; PpvVector4s=^TpvVector4s; TpvVector4s=array[0..$ff] of TpvVector4; PPpvVector4s=^TPpvVector4s; TPpvVector4s=array[0..$ff] of PpvVector4; PpvPlane=^TpvPlane; TpvPlane=record public constructor Create(const aNormal:TpvVector3;const aDistance:TpvScalar); overload; constructor Create(const aX,aY,aZ,aDistance:TpvScalar); overload; constructor Create(const aA,aB,aC:TpvVector3); overload; constructor Create(const aA,aB,aC:TpvVector4); overload; constructor Create(const aVector:TpvVector4); overload; function ToVector:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} function Normalize:TpvPlane; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const aPoint:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const aPoint:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} procedure ClipSegment(const aP0,aP1:TpvVector3;out aClipped:TpvVector3); overload; function ClipSegmentClosest(const aP0,aP1:TpvVector3;out aClipped0,aClipped1:TpvVector3):TpvInt32; overload; function ClipSegmentLine(var aP0,aP1:TpvVector3):boolean; case TpvUInt8 of 0:( RawComponents:array[0..3] of TpvScalar; ); 1:( x,y,z,w:TpvScalar; ); 2:( Normal:TpvVector3; Distance:TpvScalar; ); end; PpvQuaternion=^TpvQuaternion; TpvQuaternion=record public constructor Create(const aX:TpvScalar); overload; constructor Create(const aX,aY,aZ,aW:TpvScalar); overload; constructor Create(const aVector:TpvVector4); overload; constructor CreateFromScaledAngleAxis(const aScaledAngleAxis:TpvVector3); constructor CreateFromAngularVelocity(const aAngularVelocity:TpvVector3); constructor CreateFromAngleAxis(const aAngle:TpvScalar;const aAxis:TpvVector3); constructor CreateFromEuler(const aPitch,aYaw,aRoll:TpvScalar); overload; constructor CreateFromEuler(const aAngles:TpvVector3); overload; constructor CreateFromNormalizedSphericalCoordinates(const aNormalizedSphericalCoordinates:TpvNormalizedSphericalCoordinates); constructor CreateFromToRotation(const aFromDirection,aToDirection:TpvVector3); constructor CreateFromCols(const aC0,aC1,aC2:TpvVector3); constructor CreateFromXY(const aX,aY:TpvVector3); class operator Implicit(const a:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvQuaternion):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvQuaternion):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvQuaternion): TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply(const a:TpvVector3;const b:TpvQuaternion):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply(const a:TpvVector4;const b:TpvQuaternion):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator IntDivide(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Positive(const a:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} private function GetComponent(const aIndex:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} public function ToNormalizedSphericalCoordinates:TpvNormalizedSphericalCoordinates; {$ifdef CAN_INLINE}inline;{$endif} function ToEuler:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function ToPitch:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ToYaw:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ToRoll:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ToAngularVelocity:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} procedure ToAngleAxis(out aAngle:TpvScalar;out aAxis:TpvVector3); {$ifdef CAN_INLINE}inline;{$endif} function ToScaledAngleAxis:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Generator:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Flip:TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Perpendicular:TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Conjugate:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Inverse:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Length:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function SquaredLength:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Normalize:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function DistanceTo({$ifdef fpc}constref{$else}const{$endif} b:TpvQuaternion):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Abs:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Exp:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Log:TpvQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Dot({$ifdef fpc}constref{$else}const{$endif} b:TpvQuaternion):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Lerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function ApproximatedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function Elerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function Sqlerp(const aB,aC,aD:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function UnflippedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function UnflippedApproximatedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function UnflippedSqlerp(const aB,aC,aD:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; function AngleBetween(const aP:TpvQuaternion):TpvScalar; function Between(const aP:TpvQuaternion):TpvQuaternion; class procedure Hermite(out aRotation:TpvQuaternion;out aVelocity:TpvVector3;const aTime:TpvScalar;const aR0,aR1:TpvQuaternion;const aV0,aV1:TpvVector3); static; class procedure CatmullRom(out aRotation:TpvQuaternion;out aVelocity:TpvVector3;const aTime:TpvScalar;const aR0,aR1,aR2,aR3:TpvQuaternion); static; function RotateAroundAxis(const aVector:TpvQuaternion):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Integrate(const aOmega:TpvVector3;const aDeltaTime:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Spin(const aOmega:TpvVector3;const aDeltaTime:TpvScalar):TpvQuaternion; {$ifdef CAN_INLINE}inline;{$endif} property Components[const aIndex:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; case TpvUInt8 of 0:(RawComponents:array[0..3] of TpvScalar); 1:(x,y,z,w:TpvScalar); 2:(Vector:TpvVector4); end; PpvMatrix2x2=^TpvMatrix2x2; TpvMatrix2x2=record public // constructor Create; overload; constructor Create(const pX:TpvScalar); overload; constructor Create(const pXX,pXY,pYX,pYY:TpvScalar); overload; constructor Create(const pX,pY:TpvVector2); overload; class operator Implicit(const a:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvMatrix2x2):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvMatrix2x2):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc(const a:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Dec(const a:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvMatrix2x2): TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix2x2;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvVector2;const b:TpvMatrix2x2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative(const a:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} class operator Positive(const a:TpvMatrix2x2):TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} private function GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} function GetColumn(const pIndex:TpvInt32):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} procedure SetColumn(const pIndex:TpvInt32;const pValue:TpvVector2); {$ifdef CAN_INLINE}inline;{$endif} function GetRow(const pIndex:TpvInt32):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} procedure SetRow(const pIndex:TpvInt32;const pValue:TpvVector2); {$ifdef CAN_INLINE}inline;{$endif} public function Determinant:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Inverse:TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} function Transpose:TpvMatrix2x2; {$ifdef CAN_INLINE}inline;{$endif} property Components[const pIndexA,pIndexB:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; property Columns[const pIndex:TpvInt32]:TpvVector2 read GetColumn write SetColumn; property Rows[const pIndex:TpvInt32]:TpvVector2 read GetRow write SetRow; case TpvInt32 of 0:(RawComponents:array[0..1,0..1] of TpvScalar); end; PpvDecomposedMatrix3x3=^TpvDecomposedMatrix3x3; TpvDecomposedMatrix3x3=record public Valid:boolean; Scale:TpvVector3; Skew:TpvVector3; // XY XZ YZ Rotation:TpvQuaternion; function Lerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Elerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Sqlerp(const aB,aC,aD:TpvDecomposedMatrix3x3;const aTime:TpvScalar):TpvDecomposedMatrix3x3; end; PpvMatrix3x3=^TpvMatrix3x3; TpvMatrix3x3=record public // constructor Create; overload; constructor Create(const pX:TpvScalar); overload; constructor Create(const pXX,pXY,pXZ,pYX,pYY,pYZ,pZX,pZY,pZZ:TpvScalar); overload; constructor Create(const pX,pY,pZ:TpvVector3); overload; constructor CreateRotateX(const Angle:TpvScalar); constructor CreateRotateY(const Angle:TpvScalar); constructor CreateRotateZ(const Angle:TpvScalar); constructor CreateRotate(const Angle:TpvScalar;const Axis:TpvVector3); constructor CreateSkewYX(const Angle:TpvScalar); constructor CreateSkewZX(const Angle:TpvScalar); constructor CreateSkewXY(const Angle:TpvScalar); constructor CreateSkewZY(const Angle:TpvScalar); constructor CreateSkewXZ(const Angle:TpvScalar); constructor CreateSkewYZ(const Angle:TpvScalar); constructor CreateScale(const sx,sy:TpvScalar); overload; constructor CreateScale(const sx,sy,sz:TpvScalar); overload; constructor CreateScale(const pScale:TpvVector2); overload; constructor CreateScale(const pScale:TpvVector3); overload; constructor CreateTranslation(const tx,ty:TpvScalar); overload; constructor CreateTranslation(const pTranslation:TpvVector2); overload; constructor CreateFromToRotation(const FromDirection,ToDirection:TpvVector3); constructor CreateConstruct(const pForwards,pUp:TpvVector3); constructor CreateConstructForwardUp(const aForward,aUp:TpvVector3); constructor CreateOuterProduct(const u,v:TpvVector3); constructor CreateFromQuaternion(ppvQuaternion:TpvQuaternion); constructor CreateFromQTangent(pQTangent:TpvQuaternion); constructor CreateRecomposed(const DecomposedMatrix3x3:TpvDecomposedMatrix3x3); class operator Implicit(const a:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvMatrix3x3):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvMatrix3x3):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc(const a:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Dec(const a:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Add(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Subtract(const a:TpvScalar;const b:TpvMatrix3x3): TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix3x3;const b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvVector2;const b:TpvMatrix3x3):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix3x3;const b:TpvVector3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvVector3;const b:TpvMatrix3x3):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix3x3;const b:TpvVector4):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvVector4;const b:TpvMatrix3x3):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvMatrix3x3;const b:TpvPlane):TpvPlane; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvPlane;const b:TpvMatrix3x3):TpvPlane; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative(const a:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} class operator Positive(const a:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} private function GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} function GetColumn(const pIndex:TpvInt32):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} procedure SetColumn(const pIndex:TpvInt32;const pValue:TpvVector3); {$ifdef CAN_INLINE}inline;{$endif} function GetRow(const pIndex:TpvInt32):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} procedure SetRow(const pIndex:TpvInt32;const pValue:TpvVector3); {$ifdef CAN_INLINE}inline;{$endif} public function Determinant:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Inverse:TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Transpose:TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function EulerAngles:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Normalize:TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function OrthoNormalize:TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function RobustOrthoNormalize(const Tolerance:TpvScalar=1e-3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function ToQuaternion:TpvQuaternion; function ToQTangent:TpvQuaternion; function SimpleLerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function SimpleNlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function SimpleSlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function SimpleElerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function SimpleSqlerp(const aB,aC,aD:TpvMatrix3x3;const aTime:TpvScalar):TpvMatrix3x3; function Lerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Elerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function Sqlerp(const aB,aC,aD:TpvMatrix3x3;const aTime:TpvScalar):TpvMatrix3x3; function MulInverse(const a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulInverse(const a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Decompose:TpvDecomposedMatrix3x3; property Components[const pIndexA,pIndexB:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; property Columns[const pIndex:TpvInt32]:TpvVector3 read GetColumn write SetColumn; property Rows[const pIndex:TpvInt32]:TpvVector3 read GetRow write SetRow; case TpvInt32 of 0:(RawComponents:array[0..2,0..2] of TpvScalar); 1:(m00,m01,m02,m10,m11,m12,m20,m21,m22:TpvScalar); 2:(Tangent,Bitangent,Normal:TpvVector3); 3:(Right,Up,Forwards:TpvVector3); end; PpvDecomposedMatrix4x4=^TpvDecomposedMatrix4x4; TpvDecomposedMatrix4x4=record public Valid:boolean; Perspective:TpvVector4; Translation:TpvVector3; Scale:TpvVector3; Skew:TpvVector3; // XY XZ YZ Rotation:TpvQuaternion; function Lerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Elerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Sqlerp(const aB,aC,aD:TpvDecomposedMatrix4x4;const aTime:TpvScalar):TpvDecomposedMatrix4x4; end; PpvMatrix4x4=^TpvMatrix4x4; TpvMatrix4x4=record public // constructor Create; overload; constructor Create(const pX:TpvScalar); overload; constructor Create(const pXX,pXY,pXZ,pXW,pYX,pYY,pYZ,pYW,pZX,pZY,pZZ,pZW,pWX,pWY,pWZ,pWW:TpvScalar); overload; constructor Create(const pX,pY,pZ:TpvVector3); overload; constructor Create(const pX,pY,pZ,pW:TpvVector3); overload; constructor Create(const pX,pY,pZ,pW:TpvVector4); overload; constructor Create(const pMatrix:TpvMatrix3x3); overload; constructor CreateRotateX(const Angle:TpvScalar); constructor CreateRotateY(const Angle:TpvScalar); constructor CreateRotateZ(const Angle:TpvScalar); constructor CreateRotate(const Angle:TpvScalar;const Axis:TpvVector3); constructor CreateRotation(const pMatrix:TpvMatrix4x4); overload; constructor CreateSkewYX(const Angle:TpvScalar); constructor CreateSkewZX(const Angle:TpvScalar); constructor CreateSkewXY(const Angle:TpvScalar); constructor CreateSkewZY(const Angle:TpvScalar); constructor CreateSkewXZ(const Angle:TpvScalar); constructor CreateSkewYZ(const Angle:TpvScalar); constructor CreateScale(const sx,sy:TpvScalar); overload; constructor CreateScale(const pScale:TpvVector2); overload; constructor CreateScale(const sx,sy,sz:TpvScalar); overload; constructor CreateScale(const pScale:TpvVector3); overload; constructor CreateScale(const sx,sy,sz,sw:TpvScalar); overload; constructor CreateScale(const pScale:TpvVector4); overload; constructor CreateTranslation(const tx,ty:TpvScalar); overload; constructor CreateTranslation(const pTranslation:TpvVector2); overload; constructor CreateTranslation(const tx,ty,tz:TpvScalar); overload; constructor CreateTranslation(const pTranslation:TpvVector3); overload; constructor CreateTranslation(const tx,ty,tz,tw:TpvScalar); overload; constructor CreateTranslation(const pTranslation:TpvVector4); overload; constructor CreateTranslated(const pMatrix:TpvMatrix4x4;pTranslation:TpvVector3); overload; constructor CreateTranslated(const pMatrix:TpvMatrix4x4;pTranslation:TpvVector4); overload; constructor CreateFromToRotation(const FromDirection,ToDirection:TpvVector3); constructor CreateConstruct(const pForwards,pUp:TpvVector3); constructor CreateOuterProduct(const u,v:TpvVector3); constructor CreateFromQuaternion(ppvQuaternion:TpvQuaternion); constructor CreateFromQTangent(pQTangent:TpvQuaternion); constructor CreateReflect(const PpvPlane:TpvPlane); constructor CreateFrustumLeftHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustumLeftHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustumLeftHandedOneToZero(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustumRightHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustumRightHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustumRightHandedOneToZero(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateFrustum(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoLeftHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoLeftHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoRightHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoRightHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrtho(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoLH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoRH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoOffCenterLH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreateOrthoOffCenterRH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); constructor CreatePerspectiveLeftHandedNegativeOneToPositiveOne(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveLeftHandedZeroToOne(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveLeftHandedOneToZero(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveRightHandedNegativeOneToPositiveOne(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveRightHandedZeroToOne(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveRightHandedOneToZero(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreatePerspectiveReversedZ(const aFOVY,aAspectRatio,aZNear:TpvScalar); constructor CreatePerspective(const fovy,Aspect,zNear,zFar:TpvScalar); constructor CreateLookAt(const Eye,Center,Up:TpvVector3); constructor CreateFill(const Eye,RightVector,UpVector,ForwardVector:TpvVector3); constructor CreateConstructX(const xAxis:TpvVector3); constructor CreateConstructY(const yAxis:TpvVector3); constructor CreateConstructZ(const zAxis:TpvVector3); constructor CreateProjectionMatrixClip(const ProjectionMatrix:TpvMatrix4x4;const ClipPlane:TpvPlane); constructor CreateRecomposed(const DecomposedMatrix4x4:TpvDecomposedMatrix4x4); class operator Implicit({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Explicit({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Equal({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Add({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4): TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector2):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector2;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvPlane):TpvPlane; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvPlane;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvPlane; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Modulus({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} class operator Positive(const a:TpvMatrix4x4):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} private function GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} procedure SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} function GetColumn(const pIndex:TpvInt32):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetColumn(const pIndex:TpvInt32;const pValue:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetRow(const pIndex:TpvInt32):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetRow(const pIndex:TpvInt32;const pValue:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} public function Determinant:TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function SimpleInverse:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Inverse:TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Transpose:TpvMatrix4x4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function EulerAngles:TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} function Normalize:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function OrthoNormalize:TpvMatrix4x4; //{$ifdef CAN_INLINE}inline;{$endif} function RobustOrthoNormalize(const Tolerance:TpvScalar=1e-3):TpvMatrix4x4; //{$ifdef CAN_INLINE}inline;{$endif} function ToQuaternion:TpvQuaternion; function ToQTangent:TpvQuaternion; function ToMatrix3x3:TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function ToRotation:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function SimpleLerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function SimpleNlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function SimpleSlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function SimpleElerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function SimpleSqlerp(const aB,aC,aD:TpvMatrix4x4;const aTime:TpvScalar):TpvMatrix4x4; function Lerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Nlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Slerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Elerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} function Sqlerp(const aB,aC,aD:TpvMatrix4x4;const aTime:TpvScalar):TpvMatrix4x4; function MulInverse({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulInverse({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulInverted({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulInverted({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulTransposedBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulTransposedBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulHomogen({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function MulHomogen({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Decompose:TpvDecomposedMatrix4x4; property Components[const pIndexA,pIndexB:TpvInt32]:TpvScalar read GetComponent write SetComponent; default; property Columns[const pIndex:TpvInt32]:TpvVector4 read GetColumn write SetColumn; property Rows[const pIndex:TpvInt32]:TpvVector4 read GetRow write SetRow; case TpvInt32 of 0:(RawComponents:array[0..3,0..3] of TpvScalar); 1:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33:TpvScalar); 2:(Tangent,Bitangent,Normal,Translation:TpvVector4); 3:(Right,Up,Forwards,Offset:TpvVector4); end; // Dual quaternion with uniform scaling support PpvDualQuaternion=^TpvDualQuaternion; TpvDualQuaternion=record public constructor Create(const pQ0,PQ1:TpvQuaternion); overload; constructor CreateFromRotationTranslationScale(const pRotation:TpvQuaternion;const pTranslation:TpvVector3;const pScale:TpvScalar); overload; constructor CreateFromMatrix(const pMatrix:TpvMatrix4x4); overload; class operator Implicit(const a:TpvMatrix4x4):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvMatrix4x4):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Implicit(const a:TpvDualQuaternion):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvDualQuaternion):TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvDualQuaternion):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvDualQuaternion):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Multiply(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Multiply(const a:TpvVector3;const b:TpvDualQuaternion):TpvVector3; {$ifdef CAN_INLINE}inline;{$endif} class operator Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Multiply(const a:TpvVector4;const b:TpvDualQuaternion):TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Divide(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Divide(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator IntDivide(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator IntDivide(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a,b:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Modulus(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} class operator Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion):TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} class operator Positive(const a:TpvDualQuaternion):TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Flip:TpvDualQuaternion; {$ifdef CAN_INLINE}inline;{$endif} function Conjugate:TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Inverse:TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} function Normalize:TpvDualQuaternion; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(fpc) and defined(cpuamd64) and not defined(Windows)}ms_abi_default;{$ifend} case TpvUInt8 of 0:(RawQuaternions:array[0..1] of TpvQuaternion); 1:(QuaternionR,QuaternionD:TpvQuaternion); end; TpvMatrix2x2Helper=record helper for TpvMatrix2x2 public const Null:TpvMatrix2x2=(RawComponents:((0.0,0.0),(0.0,0.0))); Identity:TpvMatrix2x2=(RawComponents:((1.0,0.0),(0.0,1.0))); end; TpvMatrix3x3Helper=record helper for TpvMatrix3x3 public const Null:TpvMatrix3x3=(RawComponents:((0.0,0.0,0.0),(0.0,0.0,0.0),(0.0,0.0,0.0))); Identity:TpvMatrix3x3=(RawComponents:((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))); end; TpvMatrix4x4Helper=record helper for TpvMatrix4x4 public const Null:TpvMatrix4x4=(RawComponents:((0.0,0.0,0,0.0),(0.0,0.0,0,0.0),(0.0,0.0,0,0.0),(0.0,0.0,0,0.0))); Identity:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,0.0,0,1.0))); RightToLeftHanded:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,0.0,0,1.0))); Flip:TpvMatrix4x4=(RawComponents:((0.0,0.0,-1.0,0.0),(-1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0,1.0))); InverseFlip:TpvMatrix4x4=(RawComponents:((0.0,-1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(-1.0,0.0,0,0.0),(0.0,0.0,0,1.0))); FlipYZ:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,0.0,1.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,0,1.0))); InverseFlipYZ:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,0.0,-1.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0,1.0))); NormalizedSpace:TpvMatrix4x4=(RawComponents:((2.0,0.0,0,0.0),(0.0,2.0,0.0,0.0),(0.0,0.0,2.0,0.0),(-1.0,-1.0,-1.0,1.0))); FlipYClipSpace:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,0.0,0.0,1.0))); HalfZClipSpace:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0.5,0.0),(0.0,0.0,0.5,1.0))); FlipYHalfZClipSpace:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,0.5,0.0),(0.0,0.0,0.5,1.0))); FlipZ:TpvMatrix4x4=(RawComponents:((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,0.0,0.0,1.0))); end; TpvQuaternionHelper=record helper for TpvQuaternion public const Identity:TpvQuaternion=(x:0.0;y:0.0;z:0.0;w:1.0); end; PpvSegment=^TpvSegment; TpvSegment=record public Points:array[0..1] of TpvVector3; constructor Create(const p0,p1:TpvVector3); function SquaredDistanceTo(const p:TpvVector3):TpvScalar; overload; function SquaredDistanceTo(const p:TpvVector3;out Nearest:TpvVector3):TpvScalar; overload; procedure ClosestPointTo(const p:TpvVector3;out Time:TpvScalar;out ClosestPoint:TpvVector3); function Transform(const Transform:TpvMatrix4x4):TpvSegment; {$ifdef CAN_INLINE}inline;{$endif} procedure ClosestPoints(const SegmentB:TpvSegment;out TimeA:TpvScalar;out ClosestPointA:TpvVector3;out TimeB:TpvScalar;out ClosestPointB:TpvVector3); function Intersect(const SegmentB:TpvSegment;out TimeA,TimeB:TpvScalar;out IntersectionPoint:TpvVector3):boolean; end; PpvRelativeSegment=^TpvRelativeSegment; TpvRelativeSegment=record public Origin:TpvVector3; Delta:TpvVector3; function SquaredSegmentDistanceTo(const pOtherRelativeSegment:TpvRelativeSegment;out t0,t1:TpvScalar):TpvScalar; end; PpvTriangle=^TpvTriangle; TpvTriangle=record public Points:array[0..2] of TpvVector3; Normal:TpvVector3; constructor Create(const pA,pB,pC:TpvVector3); function Contains(const p:TpvVector3):boolean; procedure ProjectToVector(const Vector:TpvVector3;out TriangleMin,TriangleMax:TpvScalar); function ProjectToPoint(var pPoint:TpvVector3;out s,t:TpvScalar):TpvScalar; function SegmentIntersect(const Segment:TpvSegment;out Time:TpvScalar;out IntersectionPoint:TpvVector3):boolean; function ClosestPointTo(const Point:TpvVector3;out ClosestPoint:TpvVector3):boolean; overload; function ClosestPointTo(const Segment:TpvSegment;out Time:TpvScalar;out pClosestPointOnSegment,pClosestPointOnTriangle:TpvVector3):boolean; overload; function GetClosestPointTo(const pPoint:TpvVector3;out ClosestPoint:TpvVector3;out s,t:TpvScalar):TpvScalar; overload; function GetClosestPointTo(const pPoint:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; overload; function DistanceTo(const Point:TpvVector3):TpvScalar; function SquaredDistanceTo(const Point:TpvVector3):TpvScalar; function RayIntersection(const RayOrigin,RayDirection:TpvVector3;var Time,u,v:TpvScalar):boolean; end; PpvSegmentTriangle=^TpvSegmentTriangle; TpvSegmentTriangle=record public Origin:TpvVector3; Edge0:TpvVector3; Edge1:TpvVector3; Edge2:TpvVector3; function RelativeSegmentIntersection(const ppvSegment:TpvRelativeSegment;out tS,tT0,tT1:TpvScalar):boolean; function SquaredPointTriangleDistance(const pPoint:TpvVector3;out pfSParam,pfTParam:TpvScalar):TpvScalar; function SquaredDistanceTo(const ppvRelativeSegment:TpvRelativeSegment;out segT,triT0,triT1:TpvScalar):TpvScalar; end; PpvOBB=^TpvOBB; TpvOBB=packed record public Center:TpvVector3; HalfExtents:TpvVector3; procedure ProjectToVector(const Vector:TpvVector3;out OBBMin,OBBMax:TpvScalar); function Intersect(const aWith:TpvOBB;const aThreshold:TpvScalar=EPSILON):boolean; overload; function RelativeSegmentIntersection(const ppvRelativeSegment:TpvRelativeSegment;out fracOut:TpvScalar;out posOut,NormalOut:TpvVector3):boolean; function TriangleIntersection(const Triangle:TpvTriangle;out Position,Normal:TpvVector3;out Penetration:TpvScalar):boolean; overload; function TriangleIntersection(const ppvTriangle:TpvTriangle;const MTV:PpvVector3=nil):boolean; overload; case TpvInt32 of 0:( Axis:array[0..2] of TpvVector3; ); 1:( Matrix:TpvMatrix3x3; ); end; PpvOBBs=^TpvOBBs; TpvOBBs=array[0..65535] of TpvOBB; PpvAABB=^TpvAABB; TpvAABB=record public constructor Create(const pMin,pMax:TpvVector3); constructor CreateFromOBB(const OBB:TpvOBB); function Cost:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Volume:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Area:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Center:TpvVector3; function Flip:TpvAABB; function SquareMagnitude:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Resize(const f:TpvScalar):TpvAABB; {$ifdef CAN_INLINE}inline;{$endif} function Combine(const WithAABB:TpvAABB):TpvAABB; {$ifdef CAN_INLINE}inline;{$endif} function CombineVector3(v:TpvVector3):TpvAABB; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const ToAABB:TpvAABB):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Radius:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Compare(const WithAABB:TpvAABB):boolean; {$ifdef CAN_INLINE}inline;{$endif} function Intersect(const aWith:TpvOBB;const aThreshold:TpvScalar=EPSILON):boolean; overload; function Intersect(const WithAABB:TpvAABB;Threshold:TpvScalar=EPSILON):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} class function Intersect(const aAABBMin,aAABBMax:TpvVector3;const WithAABB:TpvAABB;Threshold:TpvScalar=EPSILON):boolean; overload; static; {$ifdef CAN_INLINE}inline;{$endif} function Contains(const AABB:TpvAABB;const aThreshold:TpvScalar=EPSILON):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} class function Contains(const aAABBMin,aAABBMax:TpvVector3;const aAABB:TpvAABB;const aThreshold:TpvScalar=EPSILON):boolean; overload; static; {$ifdef CAN_INLINE}inline;{$endif} function Contains(const Vector:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} class function Contains(const aAABBMin,aAABBMax,aVector:TpvVector3):boolean; overload; static; {$ifdef CAN_INLINE}inline;{$endif} function Contains(const aOBB:TpvOBB):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function Touched(const Vector:TpvVector3;const Threshold:TpvScalar=1e-5):boolean; {$ifdef CAN_INLINE}inline;{$endif} function GetIntersection(const WithAABB:TpvAABB):TpvAABB; {$ifdef CAN_INLINE}inline;{$endif} function FastRayIntersection(const Origin,Direction:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} class function FastRayIntersection(const aAABBMin,aAABBMax:TpvVector3;const Origin,Direction:TpvVector3):boolean; overload; static; {$ifdef CAN_INLINE}inline;{$endif} function RayIntersectionHitDistance(const Origin,Direction:TpvVector3;var HitDist:TpvScalar):boolean; function RayIntersectionHitPoint(const Origin,Direction:TpvVector3;out HitPoint:TpvVector3):boolean; function RayIntersection(const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; overload; class function RayIntersection(const aAABBMin,aAABBMax:TpvVector3;const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; overload; static; function LineIntersection(const StartPoint,EndPoint:TpvVector3):boolean; overload; class function LineIntersection(const aAABBMin,aAABBMax:TpvVector3;const StartPoint,EndPoint:TpvVector3):boolean; overload; static; function TriangleIntersection(const Triangle:TpvTriangle):boolean; function Transform(const Transform:TpvMatrix3x3):TpvAABB; overload; {$ifdef CAN_INLINE}inline;{$endif} function Transform(const Transform:TpvMatrix4x4):TpvAABB; overload; {$ifdef CAN_INLINE}inline;{$endif} function MatrixMul(const Transform:TpvMatrix3x3):TpvAABB; overload; function MatrixMul(const Transform:TpvMatrix4x4):TpvAABB; overload; function ScissorRect(out Scissor:TpvClipRect;const mvp:TpvMatrix4x4;const vp:TpvClipRect;zcull:boolean):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function ScissorRect(out Scissor:TpvFloatClipRect;const mvp:TpvMatrix4x4;const vp:TpvFloatClipRect;zcull:boolean):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function MovingTest(const aAABBTo,bAABBFrom,bAABBTo:TpvAABB;var t:TpvScalar):boolean; function SweepTest(const bAABB:TpvAABB;const aV,bV:TpvVector3;var FirstTime,LastTime:TpvScalar):boolean; {$ifdef CAN_INLINE}inline;{$endif} case boolean of false:( Min,Max:TpvVector3; ); true:( MinMax:array[0..1] of TpvVector3; ); end; PpvAABBs=^TpvAABBs; TpvAABBs=array[0..65535] of TpvAABB; PpvSphere=^TpvSphere; TpvSphere=record public Center:TpvVector3; Radius:TpvScalar; constructor Create(const pCenter:TpvVector3;const pRadius:TpvScalar); constructor CreateFromAABB(const ppvAABB:TpvAABB); constructor CreateFromFrustum(const zNear,zFar,FOV,AspectRatio:TpvScalar;const Position,Direction:TpvVector3); function ToAABB(const pScale:TpvScalar=1.0):TpvAABB; function Cull(const p:array of TpvPlane):boolean; function Contains(const b:TpvSphere):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function Contains(const v:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const b:TpvSphere):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function DistanceTo(const b:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Intersect(const b:TpvSphere):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function Intersect(const b:TpvAABB):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function FastRayIntersection(const Origin,Direction:TpvVector3):boolean; function RayIntersection(const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; function Extends(const WithSphere:TpvSphere):TpvSphere; {$ifdef CAN_INLINE}inline;{$endif} function Transform(const Transform:TpvMatrix4x4):TpvSphere; {$ifdef CAN_INLINE}inline;{$endif} function TriangleIntersection(const Triangle:TpvTriangle;out Position,Normal:TpvVector3;out Depth:TpvScalar):boolean; overload; function TriangleIntersection(const SegmentTriangle:TpvSegmentTriangle;const TriangleNormal:TpvVector3;out Position,Normal:TpvVector3;out Depth:TpvScalar):boolean; overload; function SweptIntersection(const SphereB:TpvSphere;const VelocityA,VelocityB:TpvVector3;out TimeFirst,TimeLast:TpvScalar):boolean; {$ifdef CAN_INLINE}inline;{$endif} end; PpvSpheres=^TpvSpheres; TpvSpheres=array[0..65535] of TpvSphere; PpvCapsule=^TpvCapsule; TpvCapsule=packed record LineStartPoint:TpvVector3; LineEndPoint:TpvVector3; Radius:TpvScalar; end; PpvMinkowskiDescription=^TpvMinkowskiDescription; TpvMinkowskiDescription=record public HalfAxis:TpvVector4; Position_LM:TpvVector3; end; PpvSphereCoords=^TpvSphereCoords; TpvSphereCoords=record public Radius:TpvScalar; Theta:TpvScalar; Phi:TpvScalar; constructor CreateFromCartesianVector(const v:TpvVector3); overload; constructor CreateFromCartesianVector(const v:TpvVector4); overload; function ToCartesianVector:TpvVector3; end; PpvRect=^TpvRect; TpvRect=packed record private function GetWidth:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetWidth(const aWidth:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetHeight:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetHeight(const aHeight:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetSize:TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} procedure SetSize(const aSize:TpvVector2); {$ifdef CAN_INLINE}inline;{$endif} public constructor CreateFromVkRect2D(const aFrom:TVkRect2D); overload; constructor CreateAbsolute(const aLeft,aTop,aRight,aBottom:TpvFloat); overload; constructor CreateAbsolute(const aLeftTop,aRightBottom:TpvVector2); overload; constructor CreateRelative(const aLeft,aTop,aWidth,aHeight:TpvFloat); overload; constructor CreateRelative(const aLeftTop,aSize:TpvVector2); overload; class operator Implicit(const a:TVkRect2D):TpvRect; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TVkRect2D):TpvRect; {$ifdef CAN_INLINE}inline;{$endif} class operator Implicit(const a:TpvRect):TVkRect2D; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const a:TpvRect):TVkRect2D; {$ifdef CAN_INLINE}inline;{$endif} class operator Equal(const a,b:TpvRect):boolean; {$ifdef CAN_INLINE}inline;{$endif} class operator NotEqual(const a,b:TpvRect):boolean; {$ifdef CAN_INLINE}inline;{$endif} function ToVkRect2D:TVkRect2D; {$ifdef CAN_INLINE}inline;{$endif} function Cost:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Area:TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Center:TpvVector2; {$ifdef CAN_INLINE}inline;{$endif} function Combine(const aWithRect:TpvRect):TpvRect; overload; {$ifdef CAN_INLINE}inline;{$endif} function Combine(const aWithPoint:TpvVector2):TpvRect; overload; {$ifdef CAN_INLINE}inline;{$endif} function Intersect(const aWithRect:TpvRect;Threshold:TpvScalar=EPSILON):boolean; overload;// {$ifdef CAN_INLINE}inline;{$endif} function Contains(const aWithRect:TpvRect;Threshold:TpvScalar=EPSILON):boolean; overload;// {$ifdef CAN_INLINE}inline;{$endif} function GetIntersection(const WithAABB:TpvRect):TpvRect; {$ifdef CAN_INLINE}inline;{$endif} function Touched(const aPosition:TpvVector2;Threshold:TpvScalar=EPSILON):boolean; {$ifdef CAN_INLINE}inline;{$endif} property Width:TpvFloat read GetWidth write SetWidth; property Height:TpvFloat read GetHeight write SetHeight; property Size:TpvVector2 read GetSize write SetSize; public case TpvInt32 of 0:( Left:TpvFloat; Top:TpvFloat; Right:TpvFloat; Bottom:TpvFloat; ); 1:( MinX:TpvFloat; MinY:TpvFloat; MaxX:TpvFloat; MaxY:TpvFloat; ); 2:( LeftTop:TpvVector2; RightBottom:TpvVector2; ); 3:( Min:TpvVector2; Max:TpvVector2; ); 4:( Offset:TpvVector2; ); 5:( Vector4:TpvVector4; ); 6:( AxisComponents:array[0..1,0..1] of TpvFloat; ); 7:( Components:array[0..3] of TpvFloat; ); 8:( MinMax:array[0..1] of TpvVector2; ); end; TpvRectArray=array of TpvRect; PpvAABB2D=^TpvAABB2D; TpvAABB2D=TpvRect; Vec2=TpvVector2; Vec3=TpvVector3; Vec4=TpvVector4; Mat2=TpvMatrix2x2; Mat3=TpvMatrix3x3; Mat4=TpvMatrix4x4; TpvMathPropertyOnChange=procedure(const aSender:TObject) of object; TpvVector2Property=class(TPersistent) private fVector:PpvVector2; fOnChange:TpvMathPropertyOnChange; function GetX:TpvScalar; function GetY:TpvScalar; function GetVector:TpvVector2; procedure SetX(const aNewValue:TpvScalar); procedure SetY(const aNewValue:TpvScalar); procedure SetVector(const aNewVector:TpvVector2); public constructor Create(const aVector:PpvVector2); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Vector:TpvVector2 read GetVector write SetVector; published property x:TpvScalar read GetX write SetX; property y:TpvScalar read GetY write SetY; end; TpvVector3Property=class(TPersistent) private fVector:PpvVector3; fOnChange:TpvMathPropertyOnChange; function GetX:TpvScalar; function GetY:TpvScalar; function GetZ:TpvScalar; function GetVector:TpvVector3; procedure SetX(const aNewValue:TpvScalar); procedure SetY(const aNewValue:TpvScalar); procedure SetZ(const aNewValue:TpvScalar); procedure SetVector(const aNewVector:TpvVector3); public constructor Create(const aVector:PpvVector3); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Vector:TpvVector3 read GetVector write SetVector; published property x:TpvScalar read GetX write SetX; property y:TpvScalar read GetY write SetY; property z:TpvScalar read GetZ write SetZ; end; TpvVector4Property=class(TPersistent) private fVector:PpvVector4; fOnChange:TpvMathPropertyOnChange; function GetX:TpvScalar; function GetY:TpvScalar; function GetZ:TpvScalar; function GetW:TpvScalar; function GetVector:TpvVector4; procedure SetX(const aNewValue:TpvScalar); procedure SetY(const aNewValue:TpvScalar); procedure SetZ(const aNewValue:TpvScalar); procedure SetW(const aNewValue:TpvScalar); procedure SetVector(const aNewVector:TpvVector4); public constructor Create(const aVector:PpvVector4); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Vector:TpvVector4 read GetVector write SetVector; published property x:TpvScalar read GetX write SetX; property y:TpvScalar read GetY write SetY; property z:TpvScalar read GetZ write SetZ; property w:TpvScalar read GetW write SetW; end; TpvQuaternionProperty=class(TPersistent) private fQuaternion:PpvQuaternion; fOnChange:TpvMathPropertyOnChange; function GetX:TpvScalar; function GetY:TpvScalar; function GetZ:TpvScalar; function GetW:TpvScalar; function GetQuaternion:TpvQuaternion; procedure SetX(const aNewValue:TpvScalar); procedure SetY(const aNewValue:TpvScalar); procedure SetZ(const aNewValue:TpvScalar); procedure SetW(const aNewValue:TpvScalar); procedure SetQuaternion(const aNewQuaternion:TpvQuaternion); public constructor Create(const AQuaternion:PpvQuaternion); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Quaternion:TpvQuaternion read GetQuaternion write SetQuaternion; published property x:TpvScalar read GetX write SetX; property y:TpvScalar read GetY write SetY; property z:TpvScalar read GetZ write SetZ; property w:TpvScalar read GetW write SetW; end; TpvAngleProperty=class(TPersistent) private fRadianAngle:PpvScalar; fOnChange:TpvMathPropertyOnChange; function GetAngle:TpvScalar; function GetRadianAngle:TpvScalar; procedure SetAngle(const aNewValue:TpvScalar); procedure SetRadianAngle(const aNewValue:TpvScalar); public constructor Create(const aRadianAngle:PpvScalar); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property RadianAngle:TpvScalar read GetRadianAngle write SetRadianAngle; published property Angle:TpvScalar read GetAngle write SetAngle; end; TpvRotation3DProperty=class(TPersistent) private fQuaternion:PpvQuaternion; fOnChange:TpvMathPropertyOnChange; function GetX:TpvScalar; function GetY:TpvScalar; function GetZ:TpvScalar; function GetW:TpvScalar; function GetPitch:TpvScalar; function GetYaw:TpvScalar; function GetRoll:TpvScalar; function GetQuaternion:TpvQuaternion; procedure SetX(const aNewValue:TpvScalar); procedure SetY(const aNewValue:TpvScalar); procedure SetZ(const aNewValue:TpvScalar); procedure SetW(const aNewValue:TpvScalar); procedure SetPitch(const aNewValue:TpvScalar); procedure SetYaw(const aNewValue:TpvScalar); procedure SetRoll(const aNewValue:TpvScalar); procedure SetQuaternion(const aNewQuaternion:TpvQuaternion); public constructor Create(const AQuaternion:PpvQuaternion); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property x:TpvScalar read GetX write SetX; property y:TpvScalar read GetY write SetY; property z:TpvScalar read GetZ write SetZ; property w:TpvScalar read GetW write SetW; property Quaternion:TpvQuaternion read GetQuaternion write SetQuaternion; published property Pitch:TpvScalar read GetPitch write SetPitch; property Yaw:TpvScalar read GetYaw write SetYaw; property Roll:TpvScalar read GetRoll write SetRoll; end; TpvColorRGBProperty=class(TPersistent) private fVector:PpvVector3; fOnChange:TpvMathPropertyOnChange; function GetR:TpvScalar; function GetG:TpvScalar; function GetB:TpvScalar; function GetVector:TpvVector3; procedure SetR(const aNewValue:TpvScalar); procedure SetG(const aNewValue:TpvScalar); procedure SetB(const aNewValue:TpvScalar); procedure SetVector(const aNewVector:TpvVector3); public constructor Create(const aVector:PpvVector3); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Vector:TpvVector3 read GetVector write SetVector; published property r:TpvScalar read GetR write SetR; property g:TpvScalar read GetG write SetG; property b:TpvScalar read GetB write SetB; end; TpvColorRGBAProperty=class(TPersistent) private fVector:PpvVector4; fOnChange:TpvMathPropertyOnChange; function GetR:TpvScalar; function GetG:TpvScalar; function GetB:TpvScalar; function GetA:TpvScalar; function GetVector:TpvVector4; procedure SetR(const aNewValue:TpvScalar); procedure SetG(const aNewValue:TpvScalar); procedure SetB(const aNewValue:TpvScalar); procedure SetA(const aNewValue:TpvScalar); procedure SetVector(const aNewVector:TpvVector4); public constructor Create(const aVector:PpvVector4); destructor Destroy; override; property OnChange:TpvMathPropertyOnChange read fOnChange write fOnChange; property Vector:TpvVector4 read GetVector write SetVector; published property r:TpvScalar read GetR write SetR; property g:TpvScalar read GetG write SetG; property b:TpvScalar read GetB write SetB; property a:TpvScalar read GetA write SetA; end; TpvPolynomial=record public Coefs:TpvDoubleDynamicArray; constructor Create(const aCoefs:array of TpvDouble); function GetDegree:TpvSizeInt; function Eval(const aValue:TpvDouble):TpvDouble; procedure SimplifyEquals(const aThreshold:TpvDouble=1e-12); function GetDerivative:TpvPolynomial; function GetLinearRoots:TpvDoubleDynamicArray; function GetQuadraticRoots:TpvDoubleDynamicArray; function GetCubicRoots:TpvDoubleDynamicArray; function GetQuarticRoots:TpvDoubleDynamicArray; function GetRoots:TpvDoubleDynamicArray; function Bisection(aMin,aMax:TpvDouble;out aResult:TpvDouble):Boolean; function GetRootsInInterval(const aMin,aMax:TpvDouble):TpvDoubleDynamicArray; end; PpvPolynomial=^TpvPolynomial; function RoundUpToPowerOfTwo(x:TpvUInt32):TpvUInt32; {$ifdef fpc}{$ifdef CAN_INLINE}inline;{$endif}{$endif} function RoundUpToPowerOfTwo64(x:TpvUInt64):TpvUInt64; {$ifdef fpc}{$ifdef CAN_INLINE}inline;{$endif}{$endif} function RoundUpToPowerOfTwoSizeUInt(x:TpvSizeUInt):TpvSizeUInt; {$ifdef fpc}{$ifdef CAN_INLINE}inline;{$endif}{$endif} function IntLog2(x:TpvUInt32):TpvUInt32; {$ifdef fpc}{$ifdef CAN_INLINE}inline;{$endif}{$endif} function IntLog264(x:TpvUInt64):TpvUInt32; {$ifdef fpc}{$ifdef CAN_INLINE}inline;{$endif}{$endif} function Modulo(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ModuloPos(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function IEEERemainder(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function Modulus(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function CastFloatToUInt32(const v:TpvFloat):TpvUInt32; {$ifdef CAN_INLINE}inline;{$endif} function CastUInt32ToFloat(const v:TpvUInt32):TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} function SignNonZero(const v:TpvFloat):TpvInt32; {$ifdef CAN_INLINE}inline;{$endif} function Determinant4x4(const v0,v1,v2,v3:TpvVector4):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function SolveQuadraticRoots(const a,b,c:TpvScalar;out t1,t2:TpvScalar):boolean; function LinearPolynomialRoot(const a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function QuadraticPolynomialRoot(const a,b,c:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function CubicPolynomialRoot(const a,b,c,d:TpvScalar):TpvScalar; function FloatLerp(const aV1,aV2,aTime:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function DoubleLerp(const aV1,aV2,aTime:TpvDouble):TpvDouble; {$ifdef CAN_INLINE}inline;{$endif} function Cross(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Cross(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Cross(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Dot(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Dot(const a,b:TpvVector2):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Dot(const a,b:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Dot(const a,b:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Len(const a:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Len(const a:TpvVector2):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Len(const a:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Len(const a:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Normalize(const a:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Normalize(const a:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Normalize(const a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Normalize(const a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Minimum(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Minimum(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Minimum(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Minimum(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Maximum(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Maximum(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Maximum(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Maximum(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Pow(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Pow(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Pow(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Pow(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I,Nref:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I,Nref:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I,Nref:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function FaceForward(const N,I,Nref:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Reflect(const I,N:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Reflect(const I,N:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Reflect(const I,N:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Reflect(const I,N:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Refract(const I,N:TpvScalar;const Eta:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Refract(const I,N:TpvVector2;const Eta:TpvScalar):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Refract(const I,N:TpvVector3;const Eta:TpvScalar):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Refract(const I,N:TpvVector4;const Eta:TpvScalar):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Clamp(const Value,MinValue,MaxValue:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Clamp(const Value,MinValue,MaxValue:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Clamp(const Value,MinValue,MaxValue:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Clamp(const Value,MinValue,MaxValue:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Mix(const a,b,t:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Mix(const a,b,t:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Mix(const a,b,t:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Mix(const a,b,t:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function Step(const Edge,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function Step(const Edge,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function Step(const Edge,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function Step(const Edge,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function NearestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function NearestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function NearestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function NearestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function LinearStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function LinearStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function LinearStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function LinearStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmootherStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmootherStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmootherStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmootherStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function SmoothestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} function SuperSmoothestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} procedure DoCalculateInterval(const Vertices:PpvVector3s;const Count:TpvInt32;const Axis:TpvVector3;out OutMin,OutMax:TpvScalar); function DoSpanIntersect(const Vertices1:PpvVector3s;const Count1:TpvInt32;const Vertices2:PpvVector3s;const Count2:TpvInt32;const AxisTest:TpvVector3;out AxisPenetration:TpvVector3):TpvScalar; function BoxGetDistanceToPoint(Point:TpvVector3;const Center,Size:TpvVector3;const InvTransformMatrix,TransformMatrix:TpvMatrix4x4;var ClosestBoxPoint:TpvVector3):TpvScalar; function GetDistanceFromLine(const p0,p1,p:TpvVector3;var Projected:TpvVector3;const Time:PpvScalar=nil):TpvScalar; procedure LineClosestApproach(const pa,ua,pb,ub:TpvVector3;var Alpha,Beta:TpvScalar); procedure ClosestLineBoxPoints(const p1,p2,c:TpvVector3;const ir,r:TpvMatrix4x4;const side:TpvVector3;var lret,bret:TpvVector3); procedure ClosestLineSegmentPoints(const a0,a1,b0,b1:TpvVector3;var cp0,cp1:TpvVector3); function LineSegmentIntersection(const a0,a1,b0,b1:TpvVector3;const p:PpvVector3=nil):boolean; function LineLineIntersection(const a0,a1,b0,b1:TpvVector3;const pa:PpvVector3=nil;const pb:PpvVector3=nil;const ta:PpvScalar=nil;const tb:PpvScalar=nil):boolean; function IsPointsSameSide(const p0,p1,Origin,Direction:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function PointInTriangle(const p0,p1,p2,Normal,p:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function PointInTriangle(const p0,p1,p2,p:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} function GetOverlap(const MinA,MaxA,MinB,MaxB:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function OldTriangleTriangleIntersection(const a0,a1,a2,b0,b1,b2:TpvVector3):boolean; function TriangleTriangleIntersection(const v0,v1,v2,u0,u1,u2:TpvVector3):boolean; function UnclampedClosestPointToLine(const LineStartPoint,LineEndPoint,Point:TpvVector3;const ClosestPointOnLine:PpvVector3=nil;const Time:PpvScalar=nil):TpvScalar; function ClosestPointToLine(const LineStartPoint,LineEndPoint,Point:TpvVector3;const ClosestPointOnLine:PpvVector3=nil;const Time:PpvScalar=nil):TpvScalar; function ClosestPointToAABB(const AABB:TpvAABB;const Point:TpvVector3;const ClosestPointOnAABB:PpvVector3=nil):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ClosestPointToOBB(const OBB:TpvOBB;const Point:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ClosestPointToSphere(const Sphere:TpvSphere;const Point:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ClosestPointToCapsule(const Capsule:TpvCapsule;const Point:TpvVector3;out ClosestPoint:TpvVector3;const Time:PpvScalar=nil):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function ClosestPointToTriangle(const a,b,c,p:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; function SquaredDistanceFromPointToAABB(const AABB:TpvAABB;const Point:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function SquaredDistanceFromPointToTriangle(const p,a,b,c:TpvVector3):TpvScalar; function IsParallel(const a,b:TpvVector3;const Tolerance:TpvScalar=1e-5):boolean; {$ifdef CAN_INLINE}inline;{$endif} function Vector3ToAnglesLDX(v:TpvVector3):TpvVector3; procedure AnglesToVector3LDX(const Angles:TpvVector3;var ForwardVector,RightVector,UpVector:TpvVector3); function UnsignedAngle(const v0,v1:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function AngleDegClamp(a:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function AngleDegDiff(a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function AngleClamp(a:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function AngleDiff(a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function AngleLerp(a,b,x:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} function InertiaTensorTransform(const Inertia,Transform:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} function InertiaTensorParallelAxisTheorem(const Center:TpvVector3;const Mass:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} procedure OrthoNormalize(var Tangent,Bitangent,Normal:TpvVector3); procedure RobustOrthoNormalize(var Tangent,Bitangent,Normal:TpvVector3;const Tolerance:TpvScalar=1e-3); function MaxOverlaps(const Min1,Max1,Min2,Max2:TpvScalar;var LowerLim,UpperLim:TpvScalar):boolean; function GetHaltonSequence(const aIndex,aPrimeBase:TpvUInt32):TpvDouble; function PackFP32FloatToM6E5Float(const pValue:TpvFloat):TpvUInt32; function PackFP32FloatToM5E5Float(const pValue:TpvFloat):TpvUInt32; function Float32ToFloat11(const pValue:TpvFloat):TpvUInt32; function Float32ToFloat10(const pValue:TpvFloat):TpvUInt32; function ConvertRGB32FToRGB9E5(r,g,b:TpvFloat):TpvUInt32; function ConvertRGB32FToR11FG11FB10F(const r,g,b:TpvFloat):TpvUInt32; {$ifdef CAN_INLINE}inline;{$endif} function PackTangentSpace(const aTangent,aBitangent,aNormal:TpvVector3):TpvPackedTangentSpace; procedure UnpackTangentSpace(const aPackedTangentSpace:TpvPackedTangentSpace;out aTangent,aBitangent,aNormal:TpvVector3); function ConvertLinearToSRGB(const aColor:TpvVector3):TpvVector3; overload; function ConvertLinearToSRGB(const aColor:TpvVector4):TpvVector4; overload; function ConvertSRGBToLinear(const aColor:TpvVector3):TpvVector3; overload; function ConvertSRGBToLinear(const aColor:TpvVector4):TpvVector4; overload; function ConvertHSVToRGB(const aHSV:TpvVector3):TpvVector3; function ConvertRGBToHSV(const aRGB:TpvVector3):TpvVector3; function SolveQuadratic(const a,b,c:TpvDouble;out r0,r1:TpvDouble):TpvSizeInt; function SolveCubic(const a,b,c,d:TpvDouble;out r0,r1,r2:TpvDouble):TpvSizeInt; function SolveQuartic(const a,b,c,d,e:TpvDouble;out r0,r1,r2,r3:TpvDouble):TpvSizeInt; function SolveRootsInInterval(const aCoefs:array of TpvDouble;const aMin,aMax:TpvDouble):TpvDoubleDynamicArray; implementation function RoundUpToPowerOfTwo(x:TpvUInt32):TpvUInt32; begin dec(x); x:=x or (x shr 1); x:=x or (x shr 2); x:=x or (x shr 4); x:=x or (x shr 8); x:=x or (x shr 16); result:=x+1; end; function RoundUpToPowerOfTwo64(x:TpvUInt64):TpvUInt64; begin dec(x); x:=x or (x shr 1); x:=x or (x shr 2); x:=x or (x shr 4); x:=x or (x shr 8); x:=x or (x shr 16); x:=x or (x shr 32); result:=x+1; end; function RoundUpToPowerOfTwoSizeUInt(x:TpvSizeUInt):TpvSizeUInt; begin dec(x); x:=x or (x shr 1); x:=x or (x shr 2); x:=x or (x shr 4); x:=x or (x shr 8); x:=x or (x shr 16); {$ifdef CPU64} x:=x or (x shr 32); {$endif} result:=x+1; end; function IntLog2(x:TpvUInt32):TpvUInt32; {$if defined(fpc)}{$ifdef CAN_INLINE}inline;{$endif} begin if x<>0 then begin result:=BSRWord(x); end else begin result:=0; end; end; {$elseif defined(cpu386)} asm test eax,eax jz @Done bsr eax,eax @Done: end; {$elseif defined(cpux86_64)} asm {$ifndef fpc} .NOFRAME {$endif} {$ifdef Windows} bsr eax,ecx {$else} bsr eax,edi {$endif} jnz @Done xor eax,eax @Done: end; {$else} begin x:=x or (x shr 1); x:=x or (x shr 2); x:=x or (x shr 4); x:=x or (x shr 8); x:=x or (x shr 16); x:=x shr 1; dec(x,(x shr 1) and $55555555); x:=((x shr 2) and $33333333)+(x and $33333333); x:=((x shr 4)+x) and $0f0f0f0f; inc(x,x shr 8); inc(x,x shr 16); result:=x and $3f; end; {$ifend} function IntLog264(x:TpvUInt64):TpvUInt32; {$if defined(fpc)}{$ifdef CAN_INLINE}inline;{$endif} begin if x<>0 then begin result:=BSRQWord(x); end else begin result:=0; end; end; {$elseif defined(cpu386)} asm bsr eax,dword ptr [x+4] jz @LowPart add eax,32 jmp @Done @LowPart: xor ecx,ecx bsr eax,dword ptr [x+0] jnz @Done xor eax,eax @Done: end; {$elseif defined(cpux86_64)} asm {$ifndef fpc} .NOFRAME {$endif} {$ifdef Windows} bsr rax,rcx {$else} bsr rax,rdi {$endif} jnz @Done xor eax,eax @Done: end; {$else} begin x:=x or (x shr 1); x:=x or (x shr 2); x:=x or (x shr 4); x:=x or (x shr 8); x:=x or (x shr 16); x:=x or (x shr 32); x:=x shr 1; dec(x,(x shr 1) and $5555555555555555); x:=((x shr 2) and $3333333333333333)+(x and $3333333333333333); x:=((x shr 4)+x) and $0f0f0f0f0f0f0f0f; inc(x,x shr 8); inc(x,x shr 16); inc(x,x shr 32); result:=x and $7f; end; {$ifend} {$if defined(fpc) and (defined(cpu386) or defined(cpux64) or defined(cpuamd64))} // For to avoid "Fatal: Internal error 200604201" at the FreePascal compiler, when >= -O2 is used function Sign(const aValue:TpvScalar):TpvInt32; begin if aValue<0.0 then begin result:=-1; end else if aValue>0.0 then begin result:=1; end else begin result:=0; end; end; {$ifend} function Modulo(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin result:=x-(floor(x/y)*y); end; function ModuloPos(x,y:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin if y>0.0 then begin result:=Modulo(x,y); while result<0.0 do begin result:=result+y; end; while result>=y do begin result:=result-y; end; end else begin result:=x; end; end; function IEEERemainder(x,y:TpvScalar):TpvScalar; begin result:=x-(round(x/y)*y); end; function Modulus(x,y:TpvScalar):TpvScalar; begin result:=(abs(x)-(abs(y)*(floor(abs(x)/abs(y)))))*Sign(x); end; function CastFloatToUInt32(const v:TpvFloat):TpvUInt32; begin result:=PpvUInt32(Pointer(@v))^; end; function CastUInt32ToFloat(const v:TpvUInt32):TpvFloat; begin result:=PpvFloat(Pointer(@v))^; end; function SignNonZero(const v:TpvFloat):TpvInt32; begin result:=1-(TpvInt32(TpvUInt32(TpvUInt32(PpvUInt32(Pointer(@v))^) shr 31)) shl 1); end; function Determinant4x4(const v0,v1,v2,v3:TpvVector4):TpvScalar; begin result:=(v0.w*v1.z*v2.y*v3.x)-(v0.z*v1.w*v2.y*v3.x)- (v0.w*v1.y*v2.z*v3.x)+(v0.y*v1.w*v2.z*v3.x)+ (v0.z*v1.y*v2.w*v3.x)-(v0.y*v1.z*v2.w*v3.x)- (v0.w*v1.z*v2.x*v3.y)+(v0.z*v1.w*v2.x*v3.y)+ (v0.w*v1.x*v2.z*v3.y)-(v0.x*v1.w*v2.z*v3.y)- (v0.z*v1.x*v2.w*v3.y)+(v0.x*v1.z*v2.w*v3.y)+ (v0.w*v1.y*v2.x*v3.z)-(v0.y*v1.w*v2.x*v3.z)- (v0.w*v1.x*v2.y*v3.z)+(v0.x*v1.w*v2.y*v3.z)+ (v0.y*v1.x*v2.w*v3.z)-(v0.x*v1.y*v2.w*v3.z)- (v0.z*v1.y*v2.x*v3.w)+(v0.y*v1.z*v2.x*v3.w)+ (v0.z*v1.x*v2.y*v3.w)-(v0.x*v1.z*v2.y*v3.w)- (v0.y*v1.x*v2.z*v3.w)+(v0.x*v1.y*v2.z*v3.w); end; function SolveQuadraticRoots(const a,b,c:TpvScalar;out t1,t2:TpvScalar):boolean; var a2,d,InverseDenominator:TpvScalar; begin result:=false; d:=sqr(b)-(4.0*(a*c)); if d<0.0 then begin exit; end else begin a2:=a*2.0; if abs(a2)<1e-7 then begin exit; end else begin InverseDenominator:=1.0/a2; if abs(d)<EPSILON then begin t1:=(-b)*InverseDenominator; t2:=t1; end else begin d:=sqrt(d); t1:=((-b)+d)*InverseDenominator; t2:=((-b)-d)*InverseDenominator; if t1>t2 then begin d:=t1; t1:=t2; t2:=d; end; end; result:=true; end; end; end; function LinearPolynomialRoot(const a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin if abs(a)>EPSILON then begin result:=-(b/a); end else begin result:=0.0; end; end; function QuadraticPolynomialRoot(const a,b,c:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var d,InverseDenominator,t0,t1:TpvScalar; begin if abs(a)>EPSILON then begin d:=sqr(b)-(4.0*(a*c)); InverseDenominator:=1.0/(2.0*a); if d>=0.0 then begin if d<EPSILON then begin t0:=(-b)*InverseDenominator; t1:=t0; end else begin d:=sqrt(d); t0:=((-b)+d)*InverseDenominator; t1:=((-b)-d)*InverseDenominator; end; if abs(t0)<abs(t1) then begin result:=t0; end else begin result:=t1; end; end else begin result:=0.0; end; end else begin result:=LinearPolynomialRoot(b,c); end; end; function CubicPolynomialRoot(const a,b,c,d:TpvScalar):TpvScalar; var f,g,h,hs,r,s,t,u,i,j,k,l,m,n,p,t0,t1,t2:TpvScalar; begin if abs(a)>EPSILON then begin if abs(1.0-a)<EPSILON then begin f:=((3.0*c)-sqr(b))/3.0; g:=((2.0*(b*sqr(b)))-(9.0*(b*c))+(27.0*d))/27.0; h:=(sqr(g)*0.25)+((f*sqr(f))/27.0); if (abs(f)<1e-12) and (abs(h)<1e-12) and (abs(g)<1e-12) then begin result:=d; if result<0.0 then begin result:=power(-result,1.0/3.0); end else begin result:=-power(result,1.0/3.0); end; end else if h>0.0 then begin hs:=sqrt(h); r:=(-(g*0.5))+hs; if r<0.0 then begin s:=-power(-r,1.0/3.0); end else begin s:=power(r,1.0/3.0); end; t:=(-(g*0.5))-hs; if t<0.0 then begin u:=-power(-t,1.0/3.0); end else begin u:=power(t,1.0/3.0); end; result:=(s+u)-(b/3.0); end else begin i:=sqrt((sqr(g)/4.0)-h); if i<0.0 then begin j:=-power(-i,1.0/3.0); end else begin j:=power(i,1.0/3.0); end; k:=ArcCos(-(g/(2.0*i))); l:=-j; m:=cos(k/3.0); n:=sqrt(3.0)*sin(k/3.0); p:=-(b/3.0); t0:=(2.0*(j*cos(k/3.0)))-(b/3.0); t1:=(l*(m+n))+p; t2:=(l*(m-n))+p; if abs(t0)<abs(t1) then begin if abs(t0)<abs(t2) then begin result:=t0; end else begin result:=t2; end; end else begin if abs(t1)<abs(t2) then begin result:=t1; end else begin result:=t2; end; end; end; end else begin f:=((3.0*(c/a))-(sqr(b)/sqr(a)))/3.0; g:=(((2.0*(b*sqr(b)))/(a*sqr(a)))-((9.0*(b*c))/sqr(a))+(27.0*(d/a)))/27.0; h:=(sqr(g)*0.25)+((f*sqr(f))/27.0); if (abs(f)<1e-12) and (abs(h)<1e-12) and (abs(g)<1e-12) then begin result:=d/a; if result<0.0 then begin result:=power(-result,1.0/3.0); end else begin result:=-power(result,1.0/3.0); end; end else if h>0.0 then begin hs:=sqrt(h); r:=(-(g*0.5))+hs; if r<0.0 then begin s:=-power(-r,1.0/3.0); end else begin s:=power(r,1.0/3.0); end; t:=(-(g*0.5))-hs; if t<0.0 then begin u:=-power(-t,1.0/3.0); end else begin u:=power(t,1.0/3.0); end; result:=(s+u)-(b/(3.0*a)); end else begin i:=sqrt((sqr(g)/4.0)-h); if i<0.0 then begin j:=-power(-i,1.0/3.0); end else begin j:=power(i,1.0/3.0); end; k:=ArcCos(-(g/(2.0*i))); l:=-j; m:=cos(k/3.0); n:=sqrt(3.0)*sin(k/3.0); p:=-(b/(3.0*a)); t0:=(2.0*(j*cos(k/3.0)))-(b/(3.0*a)); t1:=(l*(m+n))+p; t2:=(l*(m-n))+p; if abs(t0)<abs(t1) then begin if abs(t0)<abs(t2) then begin result:=t0; end else begin result:=t2; end; end else begin if abs(t1)<abs(t2) then begin result:=t1; end else begin result:=t2; end; end; end; end; end else begin result:=QuadraticPolynomialRoot(b,c,d); end; end; function FloatLerp(const aV1,aV2,aTime:TpvScalar):TpvScalar; begin if aTime<0.0 then begin result:=aV1; end else if aTime>1.0 then begin result:=aV2; end else begin result:=(aV1*(1.0-aTime))+(aV2*aTime); end; end; function DoubleLerp(const aV1,aV2,aTime:TpvDouble):TpvDouble; begin if aTime<0.0 then begin result:=aV1; end else if aTime>1.0 then begin result:=aV2; end else begin result:=(aV1*(1.0-aTime))+(aV2*aTime); end; end; constructor TpvVector2.Create(const aX:TpvScalar); begin x:=aX; y:=aX; end; constructor TpvVector2.Create(const aX,aY:TpvScalar); begin x:=aX; y:=aY; end; class function TpvVector2.InlineableCreate(const aX:TpvScalar):TpvVector2; begin result.x:=aX; result.y:=aX; end; class function TpvVector2.InlineableCreate(const aX,aY:TpvScalar):TpvVector2; begin result.x:=aX; result.y:=aY; end; class operator TpvVector2.Implicit(const aScalar:TpvScalar):TpvVector2; begin result.x:=aScalar; result.y:=aScalar; end; class operator TpvVector2.Explicit(const aScalar:TpvScalar):TpvVector2; begin result.x:=aScalar; result.y:=aScalar; end; class operator TpvVector2.Equal(const aLeft,aRight:TpvVector2):boolean; begin result:=SameValue(aLeft.x,aRight.x) and SameValue(aLeft.y,aRight.y); end; class operator TpvVector2.NotEqual(const aLeft,aRight:TpvVector2):boolean; begin result:=(not SameValue(aLeft.x,aRight.x)) or (not SameValue(aLeft.y,aRight.y)); end; class operator TpvVector2.Inc(const aValue:TpvVector2):TpvVector2; begin result.x:=aValue.x+1.0; result.y:=aValue.y+1.0; end; class operator TpvVector2.Dec(const aValue:TpvVector2):TpvVector2; begin result.x:=aValue.x-1.0; result.y:=aValue.y-1.0; end; class operator TpvVector2.Add(const a,b:TpvVector2):TpvVector2; begin result.x:=a.x+b.x; result.y:=a.y+b.y; end; class operator TpvVector2.Add(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=a.x+b; result.y:=a.y+b; end; class operator TpvVector2.Add(const a:TpvScalar;const b:TpvVector2):TpvVector2; begin result.x:=a+b.x; result.y:=a+b.y; end; class operator TpvVector2.Subtract(const a,b:TpvVector2):TpvVector2; begin result.x:=a.x-b.x; result.y:=a.y-b.y; end; class operator TpvVector2.Subtract(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=a.x-b; result.y:=a.y-b; end; class operator TpvVector2.Subtract(const a:TpvScalar;const b:TpvVector2): TpvVector2; begin result.x:=a-b.x; result.y:=a-b.y; end; class operator TpvVector2.Multiply(const a,b:TpvVector2):TpvVector2; begin result.x:=a.x*b.x; result.y:=a.y*b.y; end; class operator TpvVector2.Multiply(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=a.x*b; result.y:=a.y*b; end; class operator TpvVector2.Multiply(const a:TpvScalar;const b:TpvVector2):TpvVector2; begin result.x:=a*b.x; result.y:=a*b.y; end; class operator TpvVector2.Divide(const a,b:TpvVector2):TpvVector2; begin result.x:=a.x/b.x; result.y:=a.y/b.y; end; class operator TpvVector2.Divide(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=a.x/b; result.y:=a.y/b; end; class operator TpvVector2.Divide(const a:TpvScalar;const b:TpvVector2):TpvVector2; begin result.x:=a/b.x; result.y:=a/b.y; end; class operator TpvVector2.IntDivide(const a,b:TpvVector2):TpvVector2; begin result.x:=a.x/b.x; result.y:=a.y/b.y; end; class operator TpvVector2.IntDivide(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=a.x/b; result.y:=a.y/b; end; class operator TpvVector2.IntDivide(const a:TpvScalar;const b:TpvVector2):TpvVector2; begin result.x:=a/b.x; result.y:=a/b.y; end; class operator TpvVector2.Modulus(const a,b:TpvVector2):TpvVector2; begin result.x:=Modulus(a.x,b.x); result.y:=Modulus(a.y,b.y); end; class operator TpvVector2.Modulus(const a:TpvVector2;const b:TpvScalar):TpvVector2; begin result.x:=Modulus(a.x,b); result.y:=Modulus(a.y,b); end; class operator TpvVector2.Modulus(const a:TpvScalar;const b:TpvVector2):TpvVector2; begin result.x:=Modulus(a,b.x); result.y:=Modulus(a,b.y); end; class operator TpvVector2.Negative(const aValue:TpvVector2):TpvVector2; begin result.x:=-aValue.x; result.y:=-aValue.y; end; class operator TpvVector2.Positive(const aValue:TpvVector2):TpvVector2; begin result:=aValue; end; {$i PasVulkan.Math.TpvVector2.Swizzle.Implementations.inc} function TpvVector2.GetComponent(const aIndex:TpvInt32):TpvScalar; begin result:=RawComponents[aIndex]; end; procedure TpvVector2.SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); begin RawComponents[aIndex]:=aValue; end; function TpvVector2.Perpendicular:TpvVector2; begin result.x:=-y; result.y:=x; end; function TpvVector2.Length:TpvScalar; begin result:=sqrt(sqr(x)+sqr(y)); end; function TpvVector2.SquaredLength:TpvScalar; begin result:=sqr(x)+sqr(y); end; function TpvVector2.Normalize:TpvVector2; var Factor:TpvScalar; begin Factor:=sqrt(sqr(x)+sqr(y)); if Factor<>0.0 then begin Factor:=1.0/Factor; result.x:=x*Factor; result.y:=y*Factor; end else begin result.x:=0.0; result.y:=0.0; end; end; function TpvVector2.DistanceTo(const aToVector:TpvVector2):TpvScalar; begin result:=sqrt(sqr(x-aToVector.x)+sqr(y-aToVector.y)); end; function TpvVector2.Dot(const aWithVector:TpvVector2):TpvScalar; begin result:=(x*aWithVector.x)+(y*aWithVector.y); end; function TpvVector2.Cross(const aVector:TpvVector2):TpvVector2; begin result.x:=(y*aVector.x)-(x*aVector.y); result.y:=(x*aVector.y)-(y*aVector.x); end; function TpvVector2.Lerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; var InvT:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else begin InvT:=1.0-aTime; result.x:=(x*InvT)+(aToVector.x*aTime); result.y:=(y*InvT)+(aToVector.y*aTime); end; end; function TpvVector2.Nlerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; begin result:=self.Lerp(aToVector,aTime).Normalize; end; function TpvVector2.Slerp(const aToVector:TpvVector2;const aTime:TpvScalar):TpvVector2; var DotProduct,Theta,Sinus,Cosinus:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else if self=aToVector then begin result:=aToVector; end else begin DotProduct:=self.Dot(aToVector); if DotProduct<-1.0 then begin DotProduct:=-1.0; end else if DotProduct>1.0 then begin DotProduct:=1.0; end; Theta:=ArcCos(DotProduct)*aTime; Sinus:=0.0; Cosinus:=0.0; SinCos(Theta,Sinus,Cosinus); result:=(self*Cosinus)+((aToVector-(self*DotProduct)).Normalize*Sinus); end; end; function TpvVector2.Sqlerp(const aB,aC,aD:TpvVector2;const aTime:TpvScalar):TpvVector2; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvVector2.Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector2):TpvScalar; var DeltaAB,DeltaCB:TpvVector2; LengthAB,LengthCB:TpvScalar; begin DeltaAB:=self-aOtherFirstVector; DeltaCB:=aOtherSecondVector-aOtherFirstVector; LengthAB:=DeltaAB.Length; LengthCB:=DeltaCB.Length; if (LengthAB=0.0) or (LengthCB=0.0) then begin result:=0.0; end else begin result:=ArcCos(DeltaAB.Dot(DeltaCB)/(LengthAB*LengthCB)); end; end; function TpvVector2.Rotate(const aAngle:TpvScalar):TpvVector2; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(x*Cosinus)-(y*Sinus); result.y:=(y*Cosinus)+(x*Sinus); end; function TpvVector2.Rotate(const aCenter:TpvVector2;const aAngle:TpvScalar):TpvVector2; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(((x-aCenter.x)*Cosinus)-((y-aCenter.y)*Sinus))+aCenter.x; result.y:=(((y-aCenter.y)*Cosinus)+((x-aCenter.x)*Sinus))+aCenter.y; end; constructor TpvVector3.Create(const aX:TpvScalar); begin x:=aX; y:=aX; z:=aX; end; constructor TpvVector3.Create(const aX,aY,aZ:TpvScalar); begin x:=aX; y:=aY; z:=aZ; end; constructor TpvVector3.Create(const aXY:TpvVector2;const aZ:TpvScalar=0.0); begin Vector2:=aXY; z:=aZ; end; class function TpvVector3.InlineableCreate(const aX:TpvScalar):TpvVector3; begin result.x:=aX; result.y:=aX; result.z:=aX; end; class function TpvVector3.InlineableCreate(const aX,aY,aZ:TpvScalar):TpvVector3; begin result.x:=aX; result.y:=aY; result.z:=aZ; end; class function TpvVector3.InlineableCreate(const aXY:TpvVector2;const aZ:TpvScalar=0.0):TpvVector3; begin result.Vector2:=aXY; result.z:=aZ; end; class operator TpvVector3.Implicit(const a:TpvScalar):TpvVector3; begin result.x:=a; result.y:=a; result.z:=a; end; class operator TpvVector3.Explicit(const a:TpvScalar):TpvVector3; begin result.x:=a; result.y:=a; result.z:=a; end; class operator TpvVector3.Equal(const a,b:TpvVector3):boolean; begin result:=SameValue(a.x,b.x) and SameValue(a.y,b.y) and SameValue(a.z,b.z); end; class operator TpvVector3.NotEqual(const a,b:TpvVector3):boolean; begin result:=(not SameValue(a.x,b.x)) or (not SameValue(a.y,b.y)) or (not SameValue(a.z,b.z)); end; class operator TpvVector3.Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const One:TpvFloat=1.0; asm movss xmm0,dword ptr [a+0] movss xmm1,dword ptr [a+4] movss xmm2,dword ptr [a+8] {$if defined(cpu386)} movss xmm3,dword ptr [One] {$elseif defined(fpc)} movss xmm3,dword ptr [rip+One] {$else} movss xmm3,dword ptr [rel One] {$ifend} addss xmm0,xmm3 addss xmm1,xmm3 addss xmm2,xmm3 movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x+1.0; result.y:=a.y+1.0; result.z:=a.z+1.0; end; {$ifend} class operator TpvVector3.Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const One:TpvFloat=1.0; asm movss xmm0,dword ptr [a+0] movss xmm1,dword ptr [a+4] movss xmm2,dword ptr [a+8] {$if defined(cpu386)} movss xmm3,dword ptr [One] {$elseif defined(fpc)} movss xmm3,dword ptr [rip+One] {$else} movss xmm3,dword ptr [rel One] {$ifend} subss xmm0,xmm3 subss xmm1,xmm3 subss xmm2,xmm3 movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x-1.0; result.y:=a.y-1.0; result.z:=a.z-1.0; end; {$ifend} class operator TpvVector3.Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movss xmm0,dword ptr [a+0] movss xmm1,dword ptr [a+4] movss xmm2,dword ptr [a+8] addss xmm0,dword ptr [b+0] addss xmm1,dword ptr [b+4] addss xmm2,dword ptr [b+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; end; {$ifend} class operator TpvVector3.Add(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=a.x+b; result.y:=a.y+b; result.z:=a.z+b; end; class operator TpvVector3.Add(const a:TpvScalar;const b:TpvVector3):TpvVector3; begin result.x:=a+b.x; result.y:=a+b.y; result.z:=a+b.z; end; class operator TpvVector3.Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movss xmm0,dword ptr [a+0] movss xmm1,dword ptr [a+4] movss xmm2,dword ptr [a+8] subss xmm0,dword ptr [b+0] subss xmm1,dword ptr [b+4] subss xmm2,dword ptr [b+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; end; {$ifend} class operator TpvVector3.Subtract(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=a.x-b; result.y:=a.y-b; result.z:=a.z-b; end; class operator TpvVector3.Subtract(const a:TpvScalar;const b:TpvVector3): TpvVector3; begin result.x:=a-b.x; result.y:=a-b.y; result.z:=a-b.z; end; class operator TpvVector3.Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movss xmm0,dword ptr [a] movss xmm1,xmm0 movss xmm2,xmm0 mulss xmm0,dword ptr [b+0] mulss xmm1,dword ptr [b+4] mulss xmm2,dword ptr [b+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x*b.x; result.y:=a.y*b.y; result.z:=a.z*b.z; end; {$ifend} class operator TpvVector3.Multiply(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=a.x*b; result.y:=a.y*b; result.z:=a.z*b; end; class operator TpvVector3.Multiply(const a:TpvScalar;const b:TpvVector3):TpvVector3; begin result.x:=a*b.x; result.y:=a*b.y; result.z:=a*b.z; end; class operator TpvVector3.Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movss xmm0,dword ptr [a] movss xmm1,xmm0 movss xmm2,xmm0 divss xmm0,dword ptr [b+0] divss xmm1,dword ptr [b+4] divss xmm2,dword ptr [b+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; end; {$ifend} class operator TpvVector3.Divide(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; end; class operator TpvVector3.Divide(const a:TpvScalar;const b:TpvVector3):TpvVector3; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; end; class operator TpvVector3.IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movss xmm0,dword ptr [a] movss xmm1,xmm0 movss xmm2,xmm0 divss xmm0,dword ptr [b+0] divss xmm1,dword ptr [b+4] divss xmm2,dword ptr [b+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; end; {$ifend} class operator TpvVector3.IntDivide(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; end; class operator TpvVector3.IntDivide(const a:TpvScalar;const b:TpvVector3):TpvVector3; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; end; class operator TpvVector3.Modulus(const a,b:TpvVector3):TpvVector3; begin result.x:=Modulus(a.x,b.x); result.y:=Modulus(a.y,b.y); result.z:=Modulus(a.z,b.z); end; class operator TpvVector3.Modulus(const a:TpvVector3;const b:TpvScalar):TpvVector3; begin result.x:=Modulus(a.x,b); result.y:=Modulus(a.y,b); result.z:=Modulus(a.z,b); end; class operator TpvVector3.Modulus(const a:TpvScalar;const b:TpvVector3):TpvVector3; begin result.x:=Modulus(a,b.x); result.y:=Modulus(a,b.y); result.z:=Modulus(a,b.z); end; class operator TpvVector3.Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm xorps xmm0,xmm0 xorps xmm1,xmm1 xorps xmm2,xmm2 subss xmm0,dword ptr [a+0] subss xmm1,dword ptr [a+4] subss xmm2,dword ptr [a+8] movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=-a.x; result.y:=-a.y; result.z:=-a.z; end; {$ifend} class operator TpvVector3.Positive(const a:TpvVector3):TpvVector3; begin result:=a; end; {$i PasVulkan.Math.TpvVector3.Swizzle.Implementations.inc} function TpvVector3.GetComponent(const aIndex:TpvInt32):TpvScalar; begin result:=RawComponents[aIndex]; end; procedure TpvVector3.SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); begin RawComponents[aIndex]:=aValue; end; function TpvVector3.Flip:TpvVector3; begin result.x:=x; result.y:=z; result.z:=-y; end; function TpvVector3.Perpendicular:TpvVector3; var v,p:TpvVector3; begin v:=self.Normalize; p.x:=System.abs(v.x); p.y:=System.abs(v.y); p.z:=System.abs(v.z); if (p.x<=p.y) and (p.x<=p.z) then begin p.x:=1.0; p.y:=0.0; p.z:=0.0; end else if (p.y<=p.x) and (p.y<=p.z) then begin p.x:=0.0; p.y:=1.0; p.z:=0.0; end else begin p.x:=0.0; p.y:=0.0; p.z:=1.0; end; result:=p-(v*v.Dot(p)); end; function TpvVector3.OneUnitOrthogonalVector:TpvVector3; var MinimumAxis:TpvInt32; l:TpvScalar; begin if System.abs(x)<System.abs(y) then begin if System.abs(x)<System.abs(z) then begin MinimumAxis:=0; end else begin MinimumAxis:=2; end; end else begin if System.abs(y)<System.abs(z) then begin MinimumAxis:=1; end else begin MinimumAxis:=2; end; end; case MinimumAxis of 0:begin l:=sqrt(sqr(y)+sqr(z)); result.x:=0.0; result.y:=-(z/l); result.z:=y/l; end; 1:begin l:=sqrt(sqr(x)+sqr(z)); result.x:=-(z/l); result.y:=0.0; result.z:=x/l; end; else begin l:=sqrt(sqr(x)+sqr(y)); result.x:=-(y/l); result.y:=x/l; result.z:=0.0; end; end; end; function TpvVector3.Length:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm xorps xmm2,xmm2 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm xorps xmm2,xmm2 //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] //{$else} // movss xmm0,dword ptr [rdi+0] // movss xmm1,dword ptr [rdi+4] // movss xmm2,dword ptr [rdi+8] //{$endif} movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x)+sqr(y)+sqr(z)); end; {$ifend} function TpvVector3.SquaredLength:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm xorps xmm2,xmm2 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm0,xmm1 // xmm0 = ?, ?, ?, z*z + y*y + x*x movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm xorps xmm2,xmm2 //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] (*{$else} movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] {$endif}*) movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm0,xmm1 // xmm0 = ?, ?, ?, z*z + y*y + x*x {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqr(x)+sqr(y)+sqr(z); end; {$ifend} function TpvVector3.Normalize:TpvVector3; {$if defined(SIMD) and defined(cpu386)} asm xorps xmm2,xmm2 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movaps xmm2,xmm0 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 movaps xmm1,xmm2 subps xmm1,xmm2 cmpps xmm1,xmm2,7 andps xmm2,xmm1 movaps xmm0,xmm2 movaps xmm1,xmm2 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$elseif defined(SIMD) and defined(cpux64)} asm xorps xmm2,xmm2 //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] (*{$else} movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] {$endif}*) movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movaps xmm2,xmm0 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 movaps xmm1,xmm2 subps xmm1,xmm2 cmpps xmm1,xmm2,7 andps xmm2,xmm1 movaps xmm0,xmm2 movaps xmm1,xmm2 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} var Factor:TpvScalar; begin Factor:=sqrt(sqr(x)+sqr(y)+sqr(z)); if Factor<>0.0 then begin Factor:=1.0/Factor; result.x:=x*Factor; result.y:=y*Factor; result.z:=z*Factor; end else begin result.x:=0.0; result.y:=0.0; result.z:=0.0; end; end; {$ifend} function TpvVector3.DistanceTo({$ifdef fpc}constref{$else}const{$endif} aToVector:TpvVector3):TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm xorps xmm2,xmm2 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] subss xmm0,dword ptr [edx+0] subss xmm1,dword ptr [edx+4] subss xmm2,dword ptr [edx+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm xorps xmm2,xmm2 //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] subss xmm0,dword ptr [rdx+0] subss xmm1,dword ptr [rdx+4] subss xmm2,dword ptr [rdx+8] (*{$else} movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] subss xmm0,dword ptr [rsi+0] subss xmm1,dword ptr [rsi+4] subss xmm2,dword ptr [rsi+8] {$endif}*) movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x-aToVector.x)+sqr(y-aToVector.y)+sqr(z-aToVector.z)); end; {$ifend} function TpvVector3.Abs:TpvVector3; {$if defined(SIMD) and defined(cpu386)} asm movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] (*{$else} movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] {$endif}*) movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 end; {$else} begin result.x:=System.abs(x); result.y:=System.abs(y); result.z:=System.abs(z); end; {$ifend} function TpvVector3.Dot({$ifdef fpc}constref{$else}const{$endif} aWithVector:TpvVector3):TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] mulss xmm0,dword ptr [edx+0] mulss xmm1,dword ptr [edx+4] mulss xmm2,dword ptr [edx+8] addss xmm0,xmm1 addss xmm0,xmm2 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] mulss xmm0,dword ptr [rdx+0] mulss xmm1,dword ptr [rdx+4] mulss xmm2,dword ptr [rdx+8] (*{$else} movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] mulss xmm0,dword ptr [rsi+0] mulss xmm1,dword ptr [rsi+4] mulss xmm2,dword ptr [rsi+8] {$endif}*) addss xmm0,xmm1 addss xmm0,xmm2 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=(x*aWithVector.x)+(y*aWithVector.y)+(z*aWithVector.z); end; {$ifend} function TpvVector3.AngleTo(const aToVector:TpvVector3):TpvScalar; var d:single; begin d:=sqrt(SquaredLength*aToVector.SquaredLength); if d<>0.0 then begin result:=Dot(aToVector)/d; end else begin result:=0.0; end end; function TpvVector3.Cross({$ifdef fpc}constref{$else}const{$endif} aOtherVector:TpvVector3):TpvVector3; {$if defined(SIMD) and defined(cpu386)} asm {$ifdef SSEVector3CrossOtherVariant} xorps xmm2,xmm2 xorps xmm4,xmm4 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm2,dword ptr [edx+0] movss xmm3,dword ptr [edx+4] movss xmm4,dword ptr [edx+8] movlhps xmm2,xmm3 shufps xmm2,xmm4,$88 movaps xmm1,xmm0 movaps xmm3,xmm2 shufps xmm0,xmm0,$c9 shufps xmm1,xmm1,$d2 shufps xmm2,xmm2,$d2 shufps xmm3,xmm3,$c9 mulps xmm0,xmm2 mulps xmm1,xmm3 subps xmm0,xmm1 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [ecx+0],xmm0 movss dword ptr [ecx+4],xmm1 movss dword ptr [ecx+8],xmm2 {$else} xorps xmm2,xmm2 xorps xmm3,xmm3 movss xmm0,dword ptr [eax+0] movss xmm1,dword ptr [eax+4] movss xmm2,dword ptr [eax+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm1,dword ptr [edx+0] movss xmm2,dword ptr [edx+4] movss xmm3,dword ptr [edx+8] movlhps xmm1,xmm2 shufps xmm1,xmm3,$88 movaps xmm2,xmm0 movaps xmm3,xmm1 shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 movaps xmm0,xmm2 movaps xmm1,xmm2 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [ecx+0],xmm0 movss dword ptr [ecx+4],xmm1 movss dword ptr [ecx+8],xmm2 {$endif} end; {$elseif defined(SIMD) and defined(cpux64)} asm {$ifdef SSEVector3CrossOtherVariant} //{$ifdef Windows} xorps xmm2,xmm2 xorps xmm4,xmm4 movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm2,dword ptr [r8+0] movss xmm3,dword ptr [r8+4] movss xmm4,dword ptr [r8+8] movlhps xmm2,xmm3 shufps xmm2,xmm4,$88 (*{$else} xorps xmm2,xmm2 xorps xmm4,xmm4 movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm2,dword ptr [rsi+0] movss xmm3,dword ptr [rsi+4] movss xmm4,dword ptr [rsi+8] movlhps xmm2,xmm3 shufps xmm2,xmm4,$88 {$endif}*) movaps xmm1,xmm0 movaps xmm3,xmm2 shufps xmm0,xmm0,$c9 shufps xmm1,xmm1,$d2 shufps xmm2,xmm2,$d2 shufps xmm3,xmm3,$c9 mulps xmm0,xmm2 mulps xmm1,xmm3 subps xmm0,xmm1 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa //{$ifdef Windows} movss dword ptr [rdx+0],xmm0 movss dword ptr [rdx+4],xmm1 movss dword ptr [rdx+8],xmm2 (*{$else} movss dword ptr [rax+0],xmm0 movss dword ptr [rax+4],xmm1 movss dword ptr [rax+8],xmm2 {$endif}*) {$else} //{$ifdef Windows} xorps xmm2,xmm2 xorps xmm3,xmm3 movss xmm0,dword ptr [rcx+0] movss xmm1,dword ptr [rcx+4] movss xmm2,dword ptr [rcx+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm1,dword ptr [r8+0] movss xmm2,dword ptr [r8+4] movss xmm3,dword ptr [r8+8] movlhps xmm1,xmm2 shufps xmm1,xmm3,$88 (*{$else} xorps xmm2,xmm2 xorps xmm3,xmm3 movss xmm0,dword ptr [rdi+0] movss xmm1,dword ptr [rdi+4] movss xmm2,dword ptr [rdi+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 movss xmm1,dword ptr [rsi+0] movss xmm2,dword ptr [rsi+4] movss xmm3,dword ptr [rsi+8] movlhps xmm1,xmm2 shufps xmm1,xmm3,$88 {$endif}*) movaps xmm2,xmm0 movaps xmm3,xmm1 shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 movaps xmm0,xmm2 movaps xmm1,xmm2 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa //{$ifdef Windows} movss dword ptr [rdx+0],xmm0 movss dword ptr [rdx+4],xmm1 movss dword ptr [rdx+8],xmm2 (*{$else} movss dword ptr [rax+0],xmm0 movss dword ptr [rax+4],xmm1 movss dword ptr [rax+8],xmm2 {$endif}*) {$endif} end; {$else} begin result.x:=(y*aOtherVector.z)-(z*aOtherVector.y); result.y:=(z*aOtherVector.x)-(x*aOtherVector.z); result.z:=(x*aOtherVector.y)-(y*aOtherVector.x); end; {$ifend} function TpvVector3.Lerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; var InvT:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else begin InvT:=1.0-aTime; result:=(self*InvT)+(aToVector*aTime); end; end; function TpvVector3.Nlerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; begin result:=self.Lerp(aToVector,aTime).Normalize; end; function TpvVector3.Slerp(const aToVector:TpvVector3;const aTime:TpvScalar):TpvVector3; var DotProduct,Theta,Sinus,Cosinus:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else if self=aToVector then begin result:=aToVector; end else begin DotProduct:=self.Dot(aToVector); if DotProduct<-1.0 then begin DotProduct:=-1.0; end else if DotProduct>1.0 then begin DotProduct:=1.0; end; Theta:=ArcCos(DotProduct)*aTime; Sinus:=0.0; Cosinus:=0.0; SinCos(Theta,Sinus,Cosinus); result:=(self*Cosinus)+((aToVector-(self*DotProduct)).Normalize*Sinus); end; end; function TpvVector3.Sqlerp(const aB,aC,aD:TpvVector3;const aTime:TpvScalar):TpvVector3; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvVector3.Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector3):TpvScalar; var DeltaAB,DeltaCB:TpvVector3; LengthAB,LengthCB:TpvScalar; begin DeltaAB:=self-aOtherFirstVector; DeltaCB:=aOtherSecondVector-aOtherFirstVector; LengthAB:=DeltaAB.Length; LengthCB:=DeltaCB.Length; if (LengthAB=0.0) or (LengthCB=0.0) then begin result:=0.0; end else begin result:=ArcCos(DeltaAB.Dot(DeltaCB)/(LengthAB*LengthCB)); end; end; function TpvVector3.RotateX(const aAngle:TpvScalar):TpvVector3; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=x; result.y:=(y*Cosinus)-(z*Sinus); result.z:=(y*Sinus)+(z*Cosinus); end; function TpvVector3.RotateY(const aAngle:TpvScalar):TpvVector3; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(z*Sinus)+(x*Cosinus); result.y:=y; result.z:=(z*Cosinus)-(x*Sinus); end; function TpvVector3.RotateZ(const aAngle:TpvScalar):TpvVector3; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(x*Cosinus)-(y*Sinus); result.y:=(x*Sinus)+(y*Cosinus); result.z:=z; end; function TpvVector3.ProjectToBounds(const aMinVector,aMaxVector:TpvVector3):TpvScalar; begin if x<0.0 then begin result:=x*aMaxVector.x; end else begin result:=x*aMinVector.x; end; if y<0.0 then begin result:=result+(y*aMaxVector.y); end else begin result:=result+(y*aMinVector.y); end; if z<0.0 then begin result:=result+(z*aMaxVector.z); end else begin result:=result+(z*aMinVector.z); end; end; constructor TpvVector4.Create(const aX:TpvScalar); begin x:=aX; y:=aX; z:=aX; w:=aX; end; constructor TpvVector4.Create(const aX,aY,aZ,aW:TpvScalar); begin x:=aX; y:=aY; z:=aZ; w:=aW; end; constructor TpvVector4.Create(const aXY:TpvVector2;const aZ:TpvScalar=0.0;const aW:TpvScalar=1.0); begin x:=aXY.x; y:=aXY.y; z:=aZ; w:=aW; end; constructor TpvVector4.Create(const aXYZ:TpvVector3;const aW:TpvScalar=1.0); begin x:=aXYZ.x; y:=aXYZ.y; z:=aXYZ.z; w:=aW; end; class function TpvVector4.InlineableCreate(const aX:TpvScalar):TpvVector4; begin result.x:=aX; result.y:=aX; result.z:=aX; result.w:=aX; end; class function TpvVector4.InlineableCreate(const aX,aY,aZ,aW:TpvScalar):TpvVector4; begin result.x:=aX; result.y:=aY; result.z:=aZ; result.w:=aW; end; class function TpvVector4.InlineableCreate(const aXY:TpvVector2;const aZ:TpvScalar=0.0;const aW:TpvScalar=0.0):TpvVector4; begin result.Vector2:=aXY; result.z:=aZ; result.w:=aW; end; class function TpvVector4.InlineableCreate(const aXYZ:TpvVector3;const aW:TpvScalar=0.0):TpvVector4; begin result.Vector3:=aXYZ; result.w:=aW; end; class operator TpvVector4.Implicit(const a:TpvScalar):TpvVector4; begin result.x:=a; result.y:=a; result.z:=a; result.w:=a; end; class operator TpvVector4.Explicit(const a:TpvScalar):TpvVector4; begin result.x:=a; result.y:=a; result.z:=a; result.w:=a; end; class operator TpvVector4.Equal(const a,b:TpvVector4):boolean; begin result:=SameValue(a.x,b.x) and SameValue(a.y,b.y) and SameValue(a.z,b.z) and SameValue(a.w,b.w); end; class operator TpvVector4.NotEqual(const a,b:TpvVector4):boolean; begin result:=(not SameValue(a.x,b.x)) or (not SameValue(a.y,b.y)) or (not SameValue(a.z,b.z)) or (not SameValue(a.w,b.w)); end; class operator TpvVector4.Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if defined(SIMD) and defined(cpu386)} const One:TpvVector4=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [One] addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} const One:TpvVector4=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] {$ifdef fpc} movups xmm1,dqword ptr [rip+One] {$else} movups xmm1,dqword ptr [rel One] {$endif} addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x+1.0; result.y:=a.y+1.0; result.z:=a.z+1.0; result.w:=a.w+1.0; end; {$ifend} class operator TpvVector4.Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if defined(SIMD) and defined(cpu386)} const One:TpvVector4=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [One] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} const One:TpvVector4=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] {$ifdef fpc} movups xmm1,dqword ptr [rip+One] {$else} movups xmm1,dqword ptr [rel One] {$endif} subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x-1.0; result.y:=a.y-1.0; result.z:=a.z-1.0; result.w:=a.w-1.0; end; {$ifend} class operator TpvVector4.Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; result.w:=a.w+b.w; end; {$ifend} class operator TpvVector4.Add(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=a.x+b; result.y:=a.y+b; result.z:=a.z+b; result.w:=a.w+b; end; class operator TpvVector4.Add(const a:TpvScalar;const b:TpvVector4):TpvVector4; begin result.x:=a+b.x; result.y:=a+b.y; result.z:=a+b.z; result.w:=a+b.w; end; class operator TpvVector4.Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; result.w:=a.w-b.w; end; {$ifend} class operator TpvVector4.Subtract(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=a.x-b; result.y:=a.y-b; result.z:=a.z-b; result.w:=a.w-b; end; class operator TpvVector4.Subtract(const a:TpvScalar;const b:TpvVector4): TpvVector4; begin result.x:=a-b.x; result.y:=a-b.y; result.z:=a-b.z; result.w:=a-b.w; end; class operator TpvVector4.Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] mulps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x*b.x; result.y:=a.y*b.y; result.z:=a.z*b.z; result.w:=a.w*b.w; end; {$ifend} class operator TpvVector4.Multiply(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=a.x*b; result.y:=a.y*b; result.z:=a.z*b; result.w:=a.w*b; end; class operator TpvVector4.Multiply(const a:TpvScalar;const b:TpvVector4):TpvVector4; begin result.x:=a*b.x; result.y:=a*b.y; result.z:=a*b.z; result.w:=a*b.w; end; class operator TpvVector4.Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] divps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; result.w:=a.w/b.w; end; {$ifend} class operator TpvVector4.Divide(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; result.w:=a.w/b; end; class operator TpvVector4.Divide(const a:TpvScalar;const b:TpvVector4):TpvVector4; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; result.w:=a/b.z; end; class operator TpvVector4.IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] divps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; result.w:=a.w/b.w; end; {$ifend} class operator TpvVector4.IntDivide(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; result.w:=a.w/b; end; class operator TpvVector4.IntDivide(const a:TpvScalar;const b:TpvVector4):TpvVector4; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; result.w:=a/b.w; end; class operator TpvVector4.Modulus(const a,b:TpvVector4):TpvVector4; begin result.x:=Modulus(a.x,b.x); result.y:=Modulus(a.y,b.y); result.z:=Modulus(a.z,b.z); result.w:=Modulus(a.w,b.w); end; class operator TpvVector4.Modulus(const a:TpvVector4;const b:TpvScalar):TpvVector4; begin result.x:=Modulus(a.x,b); result.y:=Modulus(a.y,b); result.z:=Modulus(a.z,b); result.w:=Modulus(a.w,b); end; class operator TpvVector4.Modulus(const a:TpvScalar;const b:TpvVector4):TpvVector4; begin result.x:=Modulus(a,b.x); result.y:=Modulus(a,b.y); result.z:=Modulus(a,b.z); result.w:=Modulus(a,b.w); end; class operator TpvVector4.Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm xorps xmm0,xmm0 movups xmm1,dqword ptr [a] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=-a.x; result.y:=-a.y; result.z:=-a.z; result.w:=-a.w; end; {$ifend} class operator TpvVector4.Positive(const a:TpvVector4):TpvVector4; begin result:=a; end; {$i PasVulkan.Math.TpvVector4.Swizzle.Implementations.inc} function TpvVector4.GetComponent(const aIndex:TpvInt32):TpvScalar; begin result:=RawComponents[aIndex]; end; procedure TpvVector4.SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); begin RawComponents[aIndex]:=aValue; end; function TpvVector4.Flip:TpvVector4; begin result.x:=x; result.y:=z; result.z:=-y; result.w:=w; end; function TpvVector4.Perpendicular:TpvVector4; var v,p:TpvVector4; begin v:=self.Normalize; p.x:=System.abs(v.x); p.y:=System.abs(v.y); p.z:=System.abs(v.z); p.w:=System.abs(v.w); if (p.x<=p.y) and (p.x<=p.z) and (p.x<=p.w) then begin p.x:=1.0; p.y:=0.0; p.z:=0.0; p.w:=0.0; end else if (p.y<=p.x) and (p.y<=p.z) and (p.y<=p.w) then begin p.x:=0.0; p.y:=1.0; p.z:=0.0; p.w:=0.0; end else if (p.z<=p.x) and (p.z<=p.y) and (p.z<=p.w) then begin p.x:=0.0; p.y:=0.0; p.z:=0.0; p.w:=1.0; end else begin p.x:=0.0; p.y:=0.0; p.z:=1.0; p.w:=0.0; end; result:=p-(v*v.Dot(p)); end; function TpvVector4.Length:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w)); end; {$ifend} function TpvVector4.SquaredLength:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqr(x)+sqr(y)+sqr(z)+sqr(w); end; {$ifend} function TpvVector4.Normalize:TpvVector4; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movaps xmm2,xmm0 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 movaps xmm1,xmm2 subps xmm1,xmm2 cmpps xmm1,xmm2,7 andps xmm2,xmm1 movups dqword ptr [edx],xmm2 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) movaps xmm2,xmm0 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 movaps xmm1,xmm2 subps xmm1,xmm2 cmpps xmm1,xmm2,7 andps xmm2,xmm1 //{$ifdef Windows} movups dqword ptr [rdx],xmm2 (*{$else} movups dqword ptr [rax],xmm2 {$endif}*) end; {$else} var Factor:TpvScalar; begin Factor:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w)); if Factor<>0.0 then begin Factor:=1.0/Factor; result.x:=x*Factor; result.y:=y*Factor; result.z:=z*Factor; result.w:=w*Factor; end else begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=0.0; end; end; {$ifend} function TpvVector4.DistanceTo({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [edx] subps xmm0,xmm1 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm1,dqword ptr [rdx] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm1,dqword ptr [rsi] {$endif}*) subps xmm0,xmm1 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x-b.x)+sqr(y-b.y)+sqr(z-b.z)+sqr(w-b.w)); end; {$ifend} function TpvVector4.Abs:TpvVector4; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 movups dqword ptr [edx],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 //{$ifdef Windows} movups dqword ptr [rdx],xmm0 (*{$else} movups dqword ptr [rax],xmm0 {$endif}*) end; {$else} begin result.x:=System.abs(x); result.y:=System.abs(y); result.z:=System.abs(z); result.w:=System.abs(w); end; {$ifend} function TpvVector4.Dot({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [edx] mulps xmm0,xmm1 movaps xmm1,xmm0 shufps xmm1,xmm0,$b1 addps xmm0,xmm1 movhlps xmm1,xmm0 addss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm1,dqword ptr [rdx] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm1,dqword ptr [rsi] {$endif}*) mulps xmm0,xmm1 movaps xmm1,xmm0 shufps xmm1,xmm0,$b1 addps xmm0,xmm1 movhlps xmm1,xmm0 addss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=(x*b.x)+(y*b.y)+(z*b.z)+(w*b.w); end; {$ifend} function TpvVector4.AngleTo(const b:TpvVector4):TpvScalar; var d:single; begin d:=sqrt(SquaredLength*b.SquaredLength); if d<>0.0 then begin result:=Dot(b)/d; end else begin result:=0.0; end end; function TpvVector4.Cross({$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if defined(SIMD) and defined(cpu386)} const AndMask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); OrMask:array[0..3] of TpvUInt32=($00000000,$00000000,$00000000,$3f800000); asm {$ifdef SSEVector3CrossOtherVariant} movups xmm0,dqword ptr [eax] movups xmm2,dqword ptr [edx] movups xmm4,dqword ptr [AndMask] movups xmm5,dqword ptr [OrMask] andps xmm0,xmm4 andps xmm2,xmm4 movaps xmm1,xmm0 movaps xmm3,xmm2 shufps xmm0,xmm0,$c9 shufps xmm1,xmm1,$d2 shufps xmm2,xmm2,$d2 shufps xmm3,xmm3,$c9 mulps xmm0,xmm2 mulps xmm1,xmm3 subps xmm0,xmm1 andps xmm0,xmm4 orps xmm0,xmm5 movups dqword ptr [ecx],xmm0 {$else} movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [edx] movups xmm4,dqword ptr [AndMask] movups xmm5,dqword ptr [OrMask] andps xmm0,xmm4 andps xmm1,xmm4 movaps xmm2,xmm0 movaps xmm3,xmm1 shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 andps xmm2,xmm4 orps xmm2,xmm5 movups dqword ptr [ecx],xmm2 {$endif} end; {$elseif defined(SIMD) and defined(cpux64)} const AndMask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); OrMask:array[0..3] of TpvUInt32=($00000000,$00000000,$00000000,$3f800000); asm {$ifdef SSEVector3CrossOtherVariant} //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm2,dqword ptr [r8] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm2,dqword ptr [rsi] {$endif}*) {$ifdef fpc} movups xmm4,dqword ptr [rip+AndMask] movups xmm5,dqword ptr [rip+OrMask] {$else} movups xmm4,dqword ptr [rel AndMask] movups xmm5,dqword ptr [rel OrMask] {$endif} andps xmm0,xmm4 andps xmm2,xmm4 movaps xmm1,xmm0 movaps xmm3,xmm2 shufps xmm0,xmm0,$c9 shufps xmm1,xmm1,$d2 shufps xmm2,xmm2,$d2 shufps xmm3,xmm3,$c9 mulps xmm0,xmm2 mulps xmm1,xmm3 subps xmm0,xmm1 andps xmm0,xmm4 orps xmm0,xmm5 //{$ifdef Windows} movups dqword ptr [rdx],xmm0 (*{$else} movups dqword ptr [rax],xmm0 {$endif}*) {$else} //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm1,dqword ptr [r8] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm1,dqword ptr [rsi] {$endif}*) {$ifdef fpc} movups xmm4,dqword ptr [rip+AndMask] movups xmm5,dqword ptr [rip+OrMask] {$else} movups xmm4,dqword ptr [rel AndMask] movups xmm5,dqword ptr [rel OrMask] {$endif} andps xmm0,xmm4 andps xmm1,xmm4 movaps xmm2,xmm0 movaps xmm3,xmm1 shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 andps xmm2,xmm4 orps xmm2,xmm5 //{$ifdef Windows} movups dqword ptr [rdx],xmm2 (*{$else} movups dqword ptr [rax],xmm2 {$endif}*) {$endif} end; {$else} begin result.x:=(y*b.z)-(z*b.y); result.y:=(z*b.x)-(x*b.z); result.z:=(x*b.y)-(y*b.x); result.w:=1.0; end; {$ifend} function TpvVector4.Lerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; var InvT:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else begin InvT:=1.0-aTime; result.x:=(x*InvT)+(aToVector.x*aTime); result.y:=(y*InvT)+(aToVector.y*aTime); result.z:=(z*InvT)+(aToVector.z*aTime); result.w:=(w*InvT)+(aToVector.w*aTime); end; end; function TpvVector4.Nlerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; begin result:=self.Lerp(aToVector,aTime).Normalize; end; function TpvVector4.Slerp(const aToVector:TpvVector4;const aTime:TpvScalar):TpvVector4; var DotProduct,Theta,Sinus,Cosinus:TpvScalar; begin if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToVector; end else if self=aToVector then begin result:=aToVector; end else begin DotProduct:=self.Dot(aToVector); if DotProduct<-1.0 then begin DotProduct:=-1.0; end else if DotProduct>1.0 then begin DotProduct:=1.0; end; Theta:=ArcCos(DotProduct)*aTime; Sinus:=0.0; Cosinus:=0.0; SinCos(Theta,Sinus,Cosinus); result:=(self*Cosinus)+((aToVector-(self*DotProduct)).Normalize*Sinus); end; end; function TpvVector4.Sqlerp(const aB,aC,aD:TpvVector4;const aTime:TpvScalar):TpvVector4; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvVector4.Angle(const aOtherFirstVector,aOtherSecondVector:TpvVector4):TpvScalar; var DeltaAB,DeltaCB:TpvVector4; LengthAB,LengthCB:TpvScalar; begin DeltaAB:=self-aOtherFirstVector; DeltaCB:=aOtherSecondVector-aOtherFirstVector; LengthAB:=DeltaAB.Length; LengthCB:=DeltaCB.Length; if (LengthAB=0.0) or (LengthCB=0.0) then begin result:=0.0; end else begin result:=ArcCos(DeltaAB.Dot(DeltaCB)/(LengthAB*LengthCB)); end; end; function TpvVector4.RotateX(const aAngle:TpvScalar):TpvVector4; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=x; result.y:=(y*Cosinus)-(z*Sinus); result.z:=(y*Sinus)+(z*Cosinus); result.w:=w; end; function TpvVector4.RotateY(const aAngle:TpvScalar):TpvVector4; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(z*Sinus)+(x*Cosinus); result.y:=y; result.z:=(z*Cosinus)-(x*Sinus); result.w:=w; end; function TpvVector4.RotateZ(const aAngle:TpvScalar):TpvVector4; var Sinus,Cosinus:TpvScalar; begin Sinus:=0.0; Cosinus:=0.0; SinCos(aAngle,Sinus,Cosinus); result.x:=(x*Cosinus)-(y*Sinus); result.y:=(x*Sinus)+(y*Cosinus); result.z:=z; result.w:=w; end; function TpvVector4.Rotate(const aAngle:TpvScalar;const aAxis:TpvVector3):TpvVector4; begin result:=TpvMatrix4x4.CreateRotate(aAngle,aAxis)*self; end; function TpvVector4.ProjectToBounds(const aMinVector,aMaxVector:TpvVector4):TpvScalar; begin if x<0.0 then begin result:=x*aMaxVector.x; end else begin result:=x*aMinVector.x; end; if y<0.0 then begin result:=result+(y*aMaxVector.y); end else begin result:=result+(y*aMinVector.y); end; if z<0.0 then begin result:=result+(z*aMaxVector.z); end else begin result:=result+(z*aMinVector.z); end; if w<0.0 then begin result:=result+(w*aMaxVector.w); end else begin result:=result+(w*aMinVector.w); end; end; {$i PasVulkan.Math.TpvVector2Helper.Swizzle.Implementations.inc} {$i PasVulkan.Math.TpvVector3Helper.Swizzle.Implementations.inc} {$i PasVulkan.Math.TpvVector4Helper.Swizzle.Implementations.inc} constructor TpvPlane.Create(const aNormal:TpvVector3;const aDistance:TpvScalar); begin Normal:=aNormal; Distance:=aDistance; end; constructor TpvPlane.Create(const aX,aY,aZ,aDistance:TpvScalar); begin Normal.x:=aX; Normal.y:=aY; Normal.z:=aZ; Distance:=aDistance; end; constructor TpvPlane.Create(const aA,aB,aC:TpvVector3); begin Normal:=((aB-aA).Cross(aC-aA)).Normalize; Distance:=-((Normal.x*aA.x)+(Normal.y*aA.y)+(Normal.z*aA.z)); end; constructor TpvPlane.Create(const aA,aB,aC:TpvVector4); begin Normal:=((aB.xyz-aA.xyz).Cross(aC.xyz-aA.xyz)).Normalize; Distance:=-((Normal.x*aA.x)+(Normal.y*aA.y)+(Normal.z*aA.z)); end; constructor TpvPlane.Create(const aVector:TpvVector4); begin Normal.x:=aVector.x; Normal.y:=aVector.y; Normal.z:=aVector.z; Distance:=aVector.w; end; function TpvPlane.ToVector:TpvVector4; begin result.x:=Normal.x; result.y:=Normal.y; result.z:=Normal.z; result.w:=Distance; end; function TpvPlane.Normalize:TpvPlane; var l:TpvScalar; begin l:=Normal.Length; if l>0.0 then begin l:=1.0/l; result.Normal:=Normal*l; result.Distance:=Distance*l; end else begin result.Normal:=0.0; result.Distance:=0.0; end; end; function TpvPlane.DistanceTo(const aPoint:TpvVector3):TpvScalar; begin result:=Normal.Dot(aPoint)+Distance; end; function TpvPlane.DistanceTo(const aPoint:TpvVector4):TpvScalar; begin result:=Normal.Dot(aPoint.xyz)+(aPoint.w*Distance); end; procedure TpvPlane.ClipSegment(const aP0,aP1:TpvVector3;out aClipped:TpvVector3); begin aClipped:=aP0+((aP1-aP0).Normalize*(-DistanceTo(aP0))); //aClipped:=aP0+((aP1-aP0)*((-DistanceTo(aP0))/Normal.Dot(aP1-aP0))); end; function TpvPlane.ClipSegmentClosest(const aP0,aP1:TpvVector3;out aClipped0,aClipped1:TpvVector3):TpvInt32; var d0,d1:TpvScalar; begin d0:=-DistanceTo(aP0); d1:=-DistanceTo(aP1); if (d0>(-EPSILON)) and (d1>(-EPSILON)) then begin if d0<d1 then begin result:=0; aClipped0:=aP0; aClipped1:=aP1; end else begin result:=1; aClipped0:=aP1; aClipped1:=aP0; end; end else if (d0<EPSILON) and (d1<EPSILON) then begin if d0>d1 then begin result:=2; aClipped0:=aP0; aClipped1:=aP1; end else begin result:=3; aClipped0:=aP1; aClipped1:=aP0; end; end else begin if d0<d1 then begin result:=4; aClipped1:=aP0; end else begin result:=5; aClipped1:=aP1; end; aClipped0:=aP1-aP0; aClipped0:=aP0+(aClipped0*((-d0)/Normal.Dot(aClipped0))); end; end; function TpvPlane.ClipSegmentLine(var aP0,aP1:TpvVector3):boolean; var d0,d1:TpvScalar; o0,o1:boolean; begin d0:=DistanceTo(aP0); d1:=DistanceTo(aP1); o0:=d0<0.0; o1:=d1<0.0; if o0 and o1 then begin // Both points are below which means that the whole line segment is below => return false result:=false; end else begin // At least one point is above or in the plane which means that the line segment is above => return true if (o0<>o1) and (abs(d0-d1)>EPSILON) then begin if o0 then begin // aP1 is above or in the plane which means that the line segment is above => clip l0 aP0:=aP0+((aP1-aP0)*(d0/(d0-d1))); end else begin // aP0 is above or in the plane which means that the line segment is above => clip l1 aP1:=aP0+((aP1-aP0)*(d0/(d0-d1))); end; end else begin // Near parallel case => no clipping end; result:=true; end; end; constructor TpvQuaternion.Create(const aX:TpvScalar); begin x:=aX; y:=aX; z:=aX; w:=aX; end; constructor TpvQuaternion.Create(const aX,aY,aZ,aW:TpvScalar); begin x:=aX; y:=aY; z:=aZ; w:=aW; end; constructor TpvQuaternion.Create(const aVector:TpvVector4); begin Vector:=aVector; end; constructor TpvQuaternion.CreateFromScaledAngleAxis(const aScaledAngleAxis:TpvVector3); var Angle,Sinus,Coefficent:TpvScalar; t:TpvVector3; begin t:=aScaledAngleAxis*0.5; Angle:=sqrt(sqr(t.x)+sqr(t.y)+sqr(t.z)); Sinus:=sin(Angle); w:=cos(Angle); if System.Abs(Sinus)>1e-6 then begin Coefficent:=Sinus/Angle; x:=t.x*Coefficent; y:=t.y*Coefficent; z:=t.z*Coefficent; end else begin x:=t.x; y:=t.y; z:=t.z; end; end; constructor TpvQuaternion.CreateFromAngularVelocity(const aAngularVelocity:TpvVector3); var Magnitude,Sinus,Cosinus,SinusGain:TpvScalar; begin Magnitude:=aAngularVelocity.Length; if Magnitude<EPSILON then begin x:=0.0; y:=0.0; z:=0.0; w:=1.0; end else begin SinCos(Magnitude*0.5,Sinus,Cosinus); SinusGain:=Sinus/Magnitude; x:=aAngularVelocity.x*SinusGain; y:=aAngularVelocity.y*SinusGain; z:=aAngularVelocity.z*SinusGain; w:=Cosinus; end; end; constructor TpvQuaternion.CreateFromAngleAxis(const aAngle:TpvScalar;const aAxis:TpvVector3); var s:TpvScalar; begin {s:=sin(aAngle*0.5); w:=cos(aAngle*0.5);} SinCos(aAngle*0.5,s,w); x:=aAxis.x*s; y:=aAxis.y*s; z:=aAxis.z*s; self:=self.Normalize; end; constructor TpvQuaternion.CreateFromEuler(const aPitch,aYaw,aRoll:TpvScalar); var sp,sy,sr,cp,cy,cr:TpvScalar; begin // Order of rotations: aRoll (Z), aPitch (X), aYaw (Y) SinCos(aPitch*0.5,sp,cp); SinCos(aYaw*0.5,sy,cy); SinCos(aRoll*0.5,sr,cr); {sp:=sin(aPitch*0.5); sy:=sin(aYaw*0.5); sr:=sin(aRoll*0.5); cp:=cos(aPitch*0.5); cy:=cos(aYaw*0.5); cr:=cos(aRoll*0.5);} Vector:=TpvVector4.Create((sp*cy*cr)+(cp*sy*sr), (cp*sy*cr)-(sp*cy*sr), (cp*cy*sr)-(sp*sy*cr), (cp*cy*cr)+(sp*sy*sr) ).Normalize; end; constructor TpvQuaternion.CreateFromEuler(const aAngles:TpvVector3); var sp,sy,sr,cp,cy,cr:TpvScalar; begin // Order of rotations: Roll (Z), Pitch (X), Yaw (Y) SinCos(aAngles.Pitch*0.5,sp,cp); SinCos(aAngles.Yaw*0.5,sy,cy); SinCos(aAngles.Roll*0.5,sr,cr); {sp:=sin(aAngles.Pitch*0.5); sy:=sin(aAngles.Yaw*0.5); sr:=sin(aAngles.Roll*0.5); cp:=cos(aAngles.Pitch*0.5); cy:=cos(aAngles.Yaw*0.5); cr:=cos(aAngles.Roll*0.5);//} Vector:=TpvVector4.Create((sp*cy*cr)+(cp*sy*sr), (cp*sy*cr)-(sp*cy*sr), (cp*cy*sr)-(sp*sy*cr), (cp*cy*cr)+(sp*sy*sr) ).Normalize; end; constructor TpvQuaternion.CreateFromNormalizedSphericalCoordinates(const aNormalizedSphericalCoordinates:TpvNormalizedSphericalCoordinates); begin x:=cos(aNormalizedSphericalCoordinates.Latitude)*sin(aNormalizedSphericalCoordinates.Longitude); y:=sin(aNormalizedSphericalCoordinates.Latitude); z:=cos(aNormalizedSphericalCoordinates.Latitude)*cos(aNormalizedSphericalCoordinates.Longitude); w:=0.0; end; constructor TpvQuaternion.CreateFromToRotation(const aFromDirection,aToDirection:TpvVector3); begin Vector.xyz:=aFromDirection.Normalize.Cross(aToDirection.Normalize); Vector.w:=sqrt((sqr(aFromDirection.x)+sqr(aFromDirection.y)+sqr(aFromDirection.z))* (sqr(aToDirection.x)+sqr(aToDirection.y)+sqr(aToDirection.z)))+ ((aFromDirection.x*aToDirection.x)+(aFromDirection.y*aToDirection.y)+(aFromDirection.z*aToDirection.z)); end; constructor TpvQuaternion.CreateFromCols(const aC0,aC1,aC2:TpvVector3); begin if aC2.z<0.0 then begin if aC0.x>aC1.y then begin self:=TpvQuaternion.Create(((1.0+aC0.x)-aC1.y)-aC2.z,aC0.y+aC1.x,aC2.x+aC0.Z,aC1.z-aC2.y).Normalize; end else begin self:=TpvQuaternion.Create(aC0.y+aC1.x,((1.0-aC0.x)+aC1.y)-aC2.z,aC1.z+aC2.y,aC2.x-aC0.z).Normalize; end; end else begin if aC0.x<-aC1.y then begin self:=TpvQuaternion.Create(aC2.x+aC0.z,aC1.z+aC2.y,((1.0-aC0.x)-aC1.y)+aC2.z,aC0.y-aC1.x).Normalize; end else begin self:=TpvQuaternion.Create(aC1.z-aC2.y,aC2.x-aC0.z,aC0.y-aC1.x,((1.0+aC0.x)+aC1.y)+aC2.z).Normalize; end; end; end; constructor TpvQuaternion.CreateFromXY(const aX,aY:TpvVector3); var c0,c1,c2:TpvVector3; begin c2:=(aX.Cross(aY)).Normalize; c1:=(c2.Cross(aX)).Normalize; c0:=aX.Normalize; self:=TpvQuaternion.CreateFromCols(c0,c1,c2); end; class operator TpvQuaternion.Implicit(const a:TpvScalar):TpvQuaternion; begin result.x:=a; result.y:=a; result.z:=a; result.w:=a; end; class operator TpvQuaternion.Explicit(const a:TpvScalar):TpvQuaternion; begin result.x:=a; result.y:=a; result.z:=a; result.w:=a; end; class operator TpvQuaternion.Equal(const a,b:TpvQuaternion):boolean; begin result:=SameValue(a.x,b.x) and SameValue(a.y,b.y) and SameValue(a.z,b.z) and SameValue(a.w,b.w); end; class operator TpvQuaternion.NotEqual(const a,b:TpvQuaternion):boolean; begin result:=(not SameValue(a.x,b.x)) or (not SameValue(a.y,b.y)) or (not SameValue(a.z,b.z)) or (not SameValue(a.w,b.w)); end; class operator TpvQuaternion.Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} const One:TpvQuaternion=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [One] addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} const One:TpvQuaternion=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] {$ifdef fpc} movups xmm1,dqword ptr [rip+One] {$else} movups xmm1,dqword ptr [rel One] {$endif} addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x+1.0; result.y:=a.y+1.0; result.z:=a.z+1.0; result.w:=a.w+1.0; end; {$ifend} class operator TpvQuaternion.Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} const One:TpvQuaternion=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [One] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} const One:TpvQuaternion=(x:1.0;y:1.0;z:1.0;w:1.0); asm movups xmm0,dqword ptr [a] {$ifdef fpc} movups xmm1,dqword ptr [rip+One] {$else} movups xmm1,dqword ptr [rel One] {$endif} subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x-1.0; result.y:=a.y-1.0; result.z:=a.z-1.0; result.w:=a.w-1.0; end; {$ifend} class operator TpvQuaternion.Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] addps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x+b.x; result.y:=a.y+b.y; result.z:=a.z+b.z; result.w:=a.w+b.w; end; {$ifend} class operator TpvQuaternion.Add(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=a.x+b; result.y:=a.y+b; result.z:=a.z+b; result.w:=a.w+b; end; class operator TpvQuaternion.Add(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; begin result.x:=a+b.x; result.y:=a+b.y; result.z:=a+b.z; result.w:=a+b.w; end; class operator TpvQuaternion.Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x-b.x; result.y:=a.y-b.y; result.z:=a.z-b.z; result.w:=a.w-b.w; end; {$ifend} class operator TpvQuaternion.Subtract(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=a.x-b; result.y:=a.y-b; result.z:=a.z-b; result.w:=a.w-b; end; class operator TpvQuaternion.Subtract(const a:TpvScalar;const b:TpvQuaternion): TpvQuaternion; begin result.x:=a-b.x; result.y:=a-b.y; result.z:=a-b.z; result.w:=a-b.w; end; class operator TpvQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const XORMaskW:array[0..3] of TpvUInt32=($00000000,$00000000,$00000000,$80000000); asm movups xmm4,dqword ptr [a] movaps xmm0,xmm4 shufps xmm0,xmm4,$49 movups xmm2,dqword ptr [b] movaps xmm3,xmm2 movaps xmm1,xmm2 shufps xmm3,xmm2,$52 // 001010010b mulps xmm3,xmm0 movaps xmm0,xmm4 shufps xmm0,xmm4,$24 // 000100100b shufps xmm1,xmm2,$3f // 000111111b {$ifdef cpu386} movups xmm5,dqword ptr [XORMaskW] {$else} {$ifdef fpc} movups xmm5,dqword ptr [rip+XORMaskW] {$else} movups xmm5,dqword ptr [rel XORMaskW] {$endif} {$endif} mulps xmm1,xmm0 movaps xmm0,xmm4 shufps xmm0,xmm4,$92 // 001001001b shufps xmm4,xmm4,$ff // 011111111b mulps xmm4,xmm2 addps xmm3,xmm1 movaps xmm1,xmm2 shufps xmm1,xmm2,$89 // 010001001b mulps xmm1,xmm0 xorps xmm3,xmm5 subps xmm4,xmm1 addps xmm3,xmm4 movups dqword ptr [result],xmm3 end; {$else} begin result.x:=((a.w*b.x)+(a.x*b.w)+(a.y*b.z))-(a.z*b.y); result.y:=((a.w*b.y)+(a.y*b.w)+(a.z*b.x))-(a.x*b.z); result.z:=((a.w*b.z)+(a.z*b.w)+(a.x*b.y))-(a.y*b.x); result.w:=(a.w*b.w)-((a.x*b.x)+(a.y*b.y)+(a.z*b.z)); end; {$ifend} class operator TpvQuaternion.Multiply(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=a.x*b; result.y:=a.y*b; result.z:=a.z*b; result.w:=a.w*b; end; class operator TpvQuaternion.Multiply(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; begin result.x:=a*b.x; result.y:=a*b.y; result.z:=a*b.z; result.w:=a*b.w; end; class operator TpvQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const Mask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} // q = a // v = b movups xmm4,dqword ptr [a] // xmm4 = q.xyzw xorps xmm7,xmm7 movss xmm5,dword ptr [b+0] movss xmm6,dword ptr [b+4] movss xmm7,dword ptr [b+8] movlhps xmm5,xmm6 shufps xmm5,xmm7,$88 //movups xmm5,dqword ptr [b] // xmm5 = v.xyz? movaps xmm6,xmm4 shufps xmm6,xmm6,$ff // xmm6 = q.wwww {$ifdef cpu386} movups xmm7,dqword ptr [Mask] // xmm7 = Mask {$else} {$ifdef fpc} movups xmm7,dqword ptr [rip+Mask] // xmm7 = Mask {$else} movups xmm7,dqword ptr [rel Mask] // xmm7 = Mask {$endif} {$endif} andps xmm4,xmm7 // xmm4 = q.xyz0 andps xmm5,xmm7 // xmm5 = v.xyz0 // t:=Vector3ScalarMul(Vector3Cross(qv,v),2.0); movaps xmm0,xmm4 // xmm4 = qv movaps xmm1,xmm5 // xmm5 = v movaps xmm2,xmm4 // xmm4 = qv movaps xmm3,xmm5 // xmm5 = v shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 addps xmm2,xmm2 // xmm6 = Vector3Add(v,Vector3ScalarMul(t,q.w)) mulps xmm6,xmm2 // xmm6 = q.wwww, xmm2 = t addps xmm6,xmm5 // xmm5 = v // Vector3Cross(qv,t) movaps xmm1,xmm4 // xmm4 = qv movaps xmm3,xmm2 // xmm2 = t shufps xmm4,xmm4,$12 shufps xmm2,xmm2,$09 shufps xmm1,xmm1,$09 shufps xmm3,xmm3,$12 mulps xmm4,xmm2 mulps xmm1,xmm3 subps xmm1,xmm4 // result:=Vector3Add(Vector3Add(v,Vector3ScalarMul(t,q.w)),Vector3Cross(qv,t)); addps xmm1,xmm6 movaps xmm0,xmm1 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 //movups dqword ptr [result],xmm1 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} var t:TpvVector3; begin // q = a // v = b // t = 2 * cross(q.xyz, v) // v' = v + q.w * t + cross(q.xyz, t) t:=a.Vector.xyz.Cross(b)*2.0; result:=(b+(a.w*t))+a.Vector.xyz.Cross(t); end; {$ifend} class operator TpvQuaternion.Multiply(const a:TpvVector3;const b:TpvQuaternion):TpvVector3; begin result:=b.Inverse*a; end; class operator TpvQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const AndMask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); OrMask:array[0..3] of TpvUInt32=($00000000,$00000000,$00000000,$3f800000); {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} // q = a // v = b movups xmm4,dqword ptr [a] // xmm4 = q.xyzw movups xmm5,dqword ptr [b] // xmm5 = v.xyz? movaps xmm6,xmm4 shufps xmm6,xmm6,$ff // xmm6 = q.wwww {$ifdef cpu386} movups xmm7,dqword ptr [AndMask] // xmm7 = AndMask {$else} {$ifdef fpc} movups xmm7,dqword ptr [rip+AndMask] // xmm7 = AndMask {$else} movups xmm7,dqword ptr [rel AndMask] // xmm7 = AndMask {$endif} {$endif} andps xmm4,xmm7 // xmm4 = q.xyz0 andps xmm5,xmm7 // xmm5 = v.xyz0 // t:=Vector3ScalarMul(Vector3Cross(qv,v),2.0); movaps xmm0,xmm4 // xmm4 = qv movaps xmm1,xmm5 // xmm5 = v movaps xmm2,xmm4 // xmm4 = qv movaps xmm3,xmm5 // xmm5 = v shufps xmm0,xmm0,$12 shufps xmm1,xmm1,$09 shufps xmm2,xmm2,$09 shufps xmm3,xmm3,$12 mulps xmm0,xmm1 mulps xmm2,xmm3 subps xmm2,xmm0 addps xmm2,xmm2 // xmm6 = Vector3Add(v,Vector3ScalarMul(t,q.w)) mulps xmm6,xmm2 // xmm6 = q.wwww, xmm2 = t addps xmm6,xmm5 // xmm5 = v // Vector3Cross(qv,t) movaps xmm1,xmm4 // xmm4 = qv movaps xmm3,xmm2 // xmm2 = t shufps xmm4,xmm4,$12 shufps xmm2,xmm2,$09 shufps xmm1,xmm1,$09 shufps xmm3,xmm3,$12 mulps xmm4,xmm2 mulps xmm1,xmm3 subps xmm1,xmm4 {$ifdef cpu386} movups xmm4,dqword ptr [OrMask] // xmm4 = OrMask {$else} {$ifdef fpc} movups xmm4,dqword ptr [rip+OrMask] // xmm4 = OrMask {$else} movups xmm4,dqword ptr [rel OrMask] // xmm4 = OrMask {$endif} {$endif} // result:=Vector3Add(Vector3Add(v,Vector3ScalarMul(t,q.w)),Vector3Cross(qv,t)); addps xmm1,xmm6 andps xmm1,xmm7 // xmm1 = xmm1.xyz0 orps xmm1,xmm4 // xmm1 = xmm1.xyz1 movups dqword ptr [result],xmm1 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} var t:TpvVector3; begin // q = a // v = b // t = 2 * cross(q.xyz, v) // v' = v + q.w * t + cross(q.xyz, t) t:=a.Vector.xyz.Cross(b.xyz)*2.0; result.xyz:=(b.xyz+(a.w*t))+a.Vector.xyz.Cross(t); result.w:=1.0; end; {$ifend} class operator TpvQuaternion.Multiply(const a:TpvVector4;const b:TpvQuaternion):TpvVector4; begin result:=b.Inverse*a; end; class operator TpvQuaternion.Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] divps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; result.w:=a.w/b.w; end; {$ifend} class operator TpvQuaternion.Divide(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; result.w:=a.w/b; end; class operator TpvQuaternion.Divide(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; result.w:=a/b.z; end; class operator TpvQuaternion.IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a] movups xmm1,dqword ptr [b] divps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=a.x/b.x; result.y:=a.y/b.y; result.z:=a.z/b.z; result.w:=a.w/b.w; end; {$ifend} class operator TpvQuaternion.IntDivide(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=a.x/b; result.y:=a.y/b; result.z:=a.z/b; result.w:=a.w/b; end; class operator TpvQuaternion.IntDivide(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; begin result.x:=a/b.x; result.y:=a/b.y; result.z:=a/b.z; result.w:=a/b.w; end; class operator TpvQuaternion.Modulus(const a,b:TpvQuaternion):TpvQuaternion; begin result.x:=Modulus(a.x,b.x); result.y:=Modulus(a.y,b.y); result.z:=Modulus(a.z,b.z); result.w:=Modulus(a.w,b.w); end; class operator TpvQuaternion.Modulus(const a:TpvQuaternion;const b:TpvScalar):TpvQuaternion; begin result.x:=Modulus(a.x,b); result.y:=Modulus(a.y,b); result.z:=Modulus(a.z,b); result.w:=Modulus(a.w,b); end; class operator TpvQuaternion.Modulus(const a:TpvScalar;const b:TpvQuaternion):TpvQuaternion; begin result.x:=Modulus(a,b.x); result.y:=Modulus(a,b.y); result.z:=Modulus(a,b.z); result.w:=Modulus(a,b.w); end; class operator TpvQuaternion.Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvQuaternion):TpvQuaternion; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm xorps xmm0,xmm0 movups xmm1,dqword ptr [a] subps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=-a.x; result.y:=-a.y; result.z:=-a.z; result.w:=-a.w; end; {$ifend} class operator TpvQuaternion.Positive(const a:TpvQuaternion):TpvQuaternion; begin result:=a; end; function TpvQuaternion.GetComponent(const aIndex:TpvInt32):TpvScalar; begin result:=RawComponents[aIndex]; end; procedure TpvQuaternion.SetComponent(const aIndex:TpvInt32;const aValue:TpvScalar); begin RawComponents[aIndex]:=aValue; end; function TpvQuaternion.ToNormalizedSphericalCoordinates:TpvNormalizedSphericalCoordinates; var ty:TpvScalar; begin ty:=y; if ty<-1.0 then begin ty:=-1.0; end else if ty>1.0 then begin ty:=1.0; end; result.Latitude:=ArcSin(ty); if (sqr(x)+sqr(z))>0.00005 then begin result.Longitude:=ArcTan2(x,z); end else begin result.Longitude:=0.0; end; end; function TpvQuaternion.ToEuler:TpvVector3; var t:TpvScalar; begin // Order of rotations: Roll (Z), Pitch (X), Yaw (Y) t:=2.0*((x*w)-(y*z)); if t<-0.995 then begin result.Pitch:=-HalfPI; result.Yaw:=0.0; result.Roll:=-ArcTan2(2.0*((x*z)-(y*w)),1.0-(2.0*(sqr(y)+sqr(z)))); end else if t>0.995 then begin result.Pitch:=HalfPI; result.Yaw:=0.0; result.Roll:=ArcTan2(2.0*((x*z)-(y*w)),1.0-(2.0*(sqr(y)+sqr(z)))); end else begin result.Pitch:=ArcSin(t); result.Yaw:=ArcTan2(2.0*((x*z)+(y*w)),1.0-(2.0*(sqr(x)+sqr(y)))); result.Roll:=ArcTan2(2.0*((x*y)+(z*w)),1.0-(2.0*(sqr(x)+sqr(z)))); end; end; function TpvQuaternion.ToPitch:TpvScalar; var t:TpvScalar; begin // Order of rotations: Roll (Z), Pitch (X), Yaw (Y) t:=2.0*((x*w)-(y*z)); if t<-0.995 then begin result:=-HalfPI; end else if t>0.995 then begin result:=HalfPI; end else begin result:=ArcSin(t); end; end; function TpvQuaternion.ToYaw:TpvScalar; var t:TpvScalar; begin // Order of rotations: Roll (Z), Pitch (X), Yaw (Y) t:=2.0*((x*w)-(y*z)); if System.abs(t)>0.995 then begin result:=0.0; end else begin result:=ArcTan2(2.0*((x*z)+(y*w)),1.0-(2.0*(sqr(x)+sqr(y)))); end; end; function TpvQuaternion.ToRoll:TpvScalar; var t:TpvScalar; begin // Order of rotations: Roll (Z), Pitch (X), Yaw (Y) t:=2.0*((x*w)-(y*z)); if t<-0.995 then begin result:=-ArcTan2(2.0*((x*z)-(y*w)),1.0-(2.0*(sqr(y)+sqr(z)))); end else if t>0.995 then begin result:=ArcTan2(2.0*((x*z)-(y*w)),1.0-(2.0*(sqr(y)+sqr(z)))); end else begin result:=ArcTan2(2.0*((x*y)+(z*w)),1.0-(2.0*(sqr(x)+sqr(z)))); end; end; function TpvQuaternion.ToAngularVelocity:TpvVector3; var Angle,Gain:TpvScalar; begin if System.abs(1.0-w)<EPSILON then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; end else begin Angle:=ArcCos(System.abs(w)); Gain:=(Sign(w)*2.0)*(Angle/Sin(Angle)); result.x:=x*Gain; result.y:=y*Gain; result.z:=z*Gain; end; end; procedure TpvQuaternion.ToAngleAxis(out aAngle:TpvScalar;out aAxis:TpvVector3); var SinAngle:TpvScalar; Quaternion:TpvQuaternion; begin Quaternion:=Normalize; SinAngle:=sqrt(1.0-sqr(Quaternion.w)); if System.abs(SinAngle)<EPSILON then begin SinAngle:=1.0; end; aAngle:=2.0*ArcCos(Quaternion.w); aAxis.x:=Quaternion.x/SinAngle; aAxis.y:=Quaternion.y/SinAngle; aAxis.z:=Quaternion.z/SinAngle; end; function TpvQuaternion.ToScaledAngleAxis:TpvVector3; begin result:=Log.Vector.xyz*2.0; end; function TpvQuaternion.Generator:TpvVector3; var s:TpvScalar; begin s:=sqrt(1.0-sqr(w)); result.x:=x; result.y:=y; result.z:=z; if s>0.0 then begin result:=result*s; end; result:=result*(2.0*ArcTan2(s,w)); end; function TpvQuaternion.Flip:TpvQuaternion; begin result.x:=x; result.y:=z; result.z:=-y; result.w:=w; end; function TpvQuaternion.Perpendicular:TpvQuaternion; var v,p:TpvQuaternion; begin v:=self.Normalize; p.x:=System.abs(v.x); p.y:=System.abs(v.y); p.z:=System.abs(v.z); p.w:=System.abs(v.w); if (p.x<=p.y) and (p.x<=p.z) and (p.x<=p.w) then begin p.x:=1.0; p.y:=0.0; p.z:=0.0; p.w:=0.0; end else if (p.y<=p.x) and (p.y<=p.z) and (p.y<=p.w) then begin p.x:=0.0; p.y:=1.0; p.z:=0.0; p.w:=0.0; end else if (p.z<=p.x) and (p.z<=p.y) and (p.z<=p.w) then begin p.x:=0.0; p.y:=0.0; p.z:=0.0; p.w:=1.0; end else begin p.x:=0.0; p.y:=0.0; p.z:=1.0; p.w:=0.0; end; result:=p-(v*v.Dot(p)); end; function TpvQuaternion.Conjugate:TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} const XORMask:array[0..3] of TpvUInt32=($80000000,$80000000,$80000000,$00000000); asm movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [XORMask] xorps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} const XORMask:array[0..3] of TpvUInt32=($80000000,$80000000,$80000000,$00000000); asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) {$ifdef fpc} movups xmm1,dqword ptr [rip+XORMask] {$else} movups xmm1,dqword ptr [rel XORMask] {$endif} xorps xmm0,xmm1 movups dqword ptr [result],xmm0 end; {$else} begin result.x:=-x; result.y:=-y; result.z:=-z; result.w:=w; end; {$ifend} function TpvQuaternion.Inverse:TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} const XORMask:array[0..3] of TpvUInt32=($80000000,$80000000,$80000000,$00000000); asm movups xmm2,dqword ptr [eax] movups xmm3,dqword ptr [XORMask] movaps xmm0,xmm2 mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 sqrtss xmm0,xmm0 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 xorps xmm2,xmm3 movups dqword ptr [result],xmm2 end; {$elseif defined(SIMD) and defined(cpux64)} const XORMask:array[0..3] of TpvUInt32=($80000000,$80000000,$80000000,$00000000); asm //{$ifdef Windows} movups xmm2,dqword ptr [rcx] (*{$else} movups xmm2,dqword ptr [rdi] {$endif}*) {$ifdef fpc} movups xmm3,dqword ptr [rip+XORMask] {$else} movups xmm3,dqword ptr [rel XORMask] {$endif} movaps xmm0,xmm2 mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 sqrtss xmm0,xmm0 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 xorps xmm2,xmm3 movups dqword ptr [result],xmm2 end; {$else} var Normal:TpvScalar; begin Normal:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w)); if Normal>0.0 then begin Normal:=1.0/Normal; end; result.x:=-(x*Normal); result.y:=-(y*Normal); result.z:=-(z*Normal); result.w:=w*Normal; end; {$ifend} function TpvQuaternion.Length:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm1,xmm0 sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm1,xmm0 sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w)); end; {$ifend} function TpvQuaternion.SquaredLength:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqr(x)+sqr(y)+sqr(z)+sqr(w); end; {$ifend} function TpvQuaternion.Normalize:TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movaps xmm2,xmm0 mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 sqrtss xmm0,xmm0 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 subps xmm1,xmm2 cmpps xmm1,xmm0,7 andps xmm2,xmm1 movups dqword ptr [edx],xmm2 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) movaps xmm2,xmm0 mulps xmm0,xmm0 movhlps xmm1,xmm0 addps xmm0,xmm1 pshufd xmm1,xmm0,$01 addss xmm0,xmm1 sqrtss xmm0,xmm0 // not rsqrtss! because rsqrtss has only 12-bit accuracy shufps xmm0,xmm0,$00 divps xmm2,xmm0 subps xmm1,xmm2 cmpps xmm1,xmm0,7 andps xmm2,xmm1 //{$ifdef Windows} movups dqword ptr [rdx],xmm2 (*{$else} movups dqword ptr [result],xmm2 {$endif}*) end; {$else} var Factor:TpvScalar; begin Factor:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w)); if Factor<>0.0 then begin Factor:=1.0/Factor; result.x:=x*Factor; result.y:=y*Factor; result.z:=z*Factor; result.w:=w*Factor; end else begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=0.0; end; end; {$ifend} function TpvQuaternion.DistanceTo({$ifdef fpc}constref{$else}const{$endif} b:TpvQuaternion):TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [edx] subps xmm0,xmm1 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm1,dqword ptr [rdx] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm1,dqword ptr [rsi] {$endif}*) subps xmm0,xmm1 mulps xmm0,xmm0 // xmm0 = w*w, z*z, y*y, x*x movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$4e // xmm1 = z*z, w*w, x*x, y*y addps xmm0,xmm1 // xmm0 = xmm0 + xmm1 = (zw*zw, zw*zw, xy*zw, xy*zw) movaps xmm1,xmm0 // xmm1 = xmm0 shufps xmm1,xmm1,$b1 // xmm0 = xy*xy, xy*xy, zw*zw, zw*zw addps xmm1,xmm0 // xmm1 = xmm1 + xmm0 = (xyzw, xyzw, xyzw, xyzw) sqrtss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=sqrt(sqr(x-b.x)+sqr(y-b.y)+sqr(z-b.z)+sqr(w-b.w)); end; {$ifend} function TpvQuaternion.Abs:TpvQuaternion; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 movups dqword ptr [edx],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] (*{$else} movups xmm0,dqword ptr [rdi] {$endif}*) xorps xmm1,xmm1 subps xmm1,xmm0 maxps xmm0,xmm1 //{$ifdef Windows} movups dqword ptr [rdx],xmm0 (*{$else} movups dqword ptr [rax],xmm0 {$endif}*) end; {$else} begin result.x:=System.abs(x); result.y:=System.abs(y); result.z:=System.abs(z); result.w:=System.abs(w); end; {$ifend} function TpvQuaternion.Exp:TpvQuaternion; var Angle,Sinus,Coefficent:TpvScalar; begin Angle:=sqrt(sqr(x)+sqr(y)+sqr(z)); Sinus:=sin(Angle); result.w:=cos(Angle); if System.Abs(Sinus)>1e-6 then begin Coefficent:=Sinus/Angle; result.x:=x*Coefficent; result.y:=y*Coefficent; result.z:=z*Coefficent; end else begin result.x:=x; result.y:=y; result.z:=z; end; end; function TpvQuaternion.Log:TpvQuaternion; var Theta,SinTheta,Coefficent:TpvScalar; begin result.x:=x; result.y:=y; result.z:=z; result.w:=0.0; if System.Abs(w)<1.0 then begin Theta:=ArcCos(w); SinTheta:=sin(Theta); if System.Abs(SinTheta)>1e-6 then begin Coefficent:=Theta/SinTheta; result.x:=result.x*Coefficent; result.y:=result.y*Coefficent; result.z:=result.z*Coefficent; end; end; end; function TpvQuaternion.Dot({$ifdef fpc}constref{$else}const{$endif} b:TpvQuaternion):TpvScalar; {$if not (defined(cpu386) or defined(cpux64))}{$ifdef CAN_INLINE}inline;{$endif}{$ifend} {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax] movups xmm1,dqword ptr [edx] mulps xmm0,xmm1 movaps xmm1,xmm0 shufps xmm1,xmm0,$b1 addps xmm0,xmm1 movhlps xmm1,xmm0 addss xmm0,xmm1 movss dword ptr [result],xmm0 end; {$elseif defined(SIMD) and defined(cpux64)} asm //{$ifdef Windows} movups xmm0,dqword ptr [rcx] movups xmm1,dqword ptr [rdx] (*{$else} movups xmm0,dqword ptr [rdi] movups xmm1,dqword ptr [rsi] {$endif}*) mulps xmm0,xmm1 movaps xmm1,xmm0 shufps xmm1,xmm0,$b1 addps xmm0,xmm1 movhlps xmm1,xmm0 addss xmm0,xmm1 {$ifdef fpc} movss dword ptr [result],xmm0 {$else} //movaps xmm0,xmm0 {$endif} end; {$else} begin result:=(x*b.x)+(y*b.y)+(z*b.z)+(w*b.w); end; {$ifend} function TpvQuaternion.Lerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var SignFactor:TpvScalar; begin if Dot(aToQuaternion)<0.0 then begin SignFactor:=-1.0; end else begin SignFactor:=1.0; end; if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToQuaternion*SignFactor; end else begin result:=(self*(1.0-aTime))+(aToQuaternion*(aTime*SignFactor)); end; end; function TpvQuaternion.Nlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; begin result:=Lerp(aToQuaternion,aTime).Normalize; end; function TpvQuaternion.Slerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var Omega,co,so,s0,s1,s2:TpvScalar; begin co:=Dot(aToQuaternion); if co<0.0 then begin co:=-co; s2:=-1.0; end else begin s2:=1.0; end; if (1.0-co)>EPSILON then begin Omega:=ArcCos(co); so:=sin(Omega); s0:=sin((1.0-aTime)*Omega)/so; s1:=sin(aTime*Omega)/so; end else begin s0:=1.0-aTime; s1:=aTime; end; result:=(s0*self)+(aToQuaternion*(s1*s2)); end; function TpvQuaternion.ApproximatedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var ca,d,a,b,k,o:TpvScalar; begin // Idea from https://zeux.io/2015/07/23/approximating-slerp/ ca:=Dot(aToQuaternion); d:=System.abs(ca); a:=1.0904+(d*(-3.2452+(d*(3.55645-(d*1.43519))))); b:=0.848013+(d*(-1.06021+(d*0.215638))); k:=(a*sqr(aTime-0.5))+b; o:=aTime+(((aTime*(aTime-0.5))*(aTime-1.0))*k); if ca<0.0 then begin result:=Nlerp(-aToQuaternion,o); end else begin result:=Nlerp(aToQuaternion,o); end; end; function TpvQuaternion.Elerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var SignFactor:TpvScalar; begin if Dot(aToQuaternion)<0.0 then begin SignFactor:=-1.0; end else begin SignFactor:=1.0; end; if aTime<=0.0 then begin result:=self; end else if aTime>=1.0 then begin result:=aToQuaternion*SignFactor; end else begin result:=((Log*(1.0-aTime))+((aToQuaternion*SignFactor).Log*aTime)).Exp; end; end; function TpvQuaternion.Sqlerp(const aB,aC,aD:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvQuaternion.UnflippedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var Omega,co,so,s0,s1:TpvScalar; begin co:=Dot(aToQuaternion); if (1.0-co)>EPSILON then begin Omega:=ArcCos(co); so:=sin(Omega); s0:=sin((1.0-aTime)*Omega)/so; s1:=sin(aTime*Omega)/so; end else begin s0:=1.0-aTime; s1:=aTime; end; result:=(s0*self)+(aToQuaternion*s1); end; function TpvQuaternion.UnflippedApproximatedSlerp(const aToQuaternion:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; var d,a,b,k,o:TpvScalar; begin // Idea from https://zeux.io/2015/07/23/approximating-slerp/ d:=System.abs(Dot(aToQuaternion)); a:=1.0904+(d*(-3.2452+(d*(3.55645-(d*1.43519))))); b:=0.848013+(d*(-1.06021+(d*0.215638))); k:=(a*sqr(aTime-0.5))+b; o:=aTime+(((aTime*(aTime-0.5))*(aTime-1.0))*k); result:=Nlerp(aToQuaternion,o); end; function TpvQuaternion.UnflippedSqlerp(const aB,aC,aD:TpvQuaternion;const aTime:TpvScalar):TpvQuaternion; begin result:=UnflippedSlerp(aD,aTime).UnflippedSlerp(aB.UnflippedSlerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvQuaternion.AngleBetween(const aP:TpvQuaternion):TpvScalar; var Difference:TpvQuaternion; begin Difference:=(self*aP.Inverse).Abs; result:=ArcCos(Clamp(Difference.w,-1.0,1.0))*2.0; end; function TpvQuaternion.Between(const aP:TpvQuaternion):TpvQuaternion; var c:TpvVector3; begin c:=aP.Vector.xyz.Cross(self.Vector.xyz); result:=TpvQuaternion.Create(c.x,c.y,c.z,sqrt(aP.Vector.xyz.SquaredLength*self.Vector.xyz.SquaredLength)+aP.Vector.xyz.Dot(self.Vector.xyz)).Normalize; end; class procedure TpvQuaternion.Hermite(out aRotation:TpvQuaternion;out aVelocity:TpvVector3;const aTime:TpvScalar;const aR0,aR1:TpvQuaternion;const aV0,aV1:TpvVector3); var t2,t3,w1,w2,w3,q1,q2,q3:TpvScalar; r1r0:TpvVector3; begin t2:=sqr(aTime); t3:=t2*aTime; w1:=(3.0*t2)-(2.0*t3); w2:=(t3-(2.0*t2))+aTime; w3:=t3-t2; q1:=(6.0*aTime)-(6.0*t2); q2:=((3.0*t2)-(4.0*aTime))+1.0; q3:=(3.0*t2)-(2.0*aTime); r1r0:=((aR1*aR0.Inverse).Abs).ToScaledAngleAxis; aRotation:=TpvQuaternion.CreateFromScaledAngleAxis((r1r0*w1)+(aV0*w2)+(aV1*w3))*aR0; aVelocity:=(q1*r1r0)+(aV0*q2)+(aV1*q3); end; class procedure TpvQuaternion.CatmullRom(out aRotation:TpvQuaternion;out aVelocity:TpvVector3;const aTime:TpvScalar;const aR0,aR1,aR2,aR3:TpvQuaternion); var r1r0,r2r1,r3r2,v1,v2:TpvVector3; begin r1r0:=((aR1*aR0.Inverse).Abs).ToScaledAngleAxis; r2r1:=((aR2*aR1.Inverse).Abs).ToScaledAngleAxis; r3r2:=((aR3*aR2.Inverse).Abs).ToScaledAngleAxis; v1:=(r1r0+r2r1)*0.5; v2:=(r2r1+r3r2)*0.5; TpvQuaternion.Hermite(aRotation,aVelocity,aTime,aR1,aR2,v1,v2); end; function TpvQuaternion.RotateAroundAxis(const aVector:TpvQuaternion):TpvQuaternion; begin result.x:=((x*aVector.w)+(z*aVector.y))-(y*aVector.z); result.y:=((x*aVector.z)+(y*aVector.w))-(z*aVector.x); result.z:=((y*aVector.x)+(z*aVector.w))-(x*aVector.y); result.w:=((x*aVector.x)+(y*aVector.y))+(z*aVector.z); end; function TpvQuaternion.Integrate(const aOmega:TpvVector3;const aDeltaTime:TpvScalar):TpvQuaternion; var ThetaLenSquared,ThetaLen,s,w:TpvScalar; Theta:TpvVector3; begin Theta:=aOmega*(aDeltaTime*0.5); ThetaLenSquared:=Theta.SquaredLength; if (sqr(ThetaLenSquared)/24.0)<EPSILON then begin s:=1.0-(ThetaLenSquared/6.0); w:=1.0-(ThetaLenSquared*0.5); end else begin ThetaLen:=sqrt(ThetaLenSquared); s:=sin(ThetaLen)/ThetaLen; w:=cos(ThetaLen); end; result.Vector.xyz:=Theta*s; result.Vector.w:=w; result:=result*self; end; function TpvQuaternion.Spin(const aOmega:TpvVector3;const aDeltaTime:TpvScalar):TpvQuaternion; var wq:TpvQuaternion; begin wq.x:=aOmega.x*aDeltaTime; wq.y:=aOmega.y*aDeltaTime; wq.z:=aOmega.z*aDeltaTime; wq.w:=0.0; result:=(self+((wq*self)*0.5)).Normalize; end; {constructor TpvMatrix2x2.Create; begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; end;//} constructor TpvMatrix2x2.Create(const pX:TpvScalar); begin RawComponents[0,0]:=pX; RawComponents[0,1]:=pX; RawComponents[1,0]:=pX; RawComponents[1,1]:=pX; end; constructor TpvMatrix2x2.Create(const pXX,pXY,pYX,pYY:TpvScalar); begin RawComponents[0,0]:=pXX; RawComponents[0,1]:=pXY; RawComponents[1,0]:=pYX; RawComponents[1,1]:=pYY; end; constructor TpvMatrix2x2.Create(const pX,pY:TpvVector2); begin RawComponents[0,0]:=pX.x; RawComponents[0,1]:=pX.y; RawComponents[1,0]:=pY.x; RawComponents[1,1]:=pY.y; end; class operator TpvMatrix2x2.Implicit(const a:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; end; class operator TpvMatrix2x2.Explicit(const a:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; end; class operator TpvMatrix2x2.Equal(const a,b:TpvMatrix2x2):boolean; begin result:=SameValue(a.RawComponents[0,0],b.RawComponents[0,0]) and SameValue(a.RawComponents[0,1],b.RawComponents[0,1]) and SameValue(a.RawComponents[1,0],b.RawComponents[1,0]) and SameValue(a.RawComponents[1,1],b.RawComponents[1,1]); end; class operator TpvMatrix2x2.NotEqual(const a,b:TpvMatrix2x2):boolean; begin result:=(not SameValue(a.RawComponents[0,0],b.RawComponents[0,0])) or (not SameValue(a.RawComponents[0,1],b.RawComponents[0,1])) or (not SameValue(a.RawComponents[1,0],b.RawComponents[1,0])) or (not SameValue(a.RawComponents[1,1],b.RawComponents[1,1])); end; class operator TpvMatrix2x2.Inc(const a:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]+1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]+1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]+1.0; end; class operator TpvMatrix2x2.Dec(const a:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]-1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]-1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]-1.0; end; class operator TpvMatrix2x2.Add(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]+b.RawComponents[0,1]; result.RawComponents[1,0]:=a.RawComponents[1,0]+b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]+b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Add(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b; result.RawComponents[0,1]:=a.RawComponents[0,1]+b; result.RawComponents[1,0]:=a.RawComponents[1,0]+b; result.RawComponents[1,1]:=a.RawComponents[1,1]+b; end; class operator TpvMatrix2x2.Add(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a+b.RawComponents[0,0]; result.RawComponents[0,1]:=a+b.RawComponents[0,1]; result.RawComponents[1,0]:=a+b.RawComponents[1,0]; result.RawComponents[1,1]:=a+b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Subtract(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]-b.RawComponents[0,1]; result.RawComponents[1,0]:=a.RawComponents[1,0]-b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]-b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Subtract(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b; result.RawComponents[0,1]:=a.RawComponents[0,1]-b; result.RawComponents[1,0]:=a.RawComponents[1,0]-b; result.RawComponents[1,1]:=a.RawComponents[1,1]-b; end; class operator TpvMatrix2x2.Subtract(const a:TpvScalar;const b:TpvMatrix2x2): TpvMatrix2x2; begin result.RawComponents[0,0]:=a-b.RawComponents[0,0]; result.RawComponents[0,1]:=a-b.RawComponents[0,1]; result.RawComponents[1,0]:=a-b.RawComponents[1,0]; result.RawComponents[1,1]:=a-b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Multiply(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=(a.RawComponents[0,0]*b.RawComponents[0,0])+(a.RawComponents[0,1]*b.RawComponents[1,0]); result.RawComponents[0,1]:=(a.RawComponents[0,0]*b.RawComponents[0,1])+(a.RawComponents[0,1]*b.RawComponents[1,1]); result.RawComponents[1,0]:=(a.RawComponents[1,0]*b.RawComponents[0,0])+(a.RawComponents[1,1]*b.RawComponents[1,0]); result.RawComponents[1,1]:=(a.RawComponents[1,0]*b.RawComponents[0,1])+(a.RawComponents[1,1]*b.RawComponents[1,1]); end; class operator TpvMatrix2x2.Multiply(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]*b; result.RawComponents[0,1]:=a.RawComponents[0,1]*b; result.RawComponents[1,0]:=a.RawComponents[1,0]*b; result.RawComponents[1,1]:=a.RawComponents[1,1]*b; end; class operator TpvMatrix2x2.Multiply(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a*b.RawComponents[0,0]; result.RawComponents[0,1]:=a*b.RawComponents[0,1]; result.RawComponents[1,0]:=a*b.RawComponents[1,0]; result.RawComponents[1,1]:=a*b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Multiply(const a:TpvMatrix2x2;const b:TpvVector2):TpvVector2; begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y); result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y); end; class operator TpvMatrix2x2.Multiply(const a:TpvVector2;const b:TpvMatrix2x2):TpvVector2; begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1]); result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1]); end; class operator TpvMatrix2x2.Divide(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result:=a*b.Inverse; end; class operator TpvMatrix2x2.Divide(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; end; class operator TpvMatrix2x2.Divide(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; end; class operator TpvMatrix2x2.IntDivide(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result:=a*b.Inverse; end; class operator TpvMatrix2x2.IntDivide(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; end; class operator TpvMatrix2x2.IntDivide(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; end; class operator TpvMatrix2x2.Modulus(const a,b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b.RawComponents[0,1]); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b.RawComponents[1,1]); end; class operator TpvMatrix2x2.Modulus(const a:TpvMatrix2x2;const b:TpvScalar):TpvMatrix2x2; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b); end; class operator TpvMatrix2x2.Modulus(const a:TpvScalar;const b:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=Modulo(a,b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a,b.RawComponents[0,1]); result.RawComponents[1,0]:=Modulo(a,b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a,b.RawComponents[1,1]); end; class operator TpvMatrix2x2.Negative(const a:TpvMatrix2x2):TpvMatrix2x2; begin result.RawComponents[0,0]:=-a.RawComponents[0,0]; result.RawComponents[0,1]:=-a.RawComponents[0,1]; result.RawComponents[1,0]:=-a.RawComponents[1,0]; result.RawComponents[1,1]:=-a.RawComponents[1,1]; end; class operator TpvMatrix2x2.Positive(const a:TpvMatrix2x2):TpvMatrix2x2; begin result:=a; end; function TpvMatrix2x2.GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; begin result:=RawComponents[pIndexA,pIndexB]; end; procedure TpvMatrix2x2.SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); begin RawComponents[pIndexA,pIndexB]:=pValue; end; function TpvMatrix2x2.GetColumn(const pIndex:TpvInt32):TpvVector2; begin result.x:=RawComponents[pIndex,0]; result.y:=RawComponents[pIndex,1]; end; procedure TpvMatrix2x2.SetColumn(const pIndex:TpvInt32;const pValue:TpvVector2); begin RawComponents[pIndex,0]:=pValue.x; RawComponents[pIndex,1]:=pValue.y; end; function TpvMatrix2x2.GetRow(const pIndex:TpvInt32):TpvVector2; begin result.x:=RawComponents[0,pIndex]; result.y:=RawComponents[1,pIndex]; end; procedure TpvMatrix2x2.SetRow(const pIndex:TpvInt32;const pValue:TpvVector2); begin RawComponents[0,pIndex]:=pValue.x; RawComponents[1,pIndex]:=pValue.y; end; function TpvMatrix2x2.Determinant:TpvScalar; begin result:=(RawComponents[0,0]*RawComponents[1,1])-(RawComponents[0,1]*RawComponents[1,0]); end; function TpvMatrix2x2.Inverse:TpvMatrix2x2; var d:TpvScalar; begin d:=(RawComponents[0,0]*RawComponents[1,1])-(RawComponents[0,1]*RawComponents[1,0]); if d<>0.0 then begin d:=1.0/d; result.RawComponents[0,0]:=RawComponents[1,1]*d; result.RawComponents[0,1]:=-(RawComponents[0,1]*d); result.RawComponents[1,0]:=-(RawComponents[1,0]*d); result.RawComponents[1,1]:=RawComponents[0,0]*d; end else begin result:=TpvMatrix2x2.Identity; end; end; function TpvMatrix2x2.Transpose:TpvMatrix2x2; begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[1,0]; result.RawComponents[1,0]:=RawComponents[0,1]; result.RawComponents[1,1]:=RawComponents[1,1]; end; function TpvDecomposedMatrix3x3.Lerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Lerp(b.Rotation,t); end; end; function TpvDecomposedMatrix3x3.Nlerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Nlerp(b.Rotation,t); end; end; function TpvDecomposedMatrix3x3.Slerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Slerp(b.Rotation,t); end; end; function TpvDecomposedMatrix3x3.Elerp(const b:TpvDecomposedMatrix3x3;const t:TpvScalar):TpvDecomposedMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Elerp(b.Rotation,t); end; end; function TpvDecomposedMatrix3x3.Sqlerp(const aB,aC,aD:TpvDecomposedMatrix3x3;const aTime:TpvScalar):TpvDecomposedMatrix3x3; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; {constructor TpvMatrix3x3.Create; begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end;//} constructor TpvMatrix3x3.Create(const pX:TpvScalar); begin RawComponents[0,0]:=pX; RawComponents[0,1]:=pX; RawComponents[0,2]:=pX; RawComponents[1,0]:=pX; RawComponents[1,1]:=pX; RawComponents[1,2]:=pX; RawComponents[2,0]:=pX; RawComponents[2,1]:=pX; RawComponents[2,2]:=pX; end; constructor TpvMatrix3x3.Create(const pXX,pXY,pXZ,pYX,pYY,pYZ,pZX,pZY,pZZ:TpvScalar); begin RawComponents[0,0]:=pXX; RawComponents[0,1]:=pXY; RawComponents[0,2]:=pXZ; RawComponents[1,0]:=pYX; RawComponents[1,1]:=pYY; RawComponents[1,2]:=pYZ; RawComponents[2,0]:=pZX; RawComponents[2,1]:=pZY; RawComponents[2,2]:=pZZ; end; constructor TpvMatrix3x3.Create(const pX,pY,pZ:TpvVector3); begin RawComponents[0,0]:=pX.x; RawComponents[0,1]:=pX.y; RawComponents[0,2]:=pX.z; RawComponents[1,0]:=pY.x; RawComponents[1,1]:=pY.y; RawComponents[1,2]:=pY.z; RawComponents[2,0]:=pZ.x; RawComponents[2,1]:=pZ.y; RawComponents[2,2]:=pZ.z; end; constructor TpvMatrix3x3.CreateRotateX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; SinCos(Angle,RawComponents[1,2],RawComponents[1,1]); RawComponents[2,0]:=0.0; RawComponents[2,1]:=-RawComponents[1,2]; RawComponents[2,2]:=RawComponents[1,1]; end; constructor TpvMatrix3x3.CreateRotateY(const Angle:TpvScalar); begin SinCos(Angle,RawComponents[2,0],RawComponents[0,0]); RawComponents[0,1]:=0.0; RawComponents[0,2]:=-RawComponents[2,0]; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=RawComponents[0,0]; end; constructor TpvMatrix3x3.CreateRotateZ(const Angle:TpvScalar); begin SinCos(Angle,RawComponents[0,1],RawComponents[0,0]); RawComponents[0,2]:=0.0; RawComponents[1,0]:=-RawComponents[0,1]; RawComponents[1,1]:=RawComponents[0,0]; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateRotate(const Angle:TpvScalar;const Axis:TpvVector3); var SinusAngle,CosinusAngle:TpvScalar; begin SinCos(Angle,SinusAngle,CosinusAngle); RawComponents[0,0]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.x)); RawComponents[1,0]:=((1.0-CosinusAngle)*Axis.x*Axis.y)-(Axis.z*SinusAngle); RawComponents[2,0]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.y*SinusAngle); RawComponents[0,1]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.z*SinusAngle); RawComponents[1,1]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.y)); RawComponents[2,1]:=((1.0-CosinusAngle)*Axis.y*Axis.z)-(Axis.x*SinusAngle); RawComponents[0,2]:=((1.0-CosinusAngle)*Axis.x*Axis.z)-(Axis.y*SinusAngle); RawComponents[1,2]:=((1.0-CosinusAngle)*Axis.y*Axis.z)+(Axis.x*SinusAngle); RawComponents[2,2]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.z)); end; constructor TpvMatrix3x3.CreateSkewYX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=tan(Angle); RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateSkewZX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=tan(Angle); RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateSkewXY(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=tan(Angle); RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateSkewZY(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=tan(Angle); RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateSkewXZ(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=tan(Angle); RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateSkewYZ(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=tan(Angle); RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateScale(const sx,sy:TpvScalar); begin RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateScale(const sx,sy,sz:TpvScalar); begin RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=sz; end; constructor TpvMatrix3x3.CreateScale(const pScale:TpvVector2); begin RawComponents[0,0]:=pScale.x; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=pScale.y; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateScale(const pScale:TpvVector3); begin RawComponents[0,0]:=pScale.x; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=pScale.y; RawComponents[1,2]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=pScale.z; end; constructor TpvMatrix3x3.CreateTranslation(const tx,ty:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=tx; RawComponents[2,1]:=ty; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateTranslation(const pTranslation:TpvVector2); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[2,0]:=pTranslation.x; RawComponents[2,1]:=pTranslation.y; RawComponents[2,2]:=1.0; end; constructor TpvMatrix3x3.CreateFromToRotation(const FromDirection,ToDirection:TpvVector3); var e,h,hvx,hvz,hvxy,hvxz,hvyz:TpvScalar; x,u,v,c:TpvVector3; begin e:=FromDirection.Dot(ToDirection); if abs(e)>(1.0-EPSILON) then begin x:=FromDirection.Abs; if x.x<x.y then begin if x.x<x.z then begin x.x:=1.0; x.y:=0.0; x.z:=0.0; end else begin x.x:=0.0; x.y:=0.0; x.z:=1.0; end; end else begin if x.y<x.z then begin x.x:=0.0; x.y:=1.0; x.z:=0.0; end else begin x.x:=0.0; x.y:=0.0; x.z:=1.0; end; end; u:=x-FromDirection; v:=x-ToDirection; c.x:=2.0/(sqr(u.x)+sqr(u.y)+sqr(u.z)); c.y:=2.0/(sqr(v.x)+sqr(v.y)+sqr(v.z)); c.z:=c.x*c.y*((u.x*v.x)+(u.y*v.y)+(u.z*v.z)); RawComponents[0,0]:=1.0+((c.z*(v.x*u.x))-((c.y*(v.x*v.x))+(c.x*(u.x*u.x)))); RawComponents[0,1]:=(c.z*(v.x*u.y))-((c.y*(v.x*v.y))+(c.x*(u.x*u.y))); RawComponents[0,2]:=(c.z*(v.x*u.z))-((c.y*(v.x*v.z))+(c.x*(u.x*u.z))); RawComponents[1,0]:=(c.z*(v.y*u.x))-((c.y*(v.y*v.x))+(c.x*(u.y*u.x))); RawComponents[1,1]:=1.0+((c.z*(v.y*u.y))-((c.y*(v.y*v.y))+(c.x*(u.y*u.y)))); RawComponents[1,2]:=(c.z*(v.y*u.z))-((c.y*(v.y*v.z))+(c.x*(u.y*u.z))); RawComponents[2,0]:=(c.z*(v.z*u.x))-((c.y*(v.z*v.x))+(c.x*(u.z*u.x))); RawComponents[2,1]:=(c.z*(v.z*u.y))-((c.y*(v.z*v.y))+(c.x*(u.z*u.y))); RawComponents[2,2]:=1.0+((c.z*(v.z*u.z))-((c.y*(v.z*v.z))+(c.x*(u.z*u.z)))); end else begin v:=FromDirection.Cross(ToDirection); h:=1.0/(1.0+e); hvx:=h*v.x; hvz:=h*v.z; hvxy:=hvx*v.y; hvxz:=hvx*v.z; hvyz:=hvz*v.y; RawComponents[0,0]:=e+(hvx*v.x); RawComponents[0,1]:=hvxy-v.z; RawComponents[0,2]:=hvxz+v.y; RawComponents[1,0]:=hvxy+v.z; RawComponents[1,1]:=e+(h*sqr(v.y)); RawComponents[1,2]:=hvyz-v.x; RawComponents[2,0]:=hvxz-v.y; RawComponents[2,1]:=hvyz+v.x; RawComponents[2,2]:=e+(hvz*v.z); end; end; constructor TpvMatrix3x3.CreateConstruct(const pForwards,pUp:TpvVector3); var RightVector,UpVector,ForwardVector:TpvVector3; begin ForwardVector:=(-pForwards).Normalize; RightVector:=pUp.Cross(ForwardVector).Normalize; UpVector:=ForwardVector.Cross(RightVector).Normalize; RawComponents[0,0]:=RightVector.x; RawComponents[0,1]:=RightVector.y; RawComponents[0,2]:=RightVector.z; RawComponents[1,0]:=UpVector.x; RawComponents[1,1]:=UpVector.y; RawComponents[1,2]:=UpVector.z; RawComponents[2,0]:=ForwardVector.x; RawComponents[2,1]:=ForwardVector.y; RawComponents[2,2]:=ForwardVector.z; end; constructor TpvMatrix3x3.CreateConstructForwardUp(const aForward,aUp:TpvVector3); var RightVector,UpVector,ForwardVector:TpvVector3; begin ForwardVector:=aForward.Normalize; RightVector:=aUp.Normalize.Cross(ForwardVector).Normalize; UpVector:=ForwardVector.Cross(RightVector).Normalize; RawComponents[0,0]:=RightVector.x; RawComponents[0,1]:=RightVector.y; RawComponents[0,2]:=RightVector.z; RawComponents[1,0]:=UpVector.x; RawComponents[1,1]:=UpVector.y; RawComponents[1,2]:=UpVector.z; RawComponents[2,0]:=ForwardVector.x; RawComponents[2,1]:=ForwardVector.y; RawComponents[2,2]:=ForwardVector.z; end; constructor TpvMatrix3x3.CreateOuterProduct(const u,v:TpvVector3); begin RawComponents[0,0]:=u.x*v.x; RawComponents[0,1]:=u.x*v.y; RawComponents[0,2]:=u.x*v.z; RawComponents[1,0]:=u.y*v.x; RawComponents[1,1]:=u.y*v.y; RawComponents[1,2]:=u.y*v.z; RawComponents[2,0]:=u.z*v.x; RawComponents[2,1]:=u.z*v.y; RawComponents[2,2]:=u.z*v.z; end; constructor TpvMatrix3x3.CreateFromQuaternion(ppvQuaternion:TpvQuaternion); var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TpvScalar; begin ppvQuaternion:=ppvQuaternion.Normalize; qx2:=ppvQuaternion.x+ppvQuaternion.x; qy2:=ppvQuaternion.y+ppvQuaternion.y; qz2:=ppvQuaternion.z+ppvQuaternion.z; qxqx2:=ppvQuaternion.x*qx2; qxqy2:=ppvQuaternion.x*qy2; qxqz2:=ppvQuaternion.x*qz2; qxqw2:=ppvQuaternion.w*qx2; qyqy2:=ppvQuaternion.y*qy2; qyqz2:=ppvQuaternion.y*qz2; qyqw2:=ppvQuaternion.w*qy2; qzqz2:=ppvQuaternion.z*qz2; qzqw2:=ppvQuaternion.w*qz2; RawComponents[0,0]:=1.0-(qyqy2+qzqz2); RawComponents[0,1]:=qxqy2+qzqw2; RawComponents[0,2]:=qxqz2-qyqw2; RawComponents[1,0]:=qxqy2-qzqw2; RawComponents[1,1]:=1.0-(qxqx2+qzqz2); RawComponents[1,2]:=qyqz2+qxqw2; RawComponents[2,0]:=qxqz2+qyqw2; RawComponents[2,1]:=qyqz2-qxqw2; RawComponents[2,2]:=1.0-(qxqx2+qyqy2); end; constructor TpvMatrix3x3.CreateFromQTangent(pQTangent:TpvQuaternion); var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TpvScalar; begin pQTangent:=pQTangent.Normalize; qx2:=pQTangent.x+pQTangent.x; qy2:=pQTangent.y+pQTangent.y; qz2:=pQTangent.z+pQTangent.z; qxqx2:=pQTangent.x*qx2; qxqy2:=pQTangent.x*qy2; qxqz2:=pQTangent.x*qz2; qxqw2:=pQTangent.w*qx2; qyqy2:=pQTangent.y*qy2; qyqz2:=pQTangent.y*qz2; qyqw2:=pQTangent.w*qy2; qzqz2:=pQTangent.z*qz2; qzqw2:=pQTangent.w*qz2; RawComponents[0,0]:=1.0-(qyqy2+qzqz2); RawComponents[0,1]:=qxqy2+qzqw2; RawComponents[0,2]:=qxqz2-qyqw2; RawComponents[1,0]:=qxqy2-qzqw2; RawComponents[1,1]:=1.0-(qxqx2+qzqz2); RawComponents[1,2]:=qyqz2+qxqw2; RawComponents[2,0]:=(RawComponents[0,1]*RawComponents[1,2])-(RawComponents[0,2]*RawComponents[1,1]); RawComponents[2,1]:=(RawComponents[0,2]*RawComponents[1,0])-(RawComponents[0,0]*RawComponents[1,2]); RawComponents[2,2]:=(RawComponents[0,0]*RawComponents[1,1])-(RawComponents[0,1]*RawComponents[1,0]); {RawComponents[2,0]:=qxqz2+qyqw2; RawComponents[2,1]:=qyqz2-qxqw2; RawComponents[2,2]:=1.0-(qxqx2+qyqy2);} if pQTangent.w<0.0 then begin RawComponents[2,0]:=-RawComponents[2,0]; RawComponents[2,1]:=-RawComponents[2,1]; RawComponents[2,2]:=-RawComponents[2,2]; end; end; constructor TpvMatrix3x3.CreateRecomposed(const DecomposedMatrix3x3:TpvDecomposedMatrix3x3); begin self:=TpvMatrix3x3.CreateFromQuaternion(DecomposedMatrix3x3.Rotation); if DecomposedMatrix3x3.Skew.z<>0.0 then begin // YZ self:=TpvMatrix3x3.Create(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,DecomposedMatrix3x3.Skew.z,1.0)*self; end; if DecomposedMatrix3x3.Skew.y<>0.0 then begin // XZ self:=TpvMatrix3x3.Create(1.0,0.0,0.0, 0.0,1.0,0.0, DecomposedMatrix3x3.Skew.y,0.0,1.0)*self; end; if DecomposedMatrix3x3.Skew.x<>0.0 then begin // XY self:=TpvMatrix3x3.Create(1.0,0.0,0.0, DecomposedMatrix3x3.Skew.x,1.0,0.0, 0.0,0.0,1.0)*self; end; self:=TpvMatrix3x3.CreateScale(DecomposedMatrix3x3.Scale)*self; end; class operator TpvMatrix3x3.Implicit(const a:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[0,2]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; result.RawComponents[1,2]:=a; result.RawComponents[2,0]:=a; result.RawComponents[2,1]:=a; result.RawComponents[2,2]:=a; end; class operator TpvMatrix3x3.Explicit(const a:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[0,2]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; result.RawComponents[1,2]:=a; result.RawComponents[2,0]:=a; result.RawComponents[2,1]:=a; result.RawComponents[2,2]:=a; end; class operator TpvMatrix3x3.Equal(const a,b:TpvMatrix3x3):boolean; begin result:=SameValue(a.RawComponents[0,0],b.RawComponents[0,0]) and SameValue(a.RawComponents[0,1],b.RawComponents[0,1]) and SameValue(a.RawComponents[0,2],b.RawComponents[0,2]) and SameValue(a.RawComponents[1,0],b.RawComponents[1,0]) and SameValue(a.RawComponents[1,1],b.RawComponents[1,1]) and SameValue(a.RawComponents[1,2],b.RawComponents[1,2]) and SameValue(a.RawComponents[2,0],b.RawComponents[2,0]) and SameValue(a.RawComponents[2,1],b.RawComponents[2,1]) and SameValue(a.RawComponents[2,2],b.RawComponents[2,2]); end; class operator TpvMatrix3x3.NotEqual(const a,b:TpvMatrix3x3):boolean; begin result:=(not SameValue(a.RawComponents[0,0],b.RawComponents[0,0])) or (not SameValue(a.RawComponents[0,1],b.RawComponents[0,1])) or (not SameValue(a.RawComponents[0,2],b.RawComponents[0,2])) or (not SameValue(a.RawComponents[1,0],b.RawComponents[1,0])) or (not SameValue(a.RawComponents[1,1],b.RawComponents[1,1])) or (not SameValue(a.RawComponents[1,2],b.RawComponents[1,2])) or (not SameValue(a.RawComponents[2,0],b.RawComponents[2,0])) or (not SameValue(a.RawComponents[2,1],b.RawComponents[2,1])) or (not SameValue(a.RawComponents[2,2],b.RawComponents[2,2])); end; class operator TpvMatrix3x3.Inc(const a:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]+1.0; result.RawComponents[0,2]:=a.RawComponents[0,2]+1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]+1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]+1.0; result.RawComponents[1,2]:=a.RawComponents[1,2]+1.0; result.RawComponents[2,0]:=a.RawComponents[2,0]+1.0; result.RawComponents[2,1]:=a.RawComponents[2,1]+1.0; result.RawComponents[2,2]:=a.RawComponents[2,2]+1.0; end; class operator TpvMatrix3x3.Dec(const a:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]-1.0; result.RawComponents[0,2]:=a.RawComponents[0,2]-1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]-1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]-1.0; result.RawComponents[1,2]:=a.RawComponents[1,2]-1.0; result.RawComponents[2,0]:=a.RawComponents[2,0]-1.0; result.RawComponents[2,1]:=a.RawComponents[2,1]-1.0; result.RawComponents[2,2]:=a.RawComponents[2,2]-1.0; end; class operator TpvMatrix3x3.Add(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]+b.RawComponents[0,1]; result.RawComponents[0,2]:=a.RawComponents[0,2]+b.RawComponents[0,2]; result.RawComponents[1,0]:=a.RawComponents[1,0]+b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]+b.RawComponents[1,1]; result.RawComponents[1,2]:=a.RawComponents[1,2]+b.RawComponents[1,2]; result.RawComponents[2,0]:=a.RawComponents[2,0]+b.RawComponents[2,0]; result.RawComponents[2,1]:=a.RawComponents[2,1]+b.RawComponents[2,1]; result.RawComponents[2,2]:=a.RawComponents[2,2]+b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Add(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b; result.RawComponents[0,1]:=a.RawComponents[0,1]+b; result.RawComponents[0,2]:=a.RawComponents[0,2]+b; result.RawComponents[1,0]:=a.RawComponents[1,0]+b; result.RawComponents[1,1]:=a.RawComponents[1,1]+b; result.RawComponents[1,2]:=a.RawComponents[1,2]+b; result.RawComponents[2,0]:=a.RawComponents[2,0]+b; result.RawComponents[2,1]:=a.RawComponents[2,1]+b; result.RawComponents[2,2]:=a.RawComponents[2,2]+b; end; class operator TpvMatrix3x3.Add(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a+b.RawComponents[0,0]; result.RawComponents[0,1]:=a+b.RawComponents[0,1]; result.RawComponents[0,2]:=a+b.RawComponents[0,2]; result.RawComponents[1,0]:=a+b.RawComponents[1,0]; result.RawComponents[1,1]:=a+b.RawComponents[1,1]; result.RawComponents[1,2]:=a+b.RawComponents[1,2]; result.RawComponents[2,0]:=a+b.RawComponents[2,0]; result.RawComponents[2,1]:=a+b.RawComponents[2,1]; result.RawComponents[2,2]:=a+b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Subtract(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]-b.RawComponents[0,1]; result.RawComponents[0,2]:=a.RawComponents[0,2]-b.RawComponents[0,2]; result.RawComponents[1,0]:=a.RawComponents[1,0]-b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]-b.RawComponents[1,1]; result.RawComponents[1,2]:=a.RawComponents[1,2]-b.RawComponents[1,2]; result.RawComponents[2,0]:=a.RawComponents[2,0]-b.RawComponents[2,0]; result.RawComponents[2,1]:=a.RawComponents[2,1]-b.RawComponents[2,1]; result.RawComponents[2,2]:=a.RawComponents[2,2]-b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Subtract(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b; result.RawComponents[0,1]:=a.RawComponents[0,1]-b; result.RawComponents[0,2]:=a.RawComponents[0,2]-b; result.RawComponents[1,0]:=a.RawComponents[1,0]-b; result.RawComponents[1,1]:=a.RawComponents[1,1]-b; result.RawComponents[1,2]:=a.RawComponents[1,2]-b; result.RawComponents[2,0]:=a.RawComponents[2,0]-b; result.RawComponents[2,1]:=a.RawComponents[2,1]-b; result.RawComponents[2,2]:=a.RawComponents[2,2]-b; end; class operator TpvMatrix3x3.Subtract(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a-b.RawComponents[0,0]; result.RawComponents[0,1]:=a-b.RawComponents[0,1]; result.RawComponents[0,2]:=a-b.RawComponents[0,2]; result.RawComponents[1,0]:=a-b.RawComponents[1,0]; result.RawComponents[1,1]:=a-b.RawComponents[1,1]; result.RawComponents[1,2]:=a-b.RawComponents[1,2]; result.RawComponents[2,0]:=a-b.RawComponents[2,0]; result.RawComponents[2,1]:=a-b.RawComponents[2,1]; result.RawComponents[2,2]:=a-b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Multiply(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=(a.RawComponents[0,0]*b.RawComponents[0,0])+(a.RawComponents[0,1]*b.RawComponents[1,0])+(a.RawComponents[0,2]*b.RawComponents[2,0]); result.RawComponents[0,1]:=(a.RawComponents[0,0]*b.RawComponents[0,1])+(a.RawComponents[0,1]*b.RawComponents[1,1])+(a.RawComponents[0,2]*b.RawComponents[2,1]); result.RawComponents[0,2]:=(a.RawComponents[0,0]*b.RawComponents[0,2])+(a.RawComponents[0,1]*b.RawComponents[1,2])+(a.RawComponents[0,2]*b.RawComponents[2,2]); result.RawComponents[1,0]:=(a.RawComponents[1,0]*b.RawComponents[0,0])+(a.RawComponents[1,1]*b.RawComponents[1,0])+(a.RawComponents[1,2]*b.RawComponents[2,0]); result.RawComponents[1,1]:=(a.RawComponents[1,0]*b.RawComponents[0,1])+(a.RawComponents[1,1]*b.RawComponents[1,1])+(a.RawComponents[1,2]*b.RawComponents[2,1]); result.RawComponents[1,2]:=(a.RawComponents[1,0]*b.RawComponents[0,2])+(a.RawComponents[1,1]*b.RawComponents[1,2])+(a.RawComponents[1,2]*b.RawComponents[2,2]); result.RawComponents[2,0]:=(a.RawComponents[2,0]*b.RawComponents[0,0])+(a.RawComponents[2,1]*b.RawComponents[1,0])+(a.RawComponents[2,2]*b.RawComponents[2,0]); result.RawComponents[2,1]:=(a.RawComponents[2,0]*b.RawComponents[0,1])+(a.RawComponents[2,1]*b.RawComponents[1,1])+(a.RawComponents[2,2]*b.RawComponents[2,1]); result.RawComponents[2,2]:=(a.RawComponents[2,0]*b.RawComponents[0,2])+(a.RawComponents[2,1]*b.RawComponents[1,2])+(a.RawComponents[2,2]*b.RawComponents[2,2]); end; class operator TpvMatrix3x3.Multiply(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]*b; result.RawComponents[0,1]:=a.RawComponents[0,1]*b; result.RawComponents[0,2]:=a.RawComponents[0,2]*b; result.RawComponents[1,0]:=a.RawComponents[1,0]*b; result.RawComponents[1,1]:=a.RawComponents[1,1]*b; result.RawComponents[1,2]:=a.RawComponents[1,2]*b; result.RawComponents[2,0]:=a.RawComponents[2,0]*b; result.RawComponents[2,1]:=a.RawComponents[2,1]*b; result.RawComponents[2,2]:=a.RawComponents[2,2]*b; end; class operator TpvMatrix3x3.Multiply(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a*b.RawComponents[0,0]; result.RawComponents[0,1]:=a*b.RawComponents[0,1]; result.RawComponents[0,2]:=a*b.RawComponents[0,2]; result.RawComponents[1,0]:=a*b.RawComponents[1,0]; result.RawComponents[1,1]:=a*b.RawComponents[1,1]; result.RawComponents[1,2]:=a*b.RawComponents[1,2]; result.RawComponents[2,0]:=a*b.RawComponents[2,0]; result.RawComponents[2,1]:=a*b.RawComponents[2,1]; result.RawComponents[2,2]:=a*b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Multiply(const a:TpvMatrix3x3;const b:TpvVector2):TpvVector2; begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+a.RawComponents[2,0]; result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+a.RawComponents[2,1]; end; class operator TpvMatrix3x3.Multiply(const a:TpvVector2;const b:TpvMatrix3x3):TpvVector2; begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+b.RawComponents[0,2]; result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+b.RawComponents[1,2]; end; class operator TpvMatrix3x3.Multiply(const a:TpvMatrix3x3;const b:TpvVector3):TpvVector3; begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+(a.RawComponents[2,0]*b.z); result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+(a.RawComponents[2,1]*b.z); result.z:=(a.RawComponents[0,2]*b.x)+(a.RawComponents[1,2]*b.y)+(a.RawComponents[2,2]*b.z); end; class operator TpvMatrix3x3.Multiply(const a:TpvVector3;const b:TpvMatrix3x3):TpvVector3; begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+(a.z*b.RawComponents[0,2]); result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+(a.z*b.RawComponents[1,2]); result.z:=(a.x*b.RawComponents[2,0])+(a.y*b.RawComponents[2,1])+(a.z*b.RawComponents[2,2]); end; class operator TpvMatrix3x3.Multiply(const a:TpvMatrix3x3;const b:TpvVector4):TpvVector4; begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+(a.RawComponents[2,0]*b.z); result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+(a.RawComponents[2,1]*b.z); result.z:=(a.RawComponents[0,2]*b.x)+(a.RawComponents[1,2]*b.y)+(a.RawComponents[2,2]*b.z); result.w:=b.w; end; class operator TpvMatrix3x3.Multiply(const a:TpvVector4;const b:TpvMatrix3x3):TpvVector4; begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+(a.z*b.RawComponents[0,2]); result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+(a.z*b.RawComponents[1,2]); result.z:=(a.x*b.RawComponents[2,0])+(a.y*b.RawComponents[2,1])+(a.z*b.RawComponents[2,2]); result.w:=a.w; end; class operator TpvMatrix3x3.Multiply(const a:TpvMatrix3x3;const b:TpvPlane):TpvPlane; begin result.Normal:=a.Inverse.Transpose*b.Normal; result.Distance:=result.Normal.Dot(a*((b.Normal*b.Distance))); end; class operator TpvMatrix3x3.Multiply(const a:TpvPlane;const b:TpvMatrix3x3):TpvPlane; begin result:=b.Transpose*a; end; class operator TpvMatrix3x3.Divide(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result:=a*b.Inverse; end; class operator TpvMatrix3x3.Divide(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[0,2]:=a.RawComponents[0,2]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; result.RawComponents[1,2]:=a.RawComponents[1,2]/b; result.RawComponents[2,0]:=a.RawComponents[2,0]/b; result.RawComponents[2,1]:=a.RawComponents[2,1]/b; result.RawComponents[2,2]:=a.RawComponents[2,2]/b; end; class operator TpvMatrix3x3.Divide(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[0,2]:=a/b.RawComponents[0,2]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; result.RawComponents[1,2]:=a/b.RawComponents[1,2]; result.RawComponents[2,0]:=a/b.RawComponents[2,0]; result.RawComponents[2,1]:=a/b.RawComponents[2,1]; result.RawComponents[2,2]:=a/b.RawComponents[2,2]; end; class operator TpvMatrix3x3.IntDivide(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result:=a*b.Inverse; end; class operator TpvMatrix3x3.IntDivide(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[0,2]:=a.RawComponents[0,2]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; result.RawComponents[1,2]:=a.RawComponents[1,2]/b; result.RawComponents[2,0]:=a.RawComponents[2,0]/b; result.RawComponents[2,1]:=a.RawComponents[2,1]/b; result.RawComponents[2,2]:=a.RawComponents[2,2]/b; end; class operator TpvMatrix3x3.IntDivide(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[0,2]:=a/b.RawComponents[0,2]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; result.RawComponents[1,2]:=a/b.RawComponents[1,2]; result.RawComponents[2,0]:=a/b.RawComponents[2,0]; result.RawComponents[2,1]:=a/b.RawComponents[2,1]; result.RawComponents[2,2]:=a/b.RawComponents[2,2]; end; class operator TpvMatrix3x3.Modulus(const a,b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b.RawComponents[0,1]); result.RawComponents[0,2]:=Modulo(a.RawComponents[0,2],b.RawComponents[0,2]); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b.RawComponents[1,1]); result.RawComponents[1,2]:=Modulo(a.RawComponents[1,2],b.RawComponents[1,2]); result.RawComponents[2,0]:=Modulo(a.RawComponents[2,0],b.RawComponents[2,0]); result.RawComponents[2,1]:=Modulo(a.RawComponents[2,1],b.RawComponents[2,1]); result.RawComponents[2,2]:=Modulo(a.RawComponents[2,2],b.RawComponents[2,2]); end; class operator TpvMatrix3x3.Modulus(const a:TpvMatrix3x3;const b:TpvScalar):TpvMatrix3x3; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b); result.RawComponents[0,2]:=Modulo(a.RawComponents[0,2],b); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b); result.RawComponents[1,2]:=Modulo(a.RawComponents[1,2],b); result.RawComponents[2,0]:=Modulo(a.RawComponents[2,0],b); result.RawComponents[2,1]:=Modulo(a.RawComponents[2,1],b); result.RawComponents[2,2]:=Modulo(a.RawComponents[2,2],b); end; class operator TpvMatrix3x3.Modulus(const a:TpvScalar;const b:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=Modulo(a,b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a,b.RawComponents[0,1]); result.RawComponents[0,2]:=Modulo(a,b.RawComponents[0,2]); result.RawComponents[1,0]:=Modulo(a,b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a,b.RawComponents[1,1]); result.RawComponents[1,2]:=Modulo(a,b.RawComponents[1,2]); result.RawComponents[2,0]:=Modulo(a,b.RawComponents[2,0]); result.RawComponents[2,1]:=Modulo(a,b.RawComponents[2,1]); result.RawComponents[2,2]:=Modulo(a,b.RawComponents[2,2]); end; class operator TpvMatrix3x3.Negative(const a:TpvMatrix3x3):TpvMatrix3x3; begin result.RawComponents[0,0]:=-a.RawComponents[0,0]; result.RawComponents[0,1]:=-a.RawComponents[0,1]; result.RawComponents[0,2]:=-a.RawComponents[0,2]; result.RawComponents[1,0]:=-a.RawComponents[1,0]; result.RawComponents[1,1]:=-a.RawComponents[1,1]; result.RawComponents[1,2]:=-a.RawComponents[1,2]; result.RawComponents[2,0]:=-a.RawComponents[2,0]; result.RawComponents[2,1]:=-a.RawComponents[2,1]; result.RawComponents[2,2]:=-a.RawComponents[2,2]; end; class operator TpvMatrix3x3.Positive(const a:TpvMatrix3x3):TpvMatrix3x3; begin result:=a; end; function TpvMatrix3x3.GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; begin result:=RawComponents[pIndexA,pIndexB]; end; procedure TpvMatrix3x3.SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); begin RawComponents[pIndexA,pIndexB]:=pValue; end; function TpvMatrix3x3.GetColumn(const pIndex:TpvInt32):TpvVector3; begin result.x:=RawComponents[pIndex,0]; result.y:=RawComponents[pIndex,1]; result.z:=RawComponents[pIndex,2]; end; procedure TpvMatrix3x3.SetColumn(const pIndex:TpvInt32;const pValue:TpvVector3); begin RawComponents[pIndex,0]:=pValue.x; RawComponents[pIndex,1]:=pValue.y; RawComponents[pIndex,2]:=pValue.z; end; function TpvMatrix3x3.GetRow(const pIndex:TpvInt32):TpvVector3; begin result.x:=RawComponents[0,pIndex]; result.y:=RawComponents[1,pIndex]; result.z:=RawComponents[2,pIndex]; end; procedure TpvMatrix3x3.SetRow(const pIndex:TpvInt32;const pValue:TpvVector3); begin RawComponents[0,pIndex]:=pValue.x; RawComponents[1,pIndex]:=pValue.y; RawComponents[2,pIndex]:=pValue.z; end; function TpvMatrix3x3.Determinant:TpvScalar; begin result:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,0]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))); end; function TpvMatrix3x3.Inverse:TpvMatrix3x3; var d:TpvScalar; begin d:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,0]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))); if d<>0.0 then begin d:=1.0/d; result.RawComponents[0,0]:=((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1]))*d; result.RawComponents[0,1]:=((RawComponents[0,2]*RawComponents[2,1])-(RawComponents[0,1]*RawComponents[2,2]))*d; result.RawComponents[0,2]:=((RawComponents[0,1]*RawComponents[1,2])-(RawComponents[0,2]*RawComponents[1,1]))*d; result.RawComponents[1,0]:=((RawComponents[1,2]*RawComponents[2,0])-(RawComponents[1,0]*RawComponents[2,2]))*d; result.RawComponents[1,1]:=((RawComponents[0,0]*RawComponents[2,2])-(RawComponents[0,2]*RawComponents[2,0]))*d; result.RawComponents[1,2]:=((RawComponents[0,2]*RawComponents[1,0])-(RawComponents[0,0]*RawComponents[1,2]))*d; result.RawComponents[2,0]:=((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))*d; result.RawComponents[2,1]:=((RawComponents[0,1]*RawComponents[2,0])-(RawComponents[0,0]*RawComponents[2,1]))*d; result.RawComponents[2,2]:=((RawComponents[0,0]*RawComponents[1,1])-(RawComponents[0,1]*RawComponents[1,0]))*d; end else begin result:=TpvMatrix3x3.Identity; end; end; function TpvMatrix3x3.Transpose:TpvMatrix3x3; begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[1,0]; result.RawComponents[0,2]:=RawComponents[2,0]; result.RawComponents[1,0]:=RawComponents[0,1]; result.RawComponents[1,1]:=RawComponents[1,1]; result.RawComponents[1,2]:=RawComponents[2,1]; result.RawComponents[2,0]:=RawComponents[0,2]; result.RawComponents[2,1]:=RawComponents[1,2]; result.RawComponents[2,2]:=RawComponents[2,2]; end; function TpvMatrix3x3.EulerAngles:TpvVector3; var v0,v1:TpvVector3; begin if abs((-1.0)-RawComponents[0,2])<EPSILON then begin result.x:=0.0; result.y:=HalfPI; result.z:=ArcTan2(RawComponents[1,0],RawComponents[2,0]); end else if abs(1.0-RawComponents[0,2])<EPSILON then begin result.x:=0.0; result.y:=-HalfPI; result.z:=ArcTan2(-RawComponents[1,0],-RawComponents[2,0]); end else begin v0.x:=-ArcSin(RawComponents[0,2]); v1.x:=PI-v0.x; v0.y:=ArcTan2(RawComponents[1,2]/cos(v0.x),RawComponents[2,2]/cos(v0.x)); v1.y:=ArcTan2(RawComponents[1,2]/cos(v1.x),RawComponents[2,2]/cos(v1.x)); v0.z:=ArcTan2(RawComponents[0,1]/cos(v0.x),RawComponents[0,0]/cos(v0.x)); v1.z:=ArcTan2(RawComponents[0,1]/cos(v1.x),RawComponents[0,0]/cos(v1.x)); if v0.SquaredLength<v1.SquaredLength then begin result:=v0; end else begin result:=v1; end; end; end; function TpvMatrix3x3.Normalize:TpvMatrix3x3; begin result.Right:=Right.Normalize; result.Up:=Up.Normalize; result.Forwards:=Forwards.Normalize; end; function TpvMatrix3x3.OrthoNormalize:TpvMatrix3x3; begin result.Normal:=Normal.Normalize; result.Tangent:=(Tangent-(result.Normal*Tangent.Dot(result.Normal))).Normalize; result.Bitangent:=result.Normal.Cross(result.Tangent).Normalize; result.Bitangent:=result.Bitangent-(result.Normal*result.Bitangent.Dot(result.Normal)); result.Bitangent:=(result.Bitangent-(result.Tangent*result.Bitangent.Dot(result.Tangent))).Normalize; result.Tangent:=result.Bitangent.Cross(result.Normal).Normalize; result.Normal:=result.Tangent.Cross(result.Bitangent).Normalize; end; function TpvMatrix3x3.RobustOrthoNormalize(const Tolerance:TpvScalar=1e-3):TpvMatrix3x3; var Bisector,Axis:TpvVector3; begin begin if Normal.Length<Tolerance then begin // Degenerate case, compute new normal Normal:=Tangent.Cross(Bitangent); if Normal.Length<Tolerance then begin result.Tangent:=TpvVector3.XAxis; result.Bitangent:=TpvVector3.YAxis; result.Normal:=TpvVector3.ZAxis; exit; end; end; result.Normal:=Normal.Normalize; end; begin // Project tangent and bitangent onto the normal orthogonal plane result.Tangent:=Tangent-(result.Normal*Tangent.Dot(result.Normal)); result.Bitangent:=Bitangent-(result.Normal*Bitangent.Dot(result.Normal)); end; begin // Check for several degenerate cases if result.Tangent.Length<Tolerance then begin if result.Bitangent.Length<Tolerance then begin result.Tangent:=result.Normal.Normalize; if (result.Tangent.x<=result.Tangent.y) and (result.Tangent.x<=result.Tangent.z) then begin result.Tangent:=TpvVector3.XAxis; end else if (result.Tangent.y<=result.Tangent.x) and (result.Tangent.y<=result.Tangent.z) then begin result.Tangent:=TpvVector3.YAxis; end else begin result.Tangent:=TpvVector3.ZAxis; end; result.Tangent:=result.Tangent-(result.Normal*result.Tangent.Dot(result.Normal)); result.Bitangent:=result.Normal.Cross(result.Tangent).Normalize; end else begin result.Tangent:=result.Bitangent.Cross(result.Normal).Normalize; end; end else begin result.Tangent:=result.Tangent.Normalize; if result.Bitangent.Length<Tolerance then begin result.Bitangent:=result.Normal.Cross(result.Tangent).Normalize; end else begin result.Bitangent:=result.Bitangent.Normalize; Bisector:=result.Tangent+result.Bitangent; if Bisector.Length<Tolerance then begin Bisector:=result.Tangent; end else begin Bisector:=Bisector.Normalize; end; Axis:=Bisector.Cross(result.Normal).Normalize; if Axis.Dot(Tangent)>0.0 then begin result.Tangent:=(Bisector+Axis).Normalize; result.Bitangent:=(Bisector-Axis).Normalize; end else begin result.Tangent:=(Bisector-Axis).Normalize; result.Bitangent:=(Bisector+Axis).Normalize; end; end; end; end; result.Bitangent:=result.Normal.Cross(result.Tangent).Normalize; result.Tangent:=result.Bitangent.Cross(result.Normal).Normalize; result.Normal:=result.Tangent.Cross(result.Bitangent).Normalize; end; function TpvMatrix3x3.ToQuaternion:TpvQuaternion; var t,s:TpvScalar; begin t:=RawComponents[0,0]+(RawComponents[1,1]+RawComponents[2,2]); if t>2.9999999 then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end else if t>0.0000001 then begin s:=sqrt(1.0+t)*2.0; result.x:=(RawComponents[1,2]-RawComponents[2,1])/s; result.y:=(RawComponents[2,0]-RawComponents[0,2])/s; result.z:=(RawComponents[0,1]-RawComponents[1,0])/s; result.w:=s*0.25; end else if (RawComponents[0,0]>RawComponents[1,1]) and (RawComponents[0,0]>RawComponents[2,2]) then begin s:=sqrt(1.0+(RawComponents[0,0]-(RawComponents[1,1]+RawComponents[2,2])))*2.0; result.x:=s*0.25; result.y:=(RawComponents[1,0]+RawComponents[0,1])/s; result.z:=(RawComponents[2,0]+RawComponents[0,2])/s; result.w:=(RawComponents[1,2]-RawComponents[2,1])/s; end else if RawComponents[1,1]>RawComponents[2,2] then begin s:=sqrt(1.0+(RawComponents[1,1]-(RawComponents[0,0]+RawComponents[2,2])))*2.0; result.x:=(RawComponents[1,0]+RawComponents[0,1])/s; result.y:=s*0.25; result.z:=(RawComponents[2,1]+RawComponents[1,2])/s; result.w:=(RawComponents[2,0]-RawComponents[0,2])/s; end else begin s:=sqrt(1.0+(RawComponents[2,2]-(RawComponents[0,0]+RawComponents[1,1])))*2.0; result.x:=(RawComponents[2,0]+RawComponents[0,2])/s; result.y:=(RawComponents[2,1]+RawComponents[1,2])/s; result.z:=s*0.25; result.w:=(RawComponents[0,1]-RawComponents[1,0])/s; end; result:=result.Normalize; end; function TpvMatrix3x3.ToQTangent:TpvQuaternion; const Threshold=1.0/32767.0; var Scale,t,s,Renormalization:TpvScalar; begin if ((((((RawComponents[0,0]*RawComponents[1,1]*RawComponents[2,2])+ (RawComponents[0,1]*RawComponents[1,2]*RawComponents[2,0]) )+ (RawComponents[0,2]*RawComponents[1,0]*RawComponents[2,1]) )- (RawComponents[0,2]*RawComponents[1,1]*RawComponents[2,0]) )- (RawComponents[0,1]*RawComponents[1,0]*RawComponents[2,2]) )- (RawComponents[0,0]*RawComponents[1,2]*RawComponents[2,1]) )<0.0 then begin // Reflection matrix, so flip y axis in case the tangent frame encodes a reflection Scale:=-1.0; RawComponents[2,0]:=-RawComponents[2,0]; RawComponents[2,1]:=-RawComponents[2,1]; RawComponents[2,2]:=-RawComponents[2,2]; end else begin // Rotation matrix, so nothing is doing to do Scale:=1.0; end; begin // Convert to quaternion t:=RawComponents[0,0]+(RawComponents[1,1]+RawComponents[2,2]); if t>2.9999999 then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end else if t>0.0000001 then begin s:=sqrt(1.0+t)*2.0; result.x:=(RawComponents[1,2]-RawComponents[2,1])/s; result.y:=(RawComponents[2,0]-RawComponents[0,2])/s; result.z:=(RawComponents[0,1]-RawComponents[1,0])/s; result.w:=s*0.25; end else if (RawComponents[0,0]>RawComponents[1,1]) and (RawComponents[0,0]>RawComponents[2,2]) then begin s:=sqrt(1.0+(RawComponents[0,0]-(RawComponents[1,1]+RawComponents[2,2])))*2.0; result.x:=s*0.25; result.y:=(RawComponents[1,0]+RawComponents[0,1])/s; result.z:=(RawComponents[2,0]+RawComponents[0,2])/s; result.w:=(RawComponents[1,2]-RawComponents[2,1])/s; end else if RawComponents[1,1]>RawComponents[2,2] then begin s:=sqrt(1.0+(RawComponents[1,1]-(RawComponents[0,0]+RawComponents[2,2])))*2.0; result.x:=(RawComponents[1,0]+RawComponents[0,1])/s; result.y:=s*0.25; result.z:=(RawComponents[2,1]+RawComponents[1,2])/s; result.w:=(RawComponents[2,0]-RawComponents[0,2])/s; end else begin s:=sqrt(1.0+(RawComponents[2,2]-(RawComponents[0,0]+RawComponents[1,1])))*2.0; result.x:=(RawComponents[2,0]+RawComponents[0,2])/s; result.y:=(RawComponents[2,1]+RawComponents[1,2])/s; result.z:=s*0.25; result.w:=(RawComponents[0,1]-RawComponents[1,0])/s; end; result:=result.Normalize; end; begin // Make sure, that we don't end up with 0 as w component if abs(result.w)<=Threshold then begin Renormalization:=sqrt(1.0-sqr(Threshold)); result.x:=result.x*Renormalization; result.y:=result.y*Renormalization; result.z:=result.z*Renormalization; if result.w>0.0 then begin result.w:=Threshold; end else begin result.w:=-Threshold; end; end; end; if ((Scale<0.0) and (result.w>=0.0)) or ((Scale>=0.0) and (result.w<0.0)) then begin // Encode reflection into quaternion's w element by making sign of w negative, // if y axis needs to be flipped, otherwise it stays positive result.x:=-result.x; result.y:=-result.y; result.z:=-result.z; result.w:=-result.w; end; end; function TpvMatrix3x3.SimpleLerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=(self*(1.0-t))+(b*t); end; end; function TpvMatrix3x3.SimpleNlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; var Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.Length, Up.Length, Forwards.Length).Lerp(TpvVector3.Create(b.Right.Length, b.Up.Length, b.Forwards.Length), t); result:=TpvMatrix3x3.CreateFromQuaternion(Normalize.ToQuaternion.Nlerp(b.Normalize.ToQuaternion,t)); result.Right:=result.Right*Scale.x; result.Up:=result.Up*Scale.y; result.Forwards:=result.Forwards*Scale.z; end; end; function TpvMatrix3x3.SimpleSlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; var Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.Length, Up.Length, Forwards.Length).Lerp(TpvVector3.Create(b.Right.Length, b.Up.Length, b.Forwards.Length), t); result:=TpvMatrix3x3.CreateFromQuaternion(Normalize.ToQuaternion.Slerp(b.Normalize.ToQuaternion,t)); result.Right:=result.Right*Scale.x; result.Up:=result.Up*Scale.y; result.Forwards:=result.Forwards*Scale.z; end; end; function TpvMatrix3x3.SimpleElerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; var Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.Length, Up.Length, Forwards.Length).Lerp(TpvVector3.Create(b.Right.Length, b.Up.Length, b.Forwards.Length), t); result:=TpvMatrix3x3.CreateFromQuaternion(Normalize.ToQuaternion.Elerp(b.Normalize.ToQuaternion,t)); result.Right:=result.Right*Scale.x; result.Up:=result.Up*Scale.y; result.Forwards:=result.Forwards*Scale.z; end; end; function TpvMatrix3x3.SimpleSqlerp(const aB,aC,aD:TpvMatrix3x3;const aTime:TpvScalar):TpvMatrix3x3; begin result:=SimpleSlerp(aD,aTime).SimpleSlerp(aB.SimpleSlerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvMatrix3x3.Lerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix3x3.CreateRecomposed(Decompose.Lerp(b.Decompose,t)); end; end; function TpvMatrix3x3.Nlerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix3x3.CreateRecomposed(Decompose.Nlerp(b.Decompose,t)); end; end; function TpvMatrix3x3.Slerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix3x3.CreateRecomposed(Decompose.Slerp(b.Decompose,t)); end; end; function TpvMatrix3x3.Elerp(const b:TpvMatrix3x3;const t:TpvScalar):TpvMatrix3x3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix3x3.CreateRecomposed(Decompose.Elerp(b.Decompose,t)); end; end; function TpvMatrix3x3.Sqlerp(const aB,aC,aD:TpvMatrix3x3;const aTime:TpvScalar):TpvMatrix3x3; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvMatrix3x3.MulInverse(const a:TpvVector3):TpvVector3; var d:TpvScalar; begin d:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[2,1]*RawComponents[1,2])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[2,0]*RawComponents[1,2]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[2,0]*RawComponents[1,1]))); if d<>0.0 then begin d:=1.0/d; end; result.x:=((a.x*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))+(a.y*((RawComponents[1,2]*RawComponents[2,0])-(RawComponents[1,0]*RawComponents[2,2])))+(a.z*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))))*d; result.y:=((RawComponents[0,0]*((a.y*RawComponents[2,2])-(a.z*RawComponents[2,1])))+(RawComponents[0,1]*((a.z*RawComponents[2,0])-(a.x*RawComponents[2,2])))+(RawComponents[0,2]*((a.x*RawComponents[2,1])-(a.y*RawComponents[2,0]))))*d; result.z:=((RawComponents[0,0]*((RawComponents[1,1]*a.z)-(RawComponents[1,2]*a.y)))+(RawComponents[0,1]*((RawComponents[1,2]*a.x)-(RawComponents[1,0]*a.z)))+(RawComponents[0,2]*((RawComponents[1,0]*a.y)-(RawComponents[1,1]*a.x))))*d; end; function TpvMatrix3x3.MulInverse(const a:TpvVector4):TpvVector4; var d:TpvScalar; begin d:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[2,1]*RawComponents[1,2])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[2,0]*RawComponents[1,2]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[2,0]*RawComponents[1,1]))); if d<>0.0 then begin d:=1.0/d; end; result.x:=((a.x*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))+(a.y*((RawComponents[1,2]*RawComponents[2,0])-(RawComponents[1,0]*RawComponents[2,2])))+(a.z*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))))*d; result.y:=((RawComponents[0,0]*((a.y*RawComponents[2,2])-(a.z*RawComponents[2,1])))+(RawComponents[0,1]*((a.z*RawComponents[2,0])-(a.x*RawComponents[2,2])))+(RawComponents[0,2]*((a.x*RawComponents[2,1])-(a.y*RawComponents[2,0]))))*d; result.z:=((RawComponents[0,0]*((RawComponents[1,1]*a.z)-(RawComponents[1,2]*a.y)))+(RawComponents[0,1]*((RawComponents[1,2]*a.x)-(RawComponents[1,0]*a.z)))+(RawComponents[0,2]*((RawComponents[1,0]*a.y)-(RawComponents[1,1]*a.x))))*d; result.w:=a.w; end; function TpvMatrix3x3.Decompose:TpvDecomposedMatrix3x3; var LocalMatrix:TpvMatrix3x3; begin if (RawComponents[0,0]=1.0) and (RawComponents[0,1]=0.0) and (RawComponents[0,2]=0.0) and (RawComponents[1,0]=0.0) and (RawComponents[1,1]=1.0) and (RawComponents[1,2]=0.0) and (RawComponents[2,0]=0.0) and (RawComponents[2,1]=0.0) and (RawComponents[2,2]=1.0) then begin result.Scale:=TpvVector3.Create(1.0,1.0,1.0); result.Skew:=TpvVector3.Create(0.0,0.0,0.0); result.Rotation:=TpvQuaternion.Create(0.0,0.0,0.0,1.0); result.Valid:=true; end else if Determinant=0.0 then begin result.Valid:=false; end else begin LocalMatrix:=self; result.Scale.x:=LocalMatrix.Right.Length; LocalMatrix.Right:=LocalMatrix.Right.Normalize; result.Skew.x:=LocalMatrix.Right.Dot(LocalMatrix.Up); LocalMatrix.Up:=LocalMatrix.Up-(LocalMatrix.Right*result.Skew.x); result.Scale.y:=LocalMatrix.Up.Length; LocalMatrix.Up:=LocalMatrix.Up.Normalize; result.Skew.x:=result.Skew.x/result.Scale.y; result.Skew.y:=LocalMatrix.Right.Dot(LocalMatrix.Forwards); LocalMatrix.Forwards:=LocalMatrix.Forwards-(LocalMatrix.Right*result.Skew.y); result.Skew.z:=LocalMatrix.Up.Dot(LocalMatrix.Forwards); LocalMatrix.Forwards:=LocalMatrix.Forwards-(LocalMatrix.Up*result.Skew.z); result.Scale.z:=LocalMatrix.Forwards.Length; LocalMatrix.Forwards:=LocalMatrix.Forwards.Normalize; result.Skew.yz:=result.Skew.yz/result.Scale.z; if LocalMatrix.Right.Dot(LocalMatrix.Up.Cross(LocalMatrix.Forwards))<0.0 then begin result.Scale.x:=-result.Scale.x; LocalMatrix:=-LocalMatrix; end; result.Rotation:=LocalMatrix.ToQuaternion; result.Valid:=true; end; end; function TpvDecomposedMatrix4x4.Lerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Perspective:=Perspective.Lerp(b.Perspective,t); result.Translation:=Translation.Lerp(b.Translation,t); result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Lerp(b.Rotation,t); end; end; function TpvDecomposedMatrix4x4.Nlerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Perspective:=Perspective.Lerp(b.Perspective,t); result.Translation:=Translation.Lerp(b.Translation,t); result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Nlerp(b.Rotation,t); end; end; function TpvDecomposedMatrix4x4.Slerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Perspective:=Perspective.Lerp(b.Perspective,t); result.Translation:=Translation.Lerp(b.Translation,t); result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Slerp(b.Rotation,t); end; end; function TpvDecomposedMatrix4x4.Elerp(const b:TpvDecomposedMatrix4x4;const t:TpvScalar):TpvDecomposedMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result.Perspective:=Perspective.Lerp(b.Perspective,t); result.Translation:=Translation.Lerp(b.Translation,t); result.Scale:=Scale.Lerp(b.Scale,t); result.Skew:=Skew.Lerp(b.Skew,t); result.Rotation:=Rotation.Elerp(b.Rotation,t); end; end; function TpvDecomposedMatrix4x4.Sqlerp(const aB,aC,aD:TpvDecomposedMatrix4x4;const aTime:TpvScalar):TpvDecomposedMatrix4x4; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; {constructor TpvMatrix4x4.Create; begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end;//} constructor TpvMatrix4x4.Create(const pX:TpvScalar); begin RawComponents[0,0]:=pX; RawComponents[0,1]:=pX; RawComponents[0,2]:=pX; RawComponents[0,3]:=pX; RawComponents[1,0]:=pX; RawComponents[1,1]:=pX; RawComponents[1,2]:=pX; RawComponents[1,3]:=pX; RawComponents[2,0]:=pX; RawComponents[2,1]:=pX; RawComponents[2,2]:=pX; RawComponents[2,3]:=pX; RawComponents[3,0]:=pX; RawComponents[3,1]:=pX; RawComponents[3,2]:=pX; RawComponents[3,3]:=pX; end; constructor TpvMatrix4x4.Create(const pXX,pXY,pXZ,pXW,pYX,pYY,pYZ,pYW,pZX,pZY,pZZ,pZW,pWX,pWY,pWZ,pWW:TpvScalar); begin RawComponents[0,0]:=pXX; RawComponents[0,1]:=pXY; RawComponents[0,2]:=pXZ; RawComponents[0,3]:=pXW; RawComponents[1,0]:=pYX; RawComponents[1,1]:=pYY; RawComponents[1,2]:=pYZ; RawComponents[1,3]:=pYW; RawComponents[2,0]:=pZX; RawComponents[2,1]:=pZY; RawComponents[2,2]:=pZZ; RawComponents[2,3]:=pZW; RawComponents[3,0]:=pWX; RawComponents[3,1]:=pWY; RawComponents[3,2]:=pWZ; RawComponents[3,3]:=pWW; end; constructor TpvMatrix4x4.Create(const pX,pY,pZ:TpvVector3); begin RawComponents[0,0]:=pX.x; RawComponents[0,1]:=pX.y; RawComponents[0,2]:=pX.z; RawComponents[0,3]:=0.0; RawComponents[1,0]:=pY.x; RawComponents[1,1]:=pY.y; RawComponents[1,2]:=pY.z; RawComponents[1,3]:=0.0; RawComponents[2,0]:=pZ.x; RawComponents[2,1]:=pZ.y; RawComponents[2,2]:=pZ.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.Create(const pX,pY,pZ,pW:TpvVector3); begin RawComponents[0,0]:=pX.x; RawComponents[0,1]:=pX.y; RawComponents[0,2]:=pX.z; RawComponents[0,3]:=0.0; RawComponents[1,0]:=pY.x; RawComponents[1,1]:=pY.y; RawComponents[1,2]:=pY.z; RawComponents[1,3]:=0.0; RawComponents[2,0]:=pZ.x; RawComponents[2,1]:=pZ.y; RawComponents[2,2]:=pZ.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=pW.x; RawComponents[3,1]:=pW.y; RawComponents[3,2]:=pW.z; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.Create(const pX,pY,pZ,pW:TpvVector4); begin RawComponents[0,0]:=pX.x; RawComponents[0,1]:=pX.y; RawComponents[0,2]:=pX.z; RawComponents[0,3]:=pX.w; RawComponents[1,0]:=pY.x; RawComponents[1,1]:=pY.y; RawComponents[1,2]:=pY.z; RawComponents[1,3]:=pY.w; RawComponents[2,0]:=pZ.x; RawComponents[2,1]:=pZ.y; RawComponents[2,2]:=pZ.z; RawComponents[2,3]:=pZ.w; RawComponents[3,0]:=pW.x; RawComponents[3,1]:=pW.y; RawComponents[3,2]:=pW.z; RawComponents[3,3]:=pW.w; end; constructor TpvMatrix4x4.Create(const pMatrix:TpvMatrix3x3); begin RawComponents[0,0]:=pMatrix.RawComponents[0,0]; RawComponents[0,1]:=pMatrix.RawComponents[0,1]; RawComponents[0,2]:=pMatrix.RawComponents[0,2]; RawComponents[0,3]:=0.0; RawComponents[1,0]:=pMatrix.RawComponents[1,0]; RawComponents[1,1]:=pMatrix.RawComponents[1,1]; RawComponents[1,2]:=pMatrix.RawComponents[1,2]; RawComponents[1,3]:=0.0; RawComponents[2,0]:=pMatrix.RawComponents[2,0]; RawComponents[2,1]:=pMatrix.RawComponents[2,1]; RawComponents[2,2]:=pMatrix.RawComponents[2,2]; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateRotateX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; SinCos(Angle,RawComponents[1,2],RawComponents[1,1]); RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=-RawComponents[1,2]; RawComponents[2,2]:=RawComponents[1,1]; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateRotateY(const Angle:TpvScalar); begin SinCos(Angle,RawComponents[2,0],RawComponents[0,0]); RawComponents[0,1]:=0.0; RawComponents[0,2]:=-RawComponents[2,0]; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=RawComponents[0,0]; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateRotateZ(const Angle:TpvScalar); begin SinCos(Angle,RawComponents[0,1],RawComponents[0,0]); RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=-RawComponents[0,1]; RawComponents[1,1]:=RawComponents[0,0]; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateRotate(const Angle:TpvScalar;const Axis:TpvVector3); var SinusAngle,CosinusAngle:TpvScalar; begin SinCos(Angle,SinusAngle,CosinusAngle); RawComponents[0,0]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.x)); RawComponents[1,0]:=((1.0-CosinusAngle)*Axis.x*Axis.y)-(Axis.z*SinusAngle); RawComponents[2,0]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.y*SinusAngle); RawComponents[0,3]:=0.0; RawComponents[0,1]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.z*SinusAngle); RawComponents[1,1]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.y)); RawComponents[2,1]:=((1.0-CosinusAngle)*Axis.y*Axis.z)-(Axis.x*SinusAngle); RawComponents[1,3]:=0.0; RawComponents[0,2]:=((1.0-CosinusAngle)*Axis.x*Axis.z)-(Axis.y*SinusAngle); RawComponents[1,2]:=((1.0-CosinusAngle)*Axis.y*Axis.z)+(Axis.x*SinusAngle); RawComponents[2,2]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.z)); RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateRotation(const pMatrix:TpvMatrix4x4); begin RawComponents[0,0]:=pMatrix.RawComponents[0,0]; RawComponents[0,1]:=pMatrix.RawComponents[0,1]; RawComponents[0,2]:=pMatrix.RawComponents[0,2]; RawComponents[0,3]:=0.0; RawComponents[1,0]:=pMatrix.RawComponents[1,0]; RawComponents[1,1]:=pMatrix.RawComponents[1,1]; RawComponents[1,2]:=pMatrix.RawComponents[1,2]; RawComponents[1,3]:=0.0; RawComponents[2,0]:=pMatrix.RawComponents[2,0]; RawComponents[2,1]:=pMatrix.RawComponents[2,1]; RawComponents[2,2]:=pMatrix.RawComponents[2,2]; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewYX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=tan(Angle); RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewZX(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=tan(Angle); RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewXY(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=tan(Angle); RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewZY(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=tan(Angle); RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewXZ(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=tan(Angle); RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateSkewYZ(const Angle:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=tan(Angle); RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateScale(const sx,sy:TpvScalar); begin RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateScale(const pScale:TpvVector2); begin RawComponents[0,0]:=pScale.x; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=pScale.y; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateScale(const sx,sy,sz:TpvScalar); begin RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=sz; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateScale(const pScale:TpvVector3); begin RawComponents[0,0]:=pScale.x; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=pScale.y; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=pScale.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateScale(const sx,sy,sz,sw:TpvScalar); begin RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=sz; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=sw; end; constructor TpvMatrix4x4.CreateScale(const pScale:TpvVector4); begin RawComponents[0,0]:=pScale.x; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=pScale.y; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=pScale.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=pScale.w; end; constructor TpvMatrix4x4.CreateTranslation(const tx,ty:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=tx; RawComponents[3,1]:=ty; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateTranslation(const pTranslation:TpvVector2); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=pTranslation.x; RawComponents[3,1]:=pTranslation.y; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateTranslation(const tx,ty,tz:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=tx; RawComponents[3,1]:=ty; RawComponents[3,2]:=tz; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateTranslation(const pTranslation:TpvVector3); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=pTranslation.x; RawComponents[3,1]:=pTranslation.y; RawComponents[3,2]:=pTranslation.z; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateTranslation(const tx,ty,tz,tw:TpvScalar); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=tx; RawComponents[3,1]:=ty; RawComponents[3,2]:=tz; RawComponents[3,3]:=tw; end; constructor TpvMatrix4x4.CreateTranslation(const pTranslation:TpvVector4); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=0.0; RawComponents[3,0]:=pTranslation.x; RawComponents[3,1]:=pTranslation.y; RawComponents[3,2]:=pTranslation.z; RawComponents[3,3]:=pTranslation.w; end; constructor TpvMatrix4x4.CreateTranslated(const pMatrix:TpvMatrix4x4;pTranslation:TpvVector3); begin RawComponents[0]:=pMatrix.RawComponents[0]; RawComponents[1]:=pMatrix.RawComponents[1]; RawComponents[2]:=pMatrix.RawComponents[2]; RawComponents[3,0]:=(pMatrix.RawComponents[0,0]*pTranslation.x)+(pMatrix.RawComponents[1,0]*pTranslation.y)+(pMatrix.RawComponents[2,0]*pTranslation.z)+pMatrix.RawComponents[3,0]; RawComponents[3,1]:=(pMatrix.RawComponents[0,1]*pTranslation.x)+(pMatrix.RawComponents[1,1]*pTranslation.y)+(pMatrix.RawComponents[2,1]*pTranslation.z)+pMatrix.RawComponents[3,1]; RawComponents[3,2]:=(pMatrix.RawComponents[0,2]*pTranslation.x)+(pMatrix.RawComponents[1,2]*pTranslation.y)+(pMatrix.RawComponents[2,2]*pTranslation.z)+pMatrix.RawComponents[3,2]; RawComponents[3,3]:=(pMatrix.RawComponents[0,3]*pTranslation.x)+(pMatrix.RawComponents[1,3]*pTranslation.y)+(pMatrix.RawComponents[2,3]*pTranslation.z)+pMatrix.RawComponents[3,3]; end; constructor TpvMatrix4x4.CreateTranslated(const pMatrix:TpvMatrix4x4;pTranslation:TpvVector4); begin RawComponents[0]:=pMatrix.RawComponents[0]; RawComponents[1]:=pMatrix.RawComponents[1]; RawComponents[2]:=pMatrix.RawComponents[2]; RawComponents[3,0]:=(pMatrix.RawComponents[0,0]*pTranslation.x)+(pMatrix.RawComponents[1,0]*pTranslation.y)+(pMatrix.RawComponents[2,0]*pTranslation.z)+(pMatrix.RawComponents[3,0]*pTranslation.w); RawComponents[3,1]:=(pMatrix.RawComponents[0,1]*pTranslation.x)+(pMatrix.RawComponents[1,1]*pTranslation.y)+(pMatrix.RawComponents[2,1]*pTranslation.z)+(pMatrix.RawComponents[3,1]*pTranslation.w); RawComponents[3,2]:=(pMatrix.RawComponents[0,2]*pTranslation.x)+(pMatrix.RawComponents[1,2]*pTranslation.y)+(pMatrix.RawComponents[2,2]*pTranslation.z)+(pMatrix.RawComponents[3,2]*pTranslation.w); RawComponents[3,3]:=(pMatrix.RawComponents[0,3]*pTranslation.x)+(pMatrix.RawComponents[1,3]*pTranslation.y)+(pMatrix.RawComponents[2,3]*pTranslation.z)+(pMatrix.RawComponents[3,3]*pTranslation.w); end; constructor TpvMatrix4x4.CreateFromToRotation(const FromDirection,ToDirection:TpvVector3); var e,h,hvx,hvz,hvxy,hvxz,hvyz:TpvScalar; x,u,v,c:TpvVector3; begin e:=FromDirection.Dot(ToDirection); if abs(e)>(1.0-EPSILON) then begin x:=FromDirection.Abs; if x.x<x.y then begin if x.x<x.z then begin x.x:=1.0; x.y:=0.0; x.z:=0.0; end else begin x.x:=0.0; x.y:=0.0; x.z:=1.0; end; end else begin if x.y<x.z then begin x.x:=0.0; x.y:=1.0; x.z:=0.0; end else begin x.x:=0.0; x.y:=0.0; x.z:=1.0; end; end; u:=x-FromDirection; v:=x-ToDirection; c.x:=2.0/(sqr(u.x)+sqr(u.y)+sqr(u.z)); c.y:=2.0/(sqr(v.x)+sqr(v.y)+sqr(v.z)); c.z:=c.x*c.y*((u.x*v.x)+(u.y*v.y)+(u.z*v.z)); RawComponents[0,0]:=1.0+((c.z*(v.x*u.x))-((c.y*(v.x*v.x))+(c.x*(u.x*u.x)))); RawComponents[0,1]:=(c.z*(v.x*u.y))-((c.y*(v.x*v.y))+(c.x*(u.x*u.y))); RawComponents[0,2]:=(c.z*(v.x*u.z))-((c.y*(v.x*v.z))+(c.x*(u.x*u.z))); RawComponents[0,3]:=0.0; RawComponents[1,0]:=(c.z*(v.y*u.x))-((c.y*(v.y*v.x))+(c.x*(u.y*u.x))); RawComponents[1,1]:=1.0+((c.z*(v.y*u.y))-((c.y*(v.y*v.y))+(c.x*(u.y*u.y)))); RawComponents[1,2]:=(c.z*(v.y*u.z))-((c.y*(v.y*v.z))+(c.x*(u.y*u.z))); RawComponents[1,3]:=0.0; RawComponents[2,0]:=(c.z*(v.z*u.x))-((c.y*(v.z*v.x))+(c.x*(u.z*u.x))); RawComponents[2,1]:=(c.z*(v.z*u.y))-((c.y*(v.z*v.y))+(c.x*(u.z*u.y))); RawComponents[2,2]:=1.0+((c.z*(v.z*u.z))-((c.y*(v.z*v.z))+(c.x*(u.z*u.z)))); RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end else begin v:=FromDirection.Cross(ToDirection); h:=1.0/(1.0+e); hvx:=h*v.x; hvz:=h*v.z; hvxy:=hvx*v.y; hvxz:=hvx*v.z; hvyz:=hvz*v.y; RawComponents[0,0]:=e+(hvx*v.x); RawComponents[0,1]:=hvxy-v.z; RawComponents[0,2]:=hvxz+v.y; RawComponents[0,3]:=0.0; RawComponents[1,0]:=hvxy+v.z; RawComponents[1,1]:=e+(h*sqr(v.y)); RawComponents[1,2]:=hvyz-v.x; RawComponents[1,3]:=0.0; RawComponents[2,0]:=hvxz-v.y; RawComponents[2,1]:=hvyz+v.x; RawComponents[2,2]:=e+(hvz*v.z); RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; end; constructor TpvMatrix4x4.CreateConstruct(const pForwards,pUp:TpvVector3); var RightVector,UpVector,ForwardVector:TpvVector3; begin ForwardVector:=(-pForwards).Normalize; RightVector:=pUp.Cross(ForwardVector).Normalize; UpVector:=ForwardVector.Cross(RightVector).Normalize; RawComponents[0,0]:=RightVector.x; RawComponents[0,1]:=RightVector.y; RawComponents[0,2]:=RightVector.z; RawComponents[0,3]:=0.0; RawComponents[1,0]:=UpVector.x; RawComponents[1,1]:=UpVector.y; RawComponents[1,2]:=UpVector.z; RawComponents[1,3]:=0.0; RawComponents[2,0]:=ForwardVector.x; RawComponents[2,1]:=ForwardVector.y; RawComponents[2,2]:=ForwardVector.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOuterProduct(const u,v:TpvVector3); begin RawComponents[0,0]:=u.x*v.x; RawComponents[0,1]:=u.x*v.y; RawComponents[0,2]:=u.x*v.z; RawComponents[0,3]:=0.0; RawComponents[1,0]:=u.y*v.x; RawComponents[1,1]:=u.y*v.y; RawComponents[1,2]:=u.y*v.z; RawComponents[1,3]:=0.0; RawComponents[2,0]:=u.z*v.x; RawComponents[2,1]:=u.z*v.y; RawComponents[2,2]:=u.z*v.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateFromQuaternion(ppvQuaternion:TpvQuaternion); var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TpvScalar; begin ppvQuaternion:=ppvQuaternion.Normalize; qx2:=ppvQuaternion.x+ppvQuaternion.x; qy2:=ppvQuaternion.y+ppvQuaternion.y; qz2:=ppvQuaternion.z+ppvQuaternion.z; qxqx2:=ppvQuaternion.x*qx2; qxqy2:=ppvQuaternion.x*qy2; qxqz2:=ppvQuaternion.x*qz2; qxqw2:=ppvQuaternion.w*qx2; qyqy2:=ppvQuaternion.y*qy2; qyqz2:=ppvQuaternion.y*qz2; qyqw2:=ppvQuaternion.w*qy2; qzqz2:=ppvQuaternion.z*qz2; qzqw2:=ppvQuaternion.w*qz2; RawComponents[0,0]:=1.0-(qyqy2+qzqz2); RawComponents[0,1]:=qxqy2+qzqw2; RawComponents[0,2]:=qxqz2-qyqw2; RawComponents[0,3]:=0.0; RawComponents[1,0]:=qxqy2-qzqw2; RawComponents[1,1]:=1.0-(qxqx2+qzqz2); RawComponents[1,2]:=qyqz2+qxqw2; RawComponents[1,3]:=0.0; RawComponents[2,0]:=qxqz2+qyqw2; RawComponents[2,1]:=qyqz2-qxqw2; RawComponents[2,2]:=1.0-(qxqx2+qyqy2); RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateFromQTangent(pQTangent:TpvQuaternion); var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TpvScalar; begin pQTangent:=pQTangent.Normalize; qx2:=pQTangent.x+pQTangent.x; qy2:=pQTangent.y+pQTangent.y; qz2:=pQTangent.z+pQTangent.z; qxqx2:=pQTangent.x*qx2; qxqy2:=pQTangent.x*qy2; qxqz2:=pQTangent.x*qz2; qxqw2:=pQTangent.w*qx2; qyqy2:=pQTangent.y*qy2; qyqz2:=pQTangent.y*qz2; qyqw2:=pQTangent.w*qy2; qzqz2:=pQTangent.z*qz2; qzqw2:=pQTangent.w*qz2; RawComponents[0,0]:=1.0-(qyqy2+qzqz2); RawComponents[0,1]:=qxqy2+qzqw2; RawComponents[0,2]:=qxqz2-qyqw2; RawComponents[0,3]:=0.0; RawComponents[1,0]:=qxqy2-qzqw2; RawComponents[1,1]:=1.0-(qxqx2+qzqz2); RawComponents[1,2]:=qyqz2+qxqw2; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(RawComponents[0,1]*RawComponents[1,2])-(RawComponents[0,2]*RawComponents[1,1]); RawComponents[2,1]:=(RawComponents[0,2]*RawComponents[1,0])-(RawComponents[0,0]*RawComponents[1,2]); RawComponents[2,2]:=(RawComponents[0,0]*RawComponents[1,1])-(RawComponents[0,1]*RawComponents[1,0]); {RawComponents[2,0]:=qxqz2+qyqw2; RawComponents[2,1]:=qyqz2-qxqw2; RawComponents[2,2]:=1.0-(qxqx2+qyqy2);} if pQTangent.w<0.0 then begin RawComponents[2,0]:=-RawComponents[2,0]; RawComponents[2,1]:=-RawComponents[2,1]; RawComponents[2,2]:=-RawComponents[2,2]; end; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateReflect(const PpvPlane:TpvPlane); var Plane:TpvPlane; l:TpvScalar; begin Plane:=PpvPlane; l:=sqr(Plane.Normal.x)+sqr(Plane.Normal.y)+sqr(Plane.Normal.z); if l>0.0 then begin l:=sqrt(l); Plane.Normal.x:=Plane.Normal.x/l; Plane.Normal.y:=Plane.Normal.y/l; Plane.Normal.z:=Plane.Normal.z/l; Plane.Distance:=Plane.Distance/l; end else begin Plane.Normal.x:=0.0; Plane.Normal.y:=0.0; Plane.Normal.z:=0.0; Plane.Distance:=0.0; end; RawComponents[0,0]:=1.0-(2.0*(Plane.Normal.x*Plane.Normal.x)); RawComponents[0,1]:=-(2.0*(Plane.Normal.x*Plane.Normal.y)); RawComponents[0,2]:=-(2.0*(Plane.Normal.x*Plane.Normal.z)); RawComponents[0,3]:=0.0; RawComponents[1,0]:=-(2.0*(Plane.Normal.x*Plane.Normal.y)); RawComponents[1,1]:=1.0-(2.0*(Plane.Normal.y*Plane.Normal.y)); RawComponents[1,2]:=-(2.0*(Plane.Normal.y*Plane.Normal.z)); RawComponents[1,3]:=0.0; RawComponents[2,0]:=-(2.0*(Plane.Normal.z*Plane.Normal.x)); RawComponents[2,1]:=-(2.0*(Plane.Normal.z*Plane.Normal.y)); RawComponents[2,2]:=1.0-(2.0*(Plane.Normal.z*Plane.Normal.z)); RawComponents[2,3]:=0.0; RawComponents[3,0]:=-(2.0*(Plane.Distance*Plane.Normal.x)); RawComponents[3,1]:=-(2.0*(Plane.Distance*Plane.Normal.y)); RawComponents[3,2]:=-(2.0*(Plane.Distance*Plane.Normal.z)); RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateFrustumLeftHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=(zFar+zNear)/fmn; RawComponents[2,3]:=1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(-((zFar*zNear)*2.0))/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustumLeftHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=zFar/fmn; RawComponents[2,3]:=1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(-(zFar*zNear))/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustumLeftHandedOneToZero(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=(-zNear)/fmn; RawComponents[2,3]:=1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(zFar*zNear)/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustumRightHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=(-(zFar+zNear))/fmn; RawComponents[2,3]:=-1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(-((zFar*zNear)*2.0))/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustumRightHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=zFar/(zNear-zFar); RawComponents[2,3]:=-1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(-(zFar*zNear))/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustumRightHandedOneToZero(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=zNear/fmn; RawComponents[2,3]:=-1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(zNear*zFar)/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateFrustum(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=(zNear*2.0)/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=(zNear*2.0)/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=(Right+Left)/rml; RawComponents[2,1]:=(Top+Bottom)/tmb; RawComponents[2,2]:=(-(zFar+zNear))/fmn; RawComponents[2,3]:=-1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=(-((zFar*zNear)*2.0))/fmn; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreateOrthoLeftHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=2.0/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-(zFar+zNear))/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoLeftHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-zNear)/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoRightHandedNegativeOneToPositiveOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=(-2.0)/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-(zFar+zNear))/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoRightHandedZeroToOne(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=(-1.0)/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-zNear)/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrtho(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=(-2.0)/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-(zFar+zNear))/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoLH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0; RawComponents[3,1]:=0; RawComponents[3,2]:=(-zNear)/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoRH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0; RawComponents[3,1]:=0; RawComponents[3,2]:=zNear/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoOffCenterLH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(Right+Left)/rml; RawComponents[3,1]:=(Top+Bottom)/tmb; RawComponents[3,2]:=zNear/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateOrthoOffCenterRH(const Left,Right,Bottom,Top,zNear,zFar:TpvScalar); var rml,tmb,fmn:TpvScalar; begin rml:=Right-Left; tmb:=Top-Bottom; fmn:=zFar-zNear; RawComponents[0,0]:=2.0/rml; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=2.0/tmb; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=(-2.0)/fmn; RawComponents[2,3]:=0.0; RawComponents[3,0]:=(-(Right+Left))/rml; RawComponents[3,1]:=(-(Top+Bottom))/tmb; RawComponents[3,2]:=(-(zFar+zNear))/fmn; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreatePerspectiveLeftHandedNegativeOneToPositiveOne(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=(-(zFar+zNear))/(zFar-zNear); RawComponents[2,3]:=1.0; RawComponents[3,2]:=(-(2.0*zNear*zFar))/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveLeftHandedZeroToOne(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=zFar/(zFar-zNear); RawComponents[2,3]:=1.0; RawComponents[3,2]:=(-(zNear*zFar))/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveLeftHandedOneToZero(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=(-zNear)/(zFar-zNear); RawComponents[2,3]:=1.0; RawComponents[3,2]:=(zNear*zFar)/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveRightHandedNegativeOneToPositiveOne(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=(-(zFar+zNear))/(zFar-zNear); RawComponents[2,3]:=-1.0; RawComponents[3,2]:=(-(2.0*zNear*zFar))/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveRightHandedZeroToOne(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=zFar/(zNear-zFar); RawComponents[2,3]:=-1.0; RawComponents[3,2]:=(-(zNear*zFar))/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveRightHandedOneToZero(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=zNear/(zFar-zNear); RawComponents[2,3]:=-1.0; RawComponents[3,2]:=(zNear*zFar)/(zFar-zNear); RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreatePerspectiveReversedZ(const aFOVY,aAspectRatio,aZNear:TpvScalar); var t,sx,sy:TpvScalar; begin t:=tan(aFOVY*DEG2RAD*0.5); sy:=1.0/t; sx:=sy/aAspectRatio; RawComponents[0,0]:=sx; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=0.0; RawComponents[1,0]:=0.0; RawComponents[1,1]:=sy; RawComponents[1,2]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=0.0; RawComponents[2,3]:=-1.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=aZNear; RawComponents[3,3]:=0.0; end; constructor TpvMatrix4x4.CreatePerspective(const fovy,Aspect,zNear,zFar:TpvScalar); var Sine,Cotangent,ZDelta,Radians:TpvScalar; begin Radians:=(fovy*0.5)*DEG2RAD; ZDelta:=zFar-zNear; Sine:=sin(Radians); if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin Cotangent:=cos(Radians)/Sine; RawComponents:=TpvMatrix4x4.Identity.RawComponents; RawComponents[0,0]:=Cotangent/aspect; RawComponents[1,1]:=Cotangent; RawComponents[2,2]:=(-(zFar+zNear))/ZDelta; RawComponents[2,3]:=-1.0; RawComponents[3,2]:=(-(2.0*zNear*zFar))/ZDelta; RawComponents[3,3]:=0.0; end; end; constructor TpvMatrix4x4.CreateLookAt(const Eye,Center,Up:TpvVector3); var RightVector,UpVector,ForwardVector:TpvVector3; begin ForwardVector:=(Eye-Center).Normalize; RightVector:=(Up.Cross(ForwardVector)).Normalize; UpVector:=(ForwardVector.Cross(RightVector)).Normalize; RawComponents[0,0]:=RightVector.x; RawComponents[1,0]:=RightVector.y; RawComponents[2,0]:=RightVector.z; RawComponents[3,0]:=-((RightVector.x*Eye.x)+(RightVector.y*Eye.y)+(RightVector.z*Eye.z)); RawComponents[0,1]:=UpVector.x; RawComponents[1,1]:=UpVector.y; RawComponents[2,1]:=UpVector.z; RawComponents[3,1]:=-((UpVector.x*Eye.x)+(UpVector.y*Eye.y)+(UpVector.z*Eye.z)); RawComponents[0,2]:=ForwardVector.x; RawComponents[1,2]:=ForwardVector.y; RawComponents[2,2]:=ForwardVector.z; RawComponents[3,2]:=-((ForwardVector.x*Eye.x)+(ForwardVector.y*Eye.y)+(ForwardVector.z*Eye.z)); RawComponents[0,3]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,3]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateFill(const Eye,RightVector,UpVector,ForwardVector:TpvVector3); begin RawComponents[0,0]:=RightVector.x; RawComponents[1,0]:=RightVector.y; RawComponents[2,0]:=RightVector.z; RawComponents[3,0]:=-((RightVector.x*Eye.x)+(RightVector.y*Eye.y)+(RightVector.z*Eye.z)); RawComponents[0,1]:=UpVector.x; RawComponents[1,1]:=UpVector.y; RawComponents[2,1]:=UpVector.z; RawComponents[3,1]:=-((UpVector.x*Eye.x)+(UpVector.y*Eye.y)+(UpVector.z*Eye.z)); RawComponents[0,2]:=ForwardVector.x; RawComponents[1,2]:=ForwardVector.y; RawComponents[2,2]:=ForwardVector.z; RawComponents[3,2]:=-((ForwardVector.x*Eye.x)+(ForwardVector.y*Eye.y)+(ForwardVector.z*Eye.z)); RawComponents[0,3]:=0.0; RawComponents[1,3]:=0.0; RawComponents[2,3]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateConstructX(const xAxis:TpvVector3); var a,b,c:TpvVector3; begin a:=xAxis.Normalize; RawComponents[0,0]:=a.x; RawComponents[0,1]:=a.y; RawComponents[0,2]:=a.z; RawComponents[0,3]:=0.0; //b:=TpvVector3.Create(0.0,0.0,1.0).Cross(a).Normalize; b:=a.Perpendicular.Normalize; RawComponents[1,0]:=b.x; RawComponents[1,1]:=b.y; RawComponents[1,2]:=b.z; RawComponents[1,3]:=0.0; c:=b.Cross(a).Normalize; RawComponents[2,0]:=c.x; RawComponents[2,1]:=c.y; RawComponents[2,2]:=c.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateConstructY(const yAxis:TpvVector3); var a,b,c:TpvVector3; begin a:=yAxis.Normalize; RawComponents[1,0]:=a.x; RawComponents[1,1]:=a.y; RawComponents[1,2]:=a.z; RawComponents[1,3]:=0.0; b:=a.Perpendicular.Normalize; RawComponents[0,0]:=b.x; RawComponents[0,1]:=b.y; RawComponents[0,2]:=b.z; RawComponents[0,3]:=0.0; c:=b.Cross(a).Normalize; RawComponents[2,0]:=c.x; RawComponents[2,1]:=c.y; RawComponents[2,2]:=c.z; RawComponents[2,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateConstructZ(const zAxis:TpvVector3); var a,b,c:TpvVector3; begin a:=zAxis.Normalize; RawComponents[2,0]:=a.x; RawComponents[2,1]:=a.y; RawComponents[2,2]:=a.z; RawComponents[2,3]:=0.0; //b:=TpvVector3.Create(0.0,1.0,0.0).Cross(a).Normalize; b:=a.Perpendicular.Normalize; RawComponents[1,0]:=b.x; RawComponents[1,1]:=b.y; RawComponents[1,2]:=b.z; RawComponents[1,3]:=0.0; c:=b.Cross(a).Normalize; RawComponents[0,0]:=c.x; RawComponents[0,1]:=c.y; RawComponents[0,2]:=c.z; RawComponents[0,3]:=0.0; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=1.0; end; constructor TpvMatrix4x4.CreateProjectionMatrixClip(const ProjectionMatrix:TpvMatrix4x4;const ClipPlane:TpvPlane); var q,c:TpvVector4; begin RawComponents:=ProjectionMatrix.RawComponents; q.x:=(Sign(ClipPlane.Normal.x)+RawComponents[2,0])/RawComponents[0,0]; q.y:=(Sign(ClipPlane.Normal.y)+RawComponents[2,1])/RawComponents[1,1]; q.z:=-1.0; q.w:=(1.0+RawComponents[2,2])/RawComponents[3,2]; c.x:=ClipPlane.Normal.x; c.y:=ClipPlane.Normal.y; c.z:=ClipPlane.Normal.z; c.w:=ClipPlane.Distance; c:=c*(2.0/c.Dot(q)); RawComponents[0,2]:=c.x; RawComponents[1,2]:=c.y; RawComponents[2,2]:=c.z+1.0; RawComponents[3,2]:=c.w; end; constructor TpvMatrix4x4.CreateRecomposed(const DecomposedMatrix4x4:TpvDecomposedMatrix4x4); begin RawComponents[0,0]:=1.0; RawComponents[0,1]:=0.0; RawComponents[0,2]:=0.0; RawComponents[0,3]:=DecomposedMatrix4x4.Perspective.x; RawComponents[1,0]:=0.0; RawComponents[1,1]:=1.0; RawComponents[1,2]:=0.0; RawComponents[1,3]:=DecomposedMatrix4x4.Perspective.y; RawComponents[2,0]:=0.0; RawComponents[2,1]:=0.0; RawComponents[2,2]:=1.0; RawComponents[2,3]:=DecomposedMatrix4x4.Perspective.z; RawComponents[3,0]:=0.0; RawComponents[3,1]:=0.0; RawComponents[3,2]:=0.0; RawComponents[3,3]:=DecomposedMatrix4x4.Perspective.w; //self:=TpvMatrix4x4.CreateTranslation(DecomposedMatrix4x4.Translation)*self; Translation:=Translation+ (Right*DecomposedMatrix4x4.Translation.x)+ (Up*DecomposedMatrix4x4.Translation.y)+ (Forwards*DecomposedMatrix4x4.Translation.z); self:=TpvMatrix4x4.CreateFromQuaternion(DecomposedMatrix4x4.Rotation)*self; if DecomposedMatrix4x4.Skew.z<>0.0 then begin // YZ self:=TpvMatrix4x4.Create(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,DecomposedMatrix4x4.Skew.z,1.0,0.0, 0.0,0.0,0.0,1.0)*self; end; if DecomposedMatrix4x4.Skew.y<>0.0 then begin // XZ self:=TpvMatrix4x4.Create(1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, DecomposedMatrix4x4.Skew.y,0.0,1.0,0.0, 0.0,0.0,0.0,1.0)*self; end; if DecomposedMatrix4x4.Skew.x<>0.0 then begin // XY self:=TpvMatrix4x4.Create(1.0,0.0,0.0,0.0, DecomposedMatrix4x4.Skew.x,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0)*self; end; self:=TpvMatrix4x4.CreateScale(DecomposedMatrix4x4.Scale)*self; end; class operator TpvMatrix4x4.Implicit({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar):TpvMatrix4x4; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[0,2]:=a; result.RawComponents[0,3]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; result.RawComponents[1,2]:=a; result.RawComponents[1,3]:=a; result.RawComponents[2,0]:=a; result.RawComponents[2,1]:=a; result.RawComponents[2,2]:=a; result.RawComponents[2,3]:=a; result.RawComponents[3,0]:=a; result.RawComponents[3,1]:=a; result.RawComponents[3,2]:=a; result.RawComponents[3,3]:=a; end; class operator TpvMatrix4x4.Explicit({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar):TpvMatrix4x4; begin result.RawComponents[0,0]:=a; result.RawComponents[0,1]:=a; result.RawComponents[0,2]:=a; result.RawComponents[0,3]:=a; result.RawComponents[1,0]:=a; result.RawComponents[1,1]:=a; result.RawComponents[1,2]:=a; result.RawComponents[1,3]:=a; result.RawComponents[2,0]:=a; result.RawComponents[2,1]:=a; result.RawComponents[2,2]:=a; result.RawComponents[2,3]:=a; result.RawComponents[3,0]:=a; result.RawComponents[3,1]:=a; result.RawComponents[3,2]:=a; result.RawComponents[3,3]:=a; end; class operator TpvMatrix4x4.Equal({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):boolean; begin result:=SameValue(a.RawComponents[0,0],b.RawComponents[0,0]) and SameValue(a.RawComponents[0,1],b.RawComponents[0,1]) and SameValue(a.RawComponents[0,2],b.RawComponents[0,2]) and SameValue(a.RawComponents[0,3],b.RawComponents[0,3]) and SameValue(a.RawComponents[1,0],b.RawComponents[1,0]) and SameValue(a.RawComponents[1,1],b.RawComponents[1,1]) and SameValue(a.RawComponents[1,2],b.RawComponents[1,2]) and SameValue(a.RawComponents[1,3],b.RawComponents[1,3]) and SameValue(a.RawComponents[2,0],b.RawComponents[2,0]) and SameValue(a.RawComponents[2,1],b.RawComponents[2,1]) and SameValue(a.RawComponents[2,2],b.RawComponents[2,2]) and SameValue(a.RawComponents[2,3],b.RawComponents[2,3]) and SameValue(a.RawComponents[3,0],b.RawComponents[3,0]) and SameValue(a.RawComponents[3,1],b.RawComponents[3,1]) and SameValue(a.RawComponents[3,2],b.RawComponents[3,2]) and SameValue(a.RawComponents[3,3],b.RawComponents[3,3]); end; class operator TpvMatrix4x4.NotEqual({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):boolean; begin result:=(not SameValue(a.RawComponents[0,0],b.RawComponents[0,0])) or (not SameValue(a.RawComponents[0,1],b.RawComponents[0,1])) or (not SameValue(a.RawComponents[0,2],b.RawComponents[0,2])) or (not SameValue(a.RawComponents[0,3],b.RawComponents[0,3])) or (not SameValue(a.RawComponents[1,0],b.RawComponents[1,0])) or (not SameValue(a.RawComponents[1,1],b.RawComponents[1,1])) or (not SameValue(a.RawComponents[1,2],b.RawComponents[1,2])) or (not SameValue(a.RawComponents[1,3],b.RawComponents[1,3])) or (not SameValue(a.RawComponents[2,0],b.RawComponents[2,0])) or (not SameValue(a.RawComponents[2,1],b.RawComponents[2,1])) or (not SameValue(a.RawComponents[2,2],b.RawComponents[2,2])) or (not SameValue(a.RawComponents[2,3],b.RawComponents[2,3])) or (not SameValue(a.RawComponents[3,0],b.RawComponents[3,0])) or (not SameValue(a.RawComponents[3,1],b.RawComponents[3,1])) or (not SameValue(a.RawComponents[3,2],b.RawComponents[3,2])) or (not SameValue(a.RawComponents[3,3],b.RawComponents[3,3])); end; class operator TpvMatrix4x4.Inc({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const cOne:array[0..3] of single=(1.0,1.0,1.0,1.0); asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] {$ifdef cpu386} movups xmm4,dqword ptr [cOne] {$else} {$ifdef fpc} movups xmm4,dqword ptr [rip+cOne] {$else} movups xmm4,dqword ptr [rel cOne] {$endif} {$endif} addps xmm0,xmm4 addps xmm1,xmm4 addps xmm2,xmm4 addps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]+1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]+1.0; result.RawComponents[0,2]:=a.RawComponents[0,2]+1.0; result.RawComponents[0,3]:=a.RawComponents[0,3]+1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]+1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]+1.0; result.RawComponents[1,2]:=a.RawComponents[1,2]+1.0; result.RawComponents[1,3]:=a.RawComponents[1,3]+1.0; result.RawComponents[2,0]:=a.RawComponents[2,0]+1.0; result.RawComponents[2,1]:=a.RawComponents[2,1]+1.0; result.RawComponents[2,2]:=a.RawComponents[2,2]+1.0; result.RawComponents[2,3]:=a.RawComponents[2,3]+1.0; result.RawComponents[3,0]:=a.RawComponents[3,0]+1.0; result.RawComponents[3,1]:=a.RawComponents[3,1]+1.0; result.RawComponents[3,2]:=a.RawComponents[3,2]+1.0; result.RawComponents[3,3]:=a.RawComponents[3,3]+1.0; end; {$ifend} class operator TpvMatrix4x4.Dec({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const cOne:array[0..3] of single=(1.0,1.0,1.0,1.0); asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] {$ifdef cpu386} movups xmm4,dqword ptr [cOne] {$else} {$ifdef fpc} movups xmm4,dqword ptr [rip+cOne] {$else} movups xmm4,dqword ptr [rel cOne] {$endif} {$endif} subps xmm0,xmm4 subps xmm1,xmm4 subps xmm2,xmm4 subps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]-1.0; result.RawComponents[0,1]:=a.RawComponents[0,1]-1.0; result.RawComponents[0,2]:=a.RawComponents[0,2]-1.0; result.RawComponents[0,3]:=a.RawComponents[0,3]-1.0; result.RawComponents[1,0]:=a.RawComponents[1,0]-1.0; result.RawComponents[1,1]:=a.RawComponents[1,1]-1.0; result.RawComponents[1,2]:=a.RawComponents[1,2]-1.0; result.RawComponents[1,3]:=a.RawComponents[1,3]-1.0; result.RawComponents[2,0]:=a.RawComponents[2,0]-1.0; result.RawComponents[2,1]:=a.RawComponents[2,1]-1.0; result.RawComponents[2,2]:=a.RawComponents[2,2]-1.0; result.RawComponents[2,3]:=a.RawComponents[2,3]-1.0; result.RawComponents[3,0]:=a.RawComponents[3,0]-1.0; result.RawComponents[3,1]:=a.RawComponents[3,1]-1.0; result.RawComponents[3,2]:=a.RawComponents[3,2]-1.0; result.RawComponents[3,3]:=a.RawComponents[3,3]-1.0; end; {$ifend} class operator TpvMatrix4x4.Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] addps xmm0,xmm4 addps xmm1,xmm5 addps xmm2,xmm6 addps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]+b.RawComponents[0,1]; result.RawComponents[0,2]:=a.RawComponents[0,2]+b.RawComponents[0,2]; result.RawComponents[0,3]:=a.RawComponents[0,3]+b.RawComponents[0,3]; result.RawComponents[1,0]:=a.RawComponents[1,0]+b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]+b.RawComponents[1,1]; result.RawComponents[1,2]:=a.RawComponents[1,2]+b.RawComponents[1,2]; result.RawComponents[1,3]:=a.RawComponents[1,3]+b.RawComponents[1,3]; result.RawComponents[2,0]:=a.RawComponents[2,0]+b.RawComponents[2,0]; result.RawComponents[2,1]:=a.RawComponents[2,1]+b.RawComponents[2,1]; result.RawComponents[2,2]:=a.RawComponents[2,2]+b.RawComponents[2,2]; result.RawComponents[2,3]:=a.RawComponents[2,3]+b.RawComponents[2,3]; result.RawComponents[3,0]:=a.RawComponents[3,0]+b.RawComponents[3,0]; result.RawComponents[3,1]:=a.RawComponents[3,1]+b.RawComponents[3,1]; result.RawComponents[3,2]:=a.RawComponents[3,2]+b.RawComponents[3,2]; result.RawComponents[3,3]:=a.RawComponents[3,3]+b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Add({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movss xmm4,dword ptr [b] shufps xmm4,xmm4,$00 addps xmm0,xmm4 addps xmm1,xmm4 addps xmm2,xmm4 addps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]+b; result.RawComponents[0,1]:=a.RawComponents[0,1]+b; result.RawComponents[0,2]:=a.RawComponents[0,2]+b; result.RawComponents[0,3]:=a.RawComponents[0,3]+b; result.RawComponents[1,0]:=a.RawComponents[1,0]+b; result.RawComponents[1,1]:=a.RawComponents[1,1]+b; result.RawComponents[1,2]:=a.RawComponents[1,2]+b; result.RawComponents[1,3]:=a.RawComponents[1,3]+b; result.RawComponents[2,0]:=a.RawComponents[2,0]+b; result.RawComponents[2,1]:=a.RawComponents[2,1]+b; result.RawComponents[2,2]:=a.RawComponents[2,2]+b; result.RawComponents[2,3]:=a.RawComponents[2,3]+b; result.RawComponents[3,0]:=a.RawComponents[3,0]+b; result.RawComponents[3,1]:=a.RawComponents[3,1]+b; result.RawComponents[3,2]:=a.RawComponents[3,2]+b; result.RawComponents[3,3]:=a.RawComponents[3,3]+b; end; {$ifend} class operator TpvMatrix4x4.Add({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movss xmm0,dword ptr [a] shufps xmm0,xmm0,$00 movaps xmm1,xmm0 movaps xmm2,xmm0 movaps xmm3,xmm0 movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] addps xmm0,xmm4 addps xmm1,xmm5 addps xmm2,xmm6 addps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a+b.RawComponents[0,0]; result.RawComponents[0,1]:=a+b.RawComponents[0,1]; result.RawComponents[0,2]:=a+b.RawComponents[0,2]; result.RawComponents[0,3]:=a+b.RawComponents[0,3]; result.RawComponents[1,0]:=a+b.RawComponents[1,0]; result.RawComponents[1,1]:=a+b.RawComponents[1,1]; result.RawComponents[1,2]:=a+b.RawComponents[1,2]; result.RawComponents[1,3]:=a+b.RawComponents[1,3]; result.RawComponents[2,0]:=a+b.RawComponents[2,0]; result.RawComponents[2,1]:=a+b.RawComponents[2,1]; result.RawComponents[2,2]:=a+b.RawComponents[2,2]; result.RawComponents[2,3]:=a+b.RawComponents[2,3]; result.RawComponents[3,0]:=a+b.RawComponents[3,0]; result.RawComponents[3,1]:=a+b.RawComponents[3,1]; result.RawComponents[3,2]:=a+b.RawComponents[3,2]; result.RawComponents[3,3]:=a+b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] subps xmm0,xmm4 subps xmm1,xmm5 subps xmm2,xmm6 subps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b.RawComponents[0,0]; result.RawComponents[0,1]:=a.RawComponents[0,1]-b.RawComponents[0,1]; result.RawComponents[0,2]:=a.RawComponents[0,2]-b.RawComponents[0,2]; result.RawComponents[0,3]:=a.RawComponents[0,3]-b.RawComponents[0,3]; result.RawComponents[1,0]:=a.RawComponents[1,0]-b.RawComponents[1,0]; result.RawComponents[1,1]:=a.RawComponents[1,1]-b.RawComponents[1,1]; result.RawComponents[1,2]:=a.RawComponents[1,2]-b.RawComponents[1,2]; result.RawComponents[1,3]:=a.RawComponents[1,3]-b.RawComponents[1,3]; result.RawComponents[2,0]:=a.RawComponents[2,0]-b.RawComponents[2,0]; result.RawComponents[2,1]:=a.RawComponents[2,1]-b.RawComponents[2,1]; result.RawComponents[2,2]:=a.RawComponents[2,2]-b.RawComponents[2,2]; result.RawComponents[2,3]:=a.RawComponents[2,3]-b.RawComponents[2,3]; result.RawComponents[3,0]:=a.RawComponents[3,0]-b.RawComponents[3,0]; result.RawComponents[3,1]:=a.RawComponents[3,1]-b.RawComponents[3,1]; result.RawComponents[3,2]:=a.RawComponents[3,2]-b.RawComponents[3,2]; result.RawComponents[3,3]:=a.RawComponents[3,3]-b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Subtract({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movss xmm4,dword ptr [b] shufps xmm4,xmm4,$00 subps xmm0,xmm4 subps xmm1,xmm4 subps xmm2,xmm4 subps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]-b; result.RawComponents[0,1]:=a.RawComponents[0,1]-b; result.RawComponents[0,2]:=a.RawComponents[0,2]-b; result.RawComponents[0,3]:=a.RawComponents[0,3]-b; result.RawComponents[1,0]:=a.RawComponents[1,0]-b; result.RawComponents[1,1]:=a.RawComponents[1,1]-b; result.RawComponents[1,2]:=a.RawComponents[1,2]-b; result.RawComponents[1,3]:=a.RawComponents[1,3]-b; result.RawComponents[2,0]:=a.RawComponents[2,0]-b; result.RawComponents[2,1]:=a.RawComponents[2,1]-b; result.RawComponents[2,2]:=a.RawComponents[2,2]-b; result.RawComponents[2,3]:=a.RawComponents[2,3]-b; result.RawComponents[3,0]:=a.RawComponents[3,0]-b; result.RawComponents[3,1]:=a.RawComponents[3,1]-b; result.RawComponents[3,2]:=a.RawComponents[3,2]-b; result.RawComponents[3,3]:=a.RawComponents[3,3]-b; end; {$ifend} class operator TpvMatrix4x4.Subtract({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4): TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movss xmm0,dword ptr [a] shufps xmm0,xmm0,$00 movaps xmm1,xmm0 movaps xmm2,xmm0 movaps xmm3,xmm0 movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] subps xmm0,xmm4 subps xmm1,xmm5 subps xmm2,xmm6 subps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a-b.RawComponents[0,0]; result.RawComponents[0,1]:=a-b.RawComponents[0,1]; result.RawComponents[0,2]:=a-b.RawComponents[0,2]; result.RawComponents[0,3]:=a-b.RawComponents[0,3]; result.RawComponents[1,0]:=a-b.RawComponents[1,0]; result.RawComponents[1,1]:=a-b.RawComponents[1,1]; result.RawComponents[1,2]:=a-b.RawComponents[1,2]; result.RawComponents[1,3]:=a-b.RawComponents[1,3]; result.RawComponents[2,0]:=a-b.RawComponents[2,0]; result.RawComponents[2,1]:=a-b.RawComponents[2,1]; result.RawComponents[2,2]:=a-b.RawComponents[2,2]; result.RawComponents[2,3]:=a-b.RawComponents[2,3]; result.RawComponents[3,0]:=a-b.RawComponents[3,0]; result.RawComponents[3,1]:=a-b.RawComponents[3,1]; result.RawComponents[3,2]:=a-b.RawComponents[3,2]; result.RawComponents[3,3]:=a-b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movups xmm0,dqword ptr [b+0] movups xmm1,dqword ptr [b+16] movups xmm2,dqword ptr [b+32] movups xmm3,dqword ptr [b+48] movups xmm7,dqword ptr [a+0] pshufd xmm4,xmm7,$00 pshufd xmm5,xmm7,$55 pshufd xmm6,xmm7,$aa pshufd xmm7,xmm7,$ff mulps xmm4,xmm0 mulps xmm5,xmm1 mulps xmm6,xmm2 mulps xmm7,xmm3 addps xmm4,xmm5 addps xmm6,xmm7 addps xmm4,xmm6 movups dqword ptr [result+0],xmm4 movups xmm7,dqword ptr [a+16] pshufd xmm4,xmm7,$00 pshufd xmm5,xmm7,$55 pshufd xmm6,xmm7,$aa pshufd xmm7,xmm7,$ff mulps xmm4,xmm0 mulps xmm5,xmm1 mulps xmm6,xmm2 mulps xmm7,xmm3 addps xmm4,xmm5 addps xmm6,xmm7 addps xmm4,xmm6 movups dqword ptr [result+16],xmm4 movups xmm7,dqword ptr [a+32] pshufd xmm4,xmm7,$00 pshufd xmm5,xmm7,$55 pshufd xmm6,xmm7,$aa pshufd xmm7,xmm7,$ff mulps xmm4,xmm0 mulps xmm5,xmm1 mulps xmm6,xmm2 mulps xmm7,xmm3 addps xmm4,xmm5 addps xmm6,xmm7 addps xmm4,xmm6 movups dqword ptr [result+32],xmm4 movups xmm7,dqword ptr [a+48] pshufd xmm4,xmm7,$00 pshufd xmm5,xmm7,$55 pshufd xmm6,xmm7,$aa pshufd xmm7,xmm7,$ff mulps xmm4,xmm0 mulps xmm5,xmm1 mulps xmm6,xmm2 mulps xmm7,xmm3 addps xmm4,xmm5 addps xmm6,xmm7 addps xmm4,xmm6 movups dqword ptr [result+48],xmm4 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=(a.RawComponents[0,0]*b.RawComponents[0,0])+(a.RawComponents[0,1]*b.RawComponents[1,0])+(a.RawComponents[0,2]*b.RawComponents[2,0])+(a.RawComponents[0,3]*b.RawComponents[3,0]); result.RawComponents[0,1]:=(a.RawComponents[0,0]*b.RawComponents[0,1])+(a.RawComponents[0,1]*b.RawComponents[1,1])+(a.RawComponents[0,2]*b.RawComponents[2,1])+(a.RawComponents[0,3]*b.RawComponents[3,1]); result.RawComponents[0,2]:=(a.RawComponents[0,0]*b.RawComponents[0,2])+(a.RawComponents[0,1]*b.RawComponents[1,2])+(a.RawComponents[0,2]*b.RawComponents[2,2])+(a.RawComponents[0,3]*b.RawComponents[3,2]); result.RawComponents[0,3]:=(a.RawComponents[0,0]*b.RawComponents[0,3])+(a.RawComponents[0,1]*b.RawComponents[1,3])+(a.RawComponents[0,2]*b.RawComponents[2,3])+(a.RawComponents[0,3]*b.RawComponents[3,3]); result.RawComponents[1,0]:=(a.RawComponents[1,0]*b.RawComponents[0,0])+(a.RawComponents[1,1]*b.RawComponents[1,0])+(a.RawComponents[1,2]*b.RawComponents[2,0])+(a.RawComponents[1,3]*b.RawComponents[3,0]); result.RawComponents[1,1]:=(a.RawComponents[1,0]*b.RawComponents[0,1])+(a.RawComponents[1,1]*b.RawComponents[1,1])+(a.RawComponents[1,2]*b.RawComponents[2,1])+(a.RawComponents[1,3]*b.RawComponents[3,1]); result.RawComponents[1,2]:=(a.RawComponents[1,0]*b.RawComponents[0,2])+(a.RawComponents[1,1]*b.RawComponents[1,2])+(a.RawComponents[1,2]*b.RawComponents[2,2])+(a.RawComponents[1,3]*b.RawComponents[3,2]); result.RawComponents[1,3]:=(a.RawComponents[1,0]*b.RawComponents[0,3])+(a.RawComponents[1,1]*b.RawComponents[1,3])+(a.RawComponents[1,2]*b.RawComponents[2,3])+(a.RawComponents[1,3]*b.RawComponents[3,3]); result.RawComponents[2,0]:=(a.RawComponents[2,0]*b.RawComponents[0,0])+(a.RawComponents[2,1]*b.RawComponents[1,0])+(a.RawComponents[2,2]*b.RawComponents[2,0])+(a.RawComponents[2,3]*b.RawComponents[3,0]); result.RawComponents[2,1]:=(a.RawComponents[2,0]*b.RawComponents[0,1])+(a.RawComponents[2,1]*b.RawComponents[1,1])+(a.RawComponents[2,2]*b.RawComponents[2,1])+(a.RawComponents[2,3]*b.RawComponents[3,1]); result.RawComponents[2,2]:=(a.RawComponents[2,0]*b.RawComponents[0,2])+(a.RawComponents[2,1]*b.RawComponents[1,2])+(a.RawComponents[2,2]*b.RawComponents[2,2])+(a.RawComponents[2,3]*b.RawComponents[3,2]); result.RawComponents[2,3]:=(a.RawComponents[2,0]*b.RawComponents[0,3])+(a.RawComponents[2,1]*b.RawComponents[1,3])+(a.RawComponents[2,2]*b.RawComponents[2,3])+(a.RawComponents[2,3]*b.RawComponents[3,3]); result.RawComponents[3,0]:=(a.RawComponents[3,0]*b.RawComponents[0,0])+(a.RawComponents[3,1]*b.RawComponents[1,0])+(a.RawComponents[3,2]*b.RawComponents[2,0])+(a.RawComponents[3,3]*b.RawComponents[3,0]); result.RawComponents[3,1]:=(a.RawComponents[3,0]*b.RawComponents[0,1])+(a.RawComponents[3,1]*b.RawComponents[1,1])+(a.RawComponents[3,2]*b.RawComponents[2,1])+(a.RawComponents[3,3]*b.RawComponents[3,1]); result.RawComponents[3,2]:=(a.RawComponents[3,0]*b.RawComponents[0,2])+(a.RawComponents[3,1]*b.RawComponents[1,2])+(a.RawComponents[3,2]*b.RawComponents[2,2])+(a.RawComponents[3,3]*b.RawComponents[3,2]); result.RawComponents[3,3]:=(a.RawComponents[3,0]*b.RawComponents[0,3])+(a.RawComponents[3,1]*b.RawComponents[1,3])+(a.RawComponents[3,2]*b.RawComponents[2,3])+(a.RawComponents[3,3]*b.RawComponents[3,3]); end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movss xmm4,dword ptr [b] shufps xmm4,xmm4,$00 mulps xmm0,xmm4 mulps xmm1,xmm4 mulps xmm2,xmm4 mulps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]*b; result.RawComponents[0,1]:=a.RawComponents[0,1]*b; result.RawComponents[0,2]:=a.RawComponents[0,2]*b; result.RawComponents[0,3]:=a.RawComponents[0,3]*b; result.RawComponents[1,0]:=a.RawComponents[1,0]*b; result.RawComponents[1,1]:=a.RawComponents[1,1]*b; result.RawComponents[1,2]:=a.RawComponents[1,2]*b; result.RawComponents[1,3]:=a.RawComponents[1,3]*b; result.RawComponents[2,0]:=a.RawComponents[2,0]*b; result.RawComponents[2,1]:=a.RawComponents[2,1]*b; result.RawComponents[2,2]:=a.RawComponents[2,2]*b; result.RawComponents[2,3]:=a.RawComponents[2,3]*b; result.RawComponents[3,0]:=a.RawComponents[3,0]*b; result.RawComponents[3,1]:=a.RawComponents[3,1]*b; result.RawComponents[3,2]:=a.RawComponents[3,2]*b; result.RawComponents[3,3]:=a.RawComponents[3,3]*b; end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movss xmm0,dword ptr [a] shufps xmm0,xmm0,$00 movaps xmm1,xmm0 movaps xmm2,xmm0 movaps xmm3,xmm0 movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] mulps xmm0,xmm4 mulps xmm1,xmm5 mulps xmm2,xmm6 mulps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a*b.RawComponents[0,0]; result.RawComponents[0,1]:=a*b.RawComponents[0,1]; result.RawComponents[0,2]:=a*b.RawComponents[0,2]; result.RawComponents[0,3]:=a*b.RawComponents[0,3]; result.RawComponents[1,0]:=a*b.RawComponents[1,0]; result.RawComponents[1,1]:=a*b.RawComponents[1,1]; result.RawComponents[1,2]:=a*b.RawComponents[1,2]; result.RawComponents[1,3]:=a*b.RawComponents[1,3]; result.RawComponents[2,0]:=a*b.RawComponents[2,0]; result.RawComponents[2,1]:=a*b.RawComponents[2,1]; result.RawComponents[2,2]:=a*b.RawComponents[2,2]; result.RawComponents[2,3]:=a*b.RawComponents[2,3]; result.RawComponents[3,0]:=a*b.RawComponents[3,0]; result.RawComponents[3,1]:=a*b.RawComponents[3,1]; result.RawComponents[3,2]:=a*b.RawComponents[3,2]; result.RawComponents[3,3]:=a*b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector2):TpvVector2; begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+a.RawComponents[3,0]; result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+a.RawComponents[3,1]; end; class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector2;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector2; begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+b.RawComponents[0,3]; result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+b.RawComponents[1,3]; end; class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const Mask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); cOne:array[0..3] of TpvScalar=(0.0,0.0,0.0,1.0); {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} xorps xmm2,xmm2 movss xmm0,dword ptr [b+0] movss xmm1,dword ptr [b+4] movss xmm2,dword ptr [b+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 //movups xmm0,dqword ptr [b] // d c b a {$ifdef cpu386} movups xmm1,dqword ptr [Mask] movups xmm2,dqword ptr [cOne] {$else} {$ifdef fpc} movups xmm1,dqword ptr [rip+Mask] movups xmm2,dqword ptr [rip+cOne] {$else} movups xmm1,dqword ptr [rel Mask] movups xmm2,dqword ptr [rel cOne] {$endif} {$endif} andps xmm0,xmm1 addps xmm0,xmm2 movaps xmm1,xmm0 // d c b a movaps xmm2,xmm0 // d c b a movaps xmm3,xmm0 // d c b a shufps xmm0,xmm0,$00 // a a a a 00000000b shufps xmm1,xmm1,$55 // b b b b 01010101b shufps xmm2,xmm2,$aa // c c c c 10101010b shufps xmm3,xmm3,$ff // d d d d 11111111b movups xmm4,dqword ptr [a+0] movups xmm5,dqword ptr [a+16] movups xmm6,dqword ptr [a+32] movups xmm7,dqword ptr [a+48] mulps xmm0,xmm4 mulps xmm1,xmm5 mulps xmm2,xmm6 mulps xmm3,xmm7 addps xmm0,xmm1 addps xmm2,xmm3 addps xmm0,xmm2 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 //movups dqword ptr [result],xmm0 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+(a.RawComponents[2,0]*b.z)+a.RawComponents[3,0]; result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+(a.RawComponents[2,1]*b.z)+a.RawComponents[3,1]; result.z:=(a.RawComponents[0,2]*b.x)+(a.RawComponents[1,2]*b.y)+(a.RawComponents[2,2]*b.z)+a.RawComponents[3,2]; end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector3; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} const Mask:array[0..3] of TpvUInt32=($ffffffff,$ffffffff,$ffffffff,$00000000); cOne:array[0..3] of TpvScalar=(0.0,0.0,0.0,1.0); {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} xorps xmm2,xmm2 movss xmm0,dword ptr [a+0] movss xmm1,dword ptr [a+4] movss xmm2,dword ptr [a+8] movlhps xmm0,xmm1 shufps xmm0,xmm2,$88 //movups xmm0,dqword ptr [a] // d c b a {$ifdef cpu386} movups xmm1,dqword ptr [Mask] movups xmm2,dqword ptr [cOne] {$else} {$ifdef fpc} movups xmm1,dqword ptr [rip+Mask] movups xmm2,dqword ptr [rip+cOne] {$else} movups xmm1,dqword ptr [rel Mask] movups xmm2,dqword ptr [rel cOne] {$endif} {$endif} andps xmm0,xmm1 addps xmm0,xmm2 movaps xmm1,xmm0 // d c b a movaps xmm2,xmm0 // d c b a movaps xmm3,xmm0 // d c b a movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] mulps xmm0,xmm4 mulps xmm1,xmm5 mulps xmm2,xmm6 mulps xmm3,xmm7 addps xmm0,xmm1 addps xmm2,xmm3 addps xmm0,xmm2 movaps xmm1,xmm0 movaps xmm2,xmm0 shufps xmm1,xmm1,$55 shufps xmm2,xmm2,$aa movss dword ptr [result+0],xmm0 movss dword ptr [result+4],xmm1 movss dword ptr [result+8],xmm2 //movups dqword ptr [result],xmm0 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+(a.z*b.RawComponents[0,2])+b.RawComponents[0,3]; result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+(a.z*b.RawComponents[1,2])+b.RawComponents[1,3]; result.z:=(a.x*b.RawComponents[2,0])+(a.y*b.RawComponents[2,1])+(a.z*b.RawComponents[2,2])+b.RawComponents[2,3]; end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movups xmm0,dqword ptr [b] // d c b a movaps xmm1,xmm0 // d c b a movaps xmm2,xmm0 // d c b a movaps xmm3,xmm0 // d c b a shufps xmm0,xmm0,$00 // a a a a 00000000b shufps xmm1,xmm1,$55 // b b b b 01010101b shufps xmm2,xmm2,$aa // c c c c 10101010b shufps xmm3,xmm3,$ff // d d d d 11111111b movups xmm4,dqword ptr [a+0] movups xmm5,dqword ptr [a+16] movups xmm6,dqword ptr [a+32] movups xmm7,dqword ptr [a+48] mulps xmm0,xmm4 mulps xmm1,xmm5 mulps xmm2,xmm6 mulps xmm3,xmm7 addps xmm0,xmm1 addps xmm2,xmm3 addps xmm0,xmm2 movups dqword ptr [result],xmm0 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.x:=(a.RawComponents[0,0]*b.x)+(a.RawComponents[1,0]*b.y)+(a.RawComponents[2,0]*b.z)+(a.RawComponents[3,0]*b.w); result.y:=(a.RawComponents[0,1]*b.x)+(a.RawComponents[1,1]*b.y)+(a.RawComponents[2,1]*b.z)+(a.RawComponents[3,1]*b.w); result.z:=(a.RawComponents[0,2]*b.x)+(a.RawComponents[1,2]*b.y)+(a.RawComponents[2,2]*b.z)+(a.RawComponents[3,2]*b.w); result.w:=(a.RawComponents[0,3]*b.x)+(a.RawComponents[1,3]*b.y)+(a.RawComponents[2,3]*b.z)+(a.RawComponents[3,3]*b.w); end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvVector4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movups xmm0,dqword ptr [a] // d c b a movaps xmm1,xmm0 // d c b a movaps xmm2,xmm0 // d c b a movaps xmm3,xmm0 // d c b a movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] mulps xmm0,xmm4 mulps xmm1,xmm5 mulps xmm2,xmm6 mulps xmm3,xmm7 addps xmm0,xmm1 addps xmm2,xmm3 addps xmm0,xmm2 movups dqword ptr [result],xmm0 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.x:=(a.x*b.RawComponents[0,0])+(a.y*b.RawComponents[0,1])+(a.z*b.RawComponents[0,2])+(a.w*b.RawComponents[0,3]); result.y:=(a.x*b.RawComponents[1,0])+(a.y*b.RawComponents[1,1])+(a.z*b.RawComponents[1,2])+(a.w*b.RawComponents[1,3]); result.z:=(a.x*b.RawComponents[2,0])+(a.y*b.RawComponents[2,1])+(a.z*b.RawComponents[2,2])+(a.w*b.RawComponents[2,3]); result.w:=(a.x*b.RawComponents[3,0])+(a.y*b.RawComponents[3,1])+(a.z*b.RawComponents[3,2])+(a.w*b.RawComponents[3,3]); end; {$ifend} class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvPlane):TpvPlane; begin result.Normal:=a.Inverse.Transpose.MulBasis(b.Normal); result.Distance:=result.Normal.Dot(a*((b.Normal*b.Distance))); end; class operator TpvMatrix4x4.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvPlane;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvPlane; begin result:=b.Transpose*a; end; class operator TpvMatrix4x4.Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; begin result:=a*b.Inverse; end; class operator TpvMatrix4x4.Divide({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movss xmm4,dword ptr [b] shufps xmm4,xmm4,$00 divps xmm0,xmm4 divps xmm1,xmm4 divps xmm2,xmm4 divps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[0,2]:=a.RawComponents[0,2]/b; result.RawComponents[0,3]:=a.RawComponents[0,3]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; result.RawComponents[1,2]:=a.RawComponents[1,2]/b; result.RawComponents[1,3]:=a.RawComponents[1,3]/b; result.RawComponents[2,0]:=a.RawComponents[2,0]/b; result.RawComponents[2,1]:=a.RawComponents[2,1]/b; result.RawComponents[2,2]:=a.RawComponents[2,2]/b; result.RawComponents[2,3]:=a.RawComponents[2,3]/b; result.RawComponents[3,0]:=a.RawComponents[3,0]/b; result.RawComponents[3,1]:=a.RawComponents[3,1]/b; result.RawComponents[3,2]:=a.RawComponents[3,2]/b; result.RawComponents[3,3]:=a.RawComponents[3,3]/b; end; {$ifend} class operator TpvMatrix4x4.Divide({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movss xmm0,dword ptr [a] shufps xmm0,xmm0,$00 movaps xmm1,xmm0 movaps xmm2,xmm0 movaps xmm3,xmm0 movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] divps xmm0,xmm4 divps xmm1,xmm5 divps xmm2,xmm6 divps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[0,2]:=a/b.RawComponents[0,2]; result.RawComponents[0,3]:=a/b.RawComponents[0,3]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; result.RawComponents[1,2]:=a/b.RawComponents[1,2]; result.RawComponents[1,3]:=a/b.RawComponents[1,3]; result.RawComponents[2,0]:=a/b.RawComponents[2,0]; result.RawComponents[2,1]:=a/b.RawComponents[2,1]; result.RawComponents[2,2]:=a/b.RawComponents[2,2]; result.RawComponents[2,3]:=a/b.RawComponents[2,3]; result.RawComponents[3,0]:=a/b.RawComponents[3,0]; result.RawComponents[3,1]:=a/b.RawComponents[3,1]; result.RawComponents[3,2]:=a/b.RawComponents[3,2]; result.RawComponents[3,3]:=a/b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; begin result:=a*b.Inverse; end; class operator TpvMatrix4x4.IntDivide({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} asm movups xmm0,dqword ptr [a+0] movups xmm1,dqword ptr [a+16] movups xmm2,dqword ptr [a+32] movups xmm3,dqword ptr [a+48] movss xmm4,dword ptr [b] shufps xmm4,xmm4,$00 divps xmm0,xmm4 divps xmm1,xmm4 divps xmm2,xmm4 divps xmm3,xmm4 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 end; {$else} begin result.RawComponents[0,0]:=a.RawComponents[0,0]/b; result.RawComponents[0,1]:=a.RawComponents[0,1]/b; result.RawComponents[0,2]:=a.RawComponents[0,2]/b; result.RawComponents[0,3]:=a.RawComponents[0,3]/b; result.RawComponents[1,0]:=a.RawComponents[1,0]/b; result.RawComponents[1,1]:=a.RawComponents[1,1]/b; result.RawComponents[1,2]:=a.RawComponents[1,2]/b; result.RawComponents[1,3]:=a.RawComponents[1,3]/b; result.RawComponents[2,0]:=a.RawComponents[2,0]/b; result.RawComponents[2,1]:=a.RawComponents[2,1]/b; result.RawComponents[2,2]:=a.RawComponents[2,2]/b; result.RawComponents[2,3]:=a.RawComponents[2,3]/b; result.RawComponents[3,0]:=a.RawComponents[3,0]/b; result.RawComponents[3,1]:=a.RawComponents[3,1]/b; result.RawComponents[3,2]:=a.RawComponents[3,2]/b; result.RawComponents[3,3]:=a.RawComponents[3,3]/b; end; {$ifend} class operator TpvMatrix4x4.IntDivide({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} movss xmm0,dword ptr [a] shufps xmm0,xmm0,$00 movaps xmm1,xmm0 movaps xmm2,xmm0 movaps xmm3,xmm0 movups xmm4,dqword ptr [b+0] movups xmm5,dqword ptr [b+16] movups xmm6,dqword ptr [b+32] movups xmm7,dqword ptr [b+48] divps xmm0,xmm4 divps xmm1,xmm5 divps xmm2,xmm6 divps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=a/b.RawComponents[0,0]; result.RawComponents[0,1]:=a/b.RawComponents[0,1]; result.RawComponents[0,2]:=a/b.RawComponents[0,2]; result.RawComponents[0,3]:=a/b.RawComponents[0,3]; result.RawComponents[1,0]:=a/b.RawComponents[1,0]; result.RawComponents[1,1]:=a/b.RawComponents[1,1]; result.RawComponents[1,2]:=a/b.RawComponents[1,2]; result.RawComponents[1,3]:=a/b.RawComponents[1,3]; result.RawComponents[2,0]:=a/b.RawComponents[2,0]; result.RawComponents[2,1]:=a/b.RawComponents[2,1]; result.RawComponents[2,2]:=a/b.RawComponents[2,2]; result.RawComponents[2,3]:=a/b.RawComponents[2,3]; result.RawComponents[3,0]:=a/b.RawComponents[3,0]; result.RawComponents[3,1]:=a/b.RawComponents[3,1]; result.RawComponents[3,2]:=a/b.RawComponents[3,2]; result.RawComponents[3,3]:=a/b.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Modulus({$ifdef fpc}constref{$else}const{$endif} a,b:TpvMatrix4x4):TpvMatrix4x4; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b.RawComponents[0,1]); result.RawComponents[0,2]:=Modulo(a.RawComponents[0,2],b.RawComponents[0,2]); result.RawComponents[0,3]:=Modulo(a.RawComponents[0,3],b.RawComponents[0,3]); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b.RawComponents[1,1]); result.RawComponents[1,2]:=Modulo(a.RawComponents[1,2],b.RawComponents[1,2]); result.RawComponents[1,3]:=Modulo(a.RawComponents[1,3],b.RawComponents[1,3]); result.RawComponents[2,0]:=Modulo(a.RawComponents[2,0],b.RawComponents[2,0]); result.RawComponents[2,1]:=Modulo(a.RawComponents[2,1],b.RawComponents[2,1]); result.RawComponents[2,2]:=Modulo(a.RawComponents[2,2],b.RawComponents[2,2]); result.RawComponents[2,3]:=Modulo(a.RawComponents[2,3],b.RawComponents[2,3]); result.RawComponents[3,0]:=Modulo(a.RawComponents[3,0],b.RawComponents[3,0]); result.RawComponents[3,1]:=Modulo(a.RawComponents[3,1],b.RawComponents[3,1]); result.RawComponents[3,2]:=Modulo(a.RawComponents[3,2],b.RawComponents[3,2]); result.RawComponents[3,3]:=Modulo(a.RawComponents[3,3],b.RawComponents[3,3]); end; class operator TpvMatrix4x4.Modulus({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4;{$ifdef fpc}constref{$else}const{$endif} b:TpvScalar):TpvMatrix4x4; begin result.RawComponents[0,0]:=Modulo(a.RawComponents[0,0],b); result.RawComponents[0,1]:=Modulo(a.RawComponents[0,1],b); result.RawComponents[0,2]:=Modulo(a.RawComponents[0,2],b); result.RawComponents[0,3]:=Modulo(a.RawComponents[0,3],b); result.RawComponents[1,0]:=Modulo(a.RawComponents[1,0],b); result.RawComponents[1,1]:=Modulo(a.RawComponents[1,1],b); result.RawComponents[1,2]:=Modulo(a.RawComponents[1,2],b); result.RawComponents[1,3]:=Modulo(a.RawComponents[1,3],b); result.RawComponents[2,0]:=Modulo(a.RawComponents[2,0],b); result.RawComponents[2,1]:=Modulo(a.RawComponents[2,1],b); result.RawComponents[2,2]:=Modulo(a.RawComponents[2,2],b); result.RawComponents[2,3]:=Modulo(a.RawComponents[2,3],b); result.RawComponents[3,0]:=Modulo(a.RawComponents[3,0],b); result.RawComponents[3,1]:=Modulo(a.RawComponents[3,1],b); result.RawComponents[3,2]:=Modulo(a.RawComponents[3,2],b); result.RawComponents[3,3]:=Modulo(a.RawComponents[3,3],b); end; class operator TpvMatrix4x4.Modulus({$ifdef fpc}constref{$else}const{$endif} a:TpvScalar;{$ifdef fpc}constref{$else}const{$endif} b:TpvMatrix4x4):TpvMatrix4x4; begin result.RawComponents[0,0]:=Modulo(a,b.RawComponents[0,0]); result.RawComponents[0,1]:=Modulo(a,b.RawComponents[0,1]); result.RawComponents[0,2]:=Modulo(a,b.RawComponents[0,2]); result.RawComponents[0,3]:=Modulo(a,b.RawComponents[0,3]); result.RawComponents[1,0]:=Modulo(a,b.RawComponents[1,0]); result.RawComponents[1,1]:=Modulo(a,b.RawComponents[1,1]); result.RawComponents[1,2]:=Modulo(a,b.RawComponents[1,2]); result.RawComponents[1,3]:=Modulo(a,b.RawComponents[1,3]); result.RawComponents[2,0]:=Modulo(a,b.RawComponents[2,0]); result.RawComponents[2,1]:=Modulo(a,b.RawComponents[2,1]); result.RawComponents[2,2]:=Modulo(a,b.RawComponents[2,2]); result.RawComponents[2,3]:=Modulo(a,b.RawComponents[2,3]); result.RawComponents[3,0]:=Modulo(a,b.RawComponents[3,0]); result.RawComponents[3,1]:=Modulo(a,b.RawComponents[3,1]); result.RawComponents[3,2]:=Modulo(a,b.RawComponents[3,2]); result.RawComponents[3,3]:=Modulo(a,b.RawComponents[3,3]); end; class operator TpvMatrix4x4.Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvMatrix4x4):TpvMatrix4x4; {$if defined(SIMD) and (defined(cpu386) or defined(cpux64))} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} xorps xmm0,xmm0 xorps xmm1,xmm1 xorps xmm2,xmm2 xorps xmm3,xmm3 movups xmm4,dqword ptr [a+0] movups xmm5,dqword ptr [a+16] movups xmm6,dqword ptr [a+32] movups xmm7,dqword ptr [a+48] subps xmm0,xmm4 subps xmm1,xmm5 subps xmm2,xmm6 subps xmm3,xmm7 movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm1 movups dqword ptr [result+32],xmm2 movups dqword ptr [result+48],xmm3 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} begin result.RawComponents[0,0]:=-a.RawComponents[0,0]; result.RawComponents[0,1]:=-a.RawComponents[0,1]; result.RawComponents[0,2]:=-a.RawComponents[0,2]; result.RawComponents[0,3]:=-a.RawComponents[0,3]; result.RawComponents[1,0]:=-a.RawComponents[1,0]; result.RawComponents[1,1]:=-a.RawComponents[1,1]; result.RawComponents[1,2]:=-a.RawComponents[1,2]; result.RawComponents[1,3]:=-a.RawComponents[1,3]; result.RawComponents[2,0]:=-a.RawComponents[2,0]; result.RawComponents[2,1]:=-a.RawComponents[2,1]; result.RawComponents[2,2]:=-a.RawComponents[2,2]; result.RawComponents[2,3]:=-a.RawComponents[2,3]; result.RawComponents[3,0]:=-a.RawComponents[3,0]; result.RawComponents[3,1]:=-a.RawComponents[3,1]; result.RawComponents[3,2]:=-a.RawComponents[3,2]; result.RawComponents[3,3]:=-a.RawComponents[3,3]; end; {$ifend} class operator TpvMatrix4x4.Positive(const a:TpvMatrix4x4):TpvMatrix4x4; begin result:=a; end; function TpvMatrix4x4.GetComponent(const pIndexA,pIndexB:TpvInt32):TpvScalar; begin result:=RawComponents[pIndexA,pIndexB]; end; procedure TpvMatrix4x4.SetComponent(const pIndexA,pIndexB:TpvInt32;const pValue:TpvScalar); begin RawComponents[pIndexA,pIndexB]:=pValue; end; function TpvMatrix4x4.GetColumn(const pIndex:TpvInt32):TpvVector4; begin result.x:=RawComponents[pIndex,0]; result.y:=RawComponents[pIndex,1]; result.z:=RawComponents[pIndex,2]; result.w:=RawComponents[pIndex,3]; end; procedure TpvMatrix4x4.SetColumn(const pIndex:TpvInt32;const pValue:TpvVector4); begin RawComponents[pIndex,0]:=pValue.x; RawComponents[pIndex,1]:=pValue.y; RawComponents[pIndex,2]:=pValue.z; RawComponents[pIndex,3]:=pValue.w; end; function TpvMatrix4x4.GetRow(const pIndex:TpvInt32):TpvVector4; begin result.x:=RawComponents[0,pIndex]; result.y:=RawComponents[1,pIndex]; result.z:=RawComponents[2,pIndex]; result.w:=RawComponents[3,pIndex]; end; procedure TpvMatrix4x4.SetRow(const pIndex:TpvInt32;const pValue:TpvVector4); begin RawComponents[0,pIndex]:=pValue.x; RawComponents[1,pIndex]:=pValue.y; RawComponents[2,pIndex]:=pValue.z; RawComponents[3,pIndex]:=pValue.w; end; function TpvMatrix4x4.Determinant:TpvScalar; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax+32] movups xmm1,dqword ptr [eax+48] movups xmm2,dqword ptr [eax+16] movaps xmm3,xmm0 movaps xmm4,xmm0 movaps xmm6,xmm1 movaps xmm7,xmm2 shufps xmm0,xmm0,$1b // 00011011b shufps xmm1,xmm1,$b1 // 10110001b shufps xmm2,xmm2,$4e // 01001110b shufps xmm7,xmm7,$39 // 00111001b mulps xmm0,xmm1 shufps xmm3,xmm3,$7d // 01111101b shufps xmm6,xmm6,$0a // 00001010b movaps xmm5,xmm0 shufps xmm0,xmm0,$4e // 01001110b shufps xmm4,xmm4,$0a // 00001010b shufps xmm1,xmm1,$28 // 00101000b subps xmm5,xmm0 mulps xmm3,xmm6 mulps xmm4,xmm1 mulps xmm5,xmm2 shufps xmm2,xmm2,$39 // 00111001b subps xmm3,xmm4 movaps xmm0,xmm3 shufps xmm0,xmm0,$39 // 00111001b mulps xmm3,xmm2 mulps xmm0,xmm7 addps xmm5,xmm3 subps xmm5,xmm0 movups xmm6,dqword ptr [eax+0] mulps xmm5,xmm6 movhlps xmm7,xmm5 addps xmm5,xmm7 movaps xmm6,xmm5 shufps xmm6,xmm6,$01 addss xmm5,xmm6 movss dword ptr [result],xmm5 end; {$elseif defined(SIMD) and defined(cpux64)} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} //{$ifdef Windows} movups xmm0,dqword ptr [rcx+32] movups xmm1,dqword ptr [rcx+48] movups xmm2,dqword ptr [rcx+16] (*{$else} movups xmm0,dqword ptr [rdi+32] movups xmm1,dqword ptr [rdi+48] movups xmm2,dqword ptr [rdi+16] {$endif}*) movaps xmm3,xmm0 movaps xmm4,xmm0 movaps xmm6,xmm1 movaps xmm7,xmm2 shufps xmm0,xmm0,$1b // 00011011b shufps xmm1,xmm1,$b1 // 10110001b shufps xmm2,xmm2,$4e // 01001110b shufps xmm7,xmm7,$39 // 00111001b mulps xmm0,xmm1 shufps xmm3,xmm3,$7d // 01111101b shufps xmm6,xmm6,$0a // 00001010b movaps xmm5,xmm0 shufps xmm0,xmm0,$4e // 01001110b shufps xmm4,xmm4,$0a // 00001010b shufps xmm1,xmm1,$28 // 00101000b subps xmm5,xmm0 mulps xmm3,xmm6 mulps xmm4,xmm1 mulps xmm5,xmm2 shufps xmm2,xmm2,$39 // 00111001b subps xmm3,xmm4 movaps xmm0,xmm3 shufps xmm0,xmm0,$39 // 00111001b mulps xmm3,xmm2 mulps xmm0,xmm7 addps xmm5,xmm3 subps xmm5,xmm0 //{$ifdef Windows} movups xmm6,dqword ptr [rcx+0] (*{$else} movups xmm6,dqword ptr [rdi+0] {$endif}*) mulps xmm5,xmm6 movhlps xmm7,xmm5 addps xmm5,xmm7 movaps xmm6,xmm5 shufps xmm6,xmm6,$01 addss xmm5,xmm6 {$ifdef fpc} movss dword ptr [result],xmm5 {$else} movaps xmm0,xmm5 {$endif} //{$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] //{$endif} end; {$else} begin result:=(RawComponents[0,0]*((((RawComponents[1,1]*RawComponents[2,2]*RawComponents[3,3])-(RawComponents[1,1]*RawComponents[2,3]*RawComponents[3,2]))-(RawComponents[2,1]*RawComponents[1,2]*RawComponents[3,3])+(RawComponents[2,1]*RawComponents[1,3]*RawComponents[3,2])+(RawComponents[3,1]*RawComponents[1,2]*RawComponents[2,3]))-(RawComponents[3,1]*RawComponents[1,3]*RawComponents[2,2])))+ (RawComponents[0,1]*(((((-(RawComponents[1,0]*RawComponents[2,2]*RawComponents[3,3]))+(RawComponents[1,0]*RawComponents[2,3]*RawComponents[3,2])+(RawComponents[2,0]*RawComponents[1,2]*RawComponents[3,3]))-(RawComponents[2,0]*RawComponents[1,3]*RawComponents[3,2]))-(RawComponents[3,0]*RawComponents[1,2]*RawComponents[2,3]))+(RawComponents[3,0]*RawComponents[1,3]*RawComponents[2,2])))+ (RawComponents[0,2]*(((((RawComponents[1,0]*RawComponents[2,1]*RawComponents[3,3])-(RawComponents[1,0]*RawComponents[2,3]*RawComponents[3,1]))-(RawComponents[2,0]*RawComponents[1,1]*RawComponents[3,3]))+(RawComponents[2,0]*RawComponents[1,3]*RawComponents[3,1])+(RawComponents[3,0]*RawComponents[1,1]*RawComponents[2,3]))-(RawComponents[3,0]*RawComponents[1,3]*RawComponents[2,1])))+ (RawComponents[0,3]*(((((-(RawComponents[1,0]*RawComponents[2,1]*RawComponents[3,2]))+(RawComponents[1,0]*RawComponents[2,2]*RawComponents[3,1])+(RawComponents[2,0]*RawComponents[1,1]*RawComponents[3,2]))-(RawComponents[2,0]*RawComponents[1,2]*RawComponents[3,1]))-(RawComponents[3,0]*RawComponents[1,1]*RawComponents[2,2]))+(RawComponents[3,0]*RawComponents[1,2]*RawComponents[2,1]))); end; {$ifend} function TpvMatrix4x4.SimpleInverse:TpvMatrix4x4; begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[1,0]; result.RawComponents[0,2]:=RawComponents[2,0]; result.RawComponents[0,3]:=RawComponents[0,3]; result.RawComponents[1,0]:=RawComponents[0,1]; result.RawComponents[1,1]:=RawComponents[1,1]; result.RawComponents[1,2]:=RawComponents[2,1]; result.RawComponents[1,3]:=RawComponents[1,3]; result.RawComponents[2,0]:=RawComponents[0,2]; result.RawComponents[2,1]:=RawComponents[1,2]; result.RawComponents[2,2]:=RawComponents[2,2]; result.RawComponents[2,3]:=RawComponents[2,3]; result.RawComponents[3,0]:=-PpvVector3(pointer(@RawComponents[3,0]))^.Dot(TpvVector3.Create(RawComponents[0,0],RawComponents[0,1],RawComponents[0,2])); result.RawComponents[3,1]:=-PpvVector3(pointer(@RawComponents[3,0]))^.Dot(TpvVector3.Create(RawComponents[1,0],RawComponents[1,1],RawComponents[1,2])); result.RawComponents[3,2]:=-PpvVector3(pointer(@RawComponents[3,0]))^.Dot(TpvVector3.Create(RawComponents[2,0],RawComponents[2,1],RawComponents[2,2])); result.RawComponents[3,3]:=RawComponents[3,3]; end; function TpvMatrix4x4.Inverse:TpvMatrix4x4; {$if defined(SIMD) and defined(cpu386)} asm mov ecx,esp and esp,$fffffff0 sub esp,$b0 movlps xmm2,qword ptr [eax+8] movlps xmm4,qword ptr [eax+40] movhps xmm2,qword ptr [eax+24] movhps xmm4,qword ptr [eax+56] movlps xmm3,qword ptr [eax+32] movlps xmm1,qword ptr [eax] movhps xmm3,qword ptr [eax+48] movhps xmm1,qword ptr [eax+16] movaps xmm5,xmm2 shufps xmm5,xmm4,$88 shufps xmm4,xmm2,$dd movaps xmm2,xmm4 mulps xmm2,xmm5 shufps xmm2,xmm2,$b1 movaps xmm6,xmm2 shufps xmm6,xmm6,$4e movaps xmm7,xmm3 shufps xmm3,xmm1,$dd shufps xmm1,xmm7,$88 movaps xmm7,xmm3 mulps xmm3,xmm6 mulps xmm6,xmm1 movaps xmm0,xmm6 movaps xmm6,xmm7 mulps xmm7,xmm2 mulps xmm2,xmm1 subps xmm3,xmm7 movaps xmm7,xmm6 mulps xmm7,xmm5 shufps xmm5,xmm5,$4e shufps xmm7,xmm7,$b1 movaps dqword ptr [esp+16],xmm2 movaps xmm2,xmm4 mulps xmm2,xmm7 addps xmm2,xmm3 movaps xmm3,xmm7 shufps xmm7,xmm7,$4e mulps xmm3,xmm1 movaps dqword ptr [esp+32],xmm3 movaps xmm3,xmm4 mulps xmm3,xmm7 mulps xmm7,xmm1 subps xmm2,xmm3 movaps xmm3,xmm6 shufps xmm3,xmm3,$4e mulps xmm3,xmm4 shufps xmm3,xmm3,$b1 movaps dqword ptr [esp+48],xmm7 movaps xmm7,xmm5 mulps xmm5,xmm3 addps xmm5,xmm2 movaps xmm2,xmm3 shufps xmm3,xmm3,$4e mulps xmm2,xmm1 movaps dqword ptr [esp+64],xmm4 movaps xmm4,xmm7 mulps xmm7,xmm3 mulps xmm3,xmm1 subps xmm5,xmm7 subps xmm3,xmm2 movaps xmm2,xmm1 mulps xmm1,xmm5 shufps xmm3,xmm3,$4e movaps xmm7,xmm1 shufps xmm1,xmm1,$4e movaps dqword ptr [esp],xmm5 addps xmm1,xmm7 movaps xmm5,xmm1 shufps xmm1,xmm1,$b1 addss xmm1,xmm5 movaps xmm5,xmm6 mulps xmm5,xmm2 shufps xmm5,xmm5,$b1 movaps xmm7,xmm5 shufps xmm5,xmm5,$4e movaps dqword ptr [esp+80],xmm4 movaps xmm4,dqword ptr [esp+64] movaps dqword ptr [esp+64],xmm6 movaps xmm6,xmm4 mulps xmm6,xmm7 addps xmm6,xmm3 movaps xmm3,xmm4 mulps xmm3,xmm5 subps xmm3,xmm6 movaps xmm6,xmm4 mulps xmm6,xmm2 shufps xmm6,xmm6,$b1 movaps dqword ptr [esp+112],xmm5 movaps xmm5,dqword ptr [esp+64] movaps dqword ptr [esp+128],xmm7 movaps xmm7,xmm6 mulps xmm7,xmm5 addps xmm7,xmm3 movaps xmm3,xmm6 shufps xmm3,xmm3,$4e movaps dqword ptr [esp+144],xmm4 movaps xmm4,xmm5 mulps xmm5,xmm3 movaps dqword ptr [esp+160],xmm4 movaps xmm4,xmm6 movaps xmm6,xmm7 subps xmm6,xmm5 movaps xmm5,xmm0 movaps xmm7,dqword ptr [esp+16] subps xmm5,xmm7 shufps xmm5,xmm5,$4e movaps xmm7,dqword ptr [esp+80] mulps xmm4,xmm7 mulps xmm3,xmm7 subps xmm5,xmm4 mulps xmm2,xmm7 addps xmm3,xmm5 shufps xmm2,xmm2,$b1 movaps xmm4,xmm2 shufps xmm4,xmm4,$4e movaps xmm5,dqword ptr [esp+144] movaps xmm0,xmm6 movaps xmm6,xmm5 mulps xmm5,xmm2 mulps xmm6,xmm4 addps xmm5,xmm3 movaps xmm3,xmm4 movaps xmm4,xmm5 subps xmm4,xmm6 movaps xmm5,dqword ptr [esp+48] movaps xmm6,dqword ptr [esp+32] subps xmm5,xmm6 shufps xmm5,xmm5,$4e movaps xmm6,[esp+128] mulps xmm6,xmm7 subps xmm6,xmm5 movaps xmm5,dqword ptr [esp+112] mulps xmm7,xmm5 subps xmm6,xmm7 movaps xmm5,dqword ptr [esp+160] mulps xmm2,xmm5 mulps xmm5,xmm3 subps xmm6,xmm2 movaps xmm2,xmm5 addps xmm2,xmm6 movaps xmm6,xmm0 movaps xmm0,xmm1 movaps xmm1,dqword ptr [esp] movaps xmm3,xmm0 rcpss xmm5,xmm0 mulss xmm0,xmm5 mulss xmm0,xmm5 addss xmm5,xmm5 subss xmm5,xmm0 movaps xmm0,xmm5 addss xmm5,xmm5 mulss xmm0,xmm0 mulss xmm3,xmm0 subss xmm5,xmm3 shufps xmm5,xmm5,$00 mulps xmm1,xmm5 mulps xmm4,xmm5 mulps xmm6,xmm5 mulps xmm5,xmm2 movups dqword ptr [result+0],xmm1 movups dqword ptr [result+16],xmm4 movups dqword ptr [result+32],xmm6 movups dqword ptr [result+48],xmm5 mov esp,ecx end; {$elseif defined(SIMD) and defined(cpux64)} {-$ifdef Windows} var StackSave0,StackSave1:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave0],xmm6 movups dqword ptr [StackSave1],xmm7 {-$endif} mov r9,rsp mov r8,$fffffffffffffff0 and rsp,r8 sub rsp,$b0 //{$ifdef Windows} movlps xmm2,qword ptr [rcx+8] movlps xmm4,qword ptr [rcx+40] movhps xmm2,qword ptr [rcx+24] movhps xmm4,qword ptr [rcx+56] movlps xmm3,qword ptr [rcx+32] movlps xmm1,qword ptr [rcx] movhps xmm3,qword ptr [rcx+48] movhps xmm1,qword ptr [rcx+16] (*{$else} movlps xmm2,qword ptr [rdi+8] movlps xmm4,qword ptr [rdi+40] movhps xmm2,qword ptr [rdi+24] movhps xmm4,qword ptr [rdi+56] movlps xmm3,qword ptr [rdi+32] movlps xmm1,qword ptr [rdi] movhps xmm3,qword ptr [rdi+48] movhps xmm1,qword ptr [rdi+16] {$endif}*) movaps xmm5,xmm2 shufps xmm5,xmm4,$88 shufps xmm4,xmm2,$dd movaps xmm2,xmm4 mulps xmm2,xmm5 shufps xmm2,xmm2,$b1 movaps xmm6,xmm2 shufps xmm6,xmm6,$4e movaps xmm7,xmm3 shufps xmm3,xmm1,$dd shufps xmm1,xmm7,$88 movaps xmm7,xmm3 mulps xmm3,xmm6 mulps xmm6,xmm1 movaps xmm0,xmm6 movaps xmm6,xmm7 mulps xmm7,xmm2 mulps xmm2,xmm1 subps xmm3,xmm7 movaps xmm7,xmm6 mulps xmm7,xmm5 shufps xmm5,xmm5,$4e shufps xmm7,xmm7,$b1 movaps dqword ptr [rsp+16],xmm2 movaps xmm2,xmm4 mulps xmm2,xmm7 addps xmm2,xmm3 movaps xmm3,xmm7 shufps xmm7,xmm7,$4e mulps xmm3,xmm1 movaps dqword ptr [rsp+32],xmm3 movaps xmm3,xmm4 mulps xmm3,xmm7 mulps xmm7,xmm1 subps xmm2,xmm3 movaps xmm3,xmm6 shufps xmm3,xmm3,$4e mulps xmm3,xmm4 shufps xmm3,xmm3,$b1 movaps dqword ptr [rsp+48],xmm7 movaps xmm7,xmm5 mulps xmm5,xmm3 addps xmm5,xmm2 movaps xmm2,xmm3 shufps xmm3,xmm3,$4e mulps xmm2,xmm1 movaps dqword ptr [rsp+64],xmm4 movaps xmm4,xmm7 mulps xmm7,xmm3 mulps xmm3,xmm1 subps xmm5,xmm7 subps xmm3,xmm2 movaps xmm2,xmm1 mulps xmm1,xmm5 shufps xmm3,xmm3,$4e movaps xmm7,xmm1 shufps xmm1,xmm1,$4e movaps dqword ptr [rsp],xmm5 addps xmm1,xmm7 movaps xmm5,xmm1 shufps xmm1,xmm1,$b1 addss xmm1,xmm5 movaps xmm5,xmm6 mulps xmm5,xmm2 shufps xmm5,xmm5,$b1 movaps xmm7,xmm5 shufps xmm5,xmm5,$4e movaps dqword ptr [rsp+80],xmm4 movaps xmm4,dqword ptr [rsp+64] movaps dqword ptr [rsp+64],xmm6 movaps xmm6,xmm4 mulps xmm6,xmm7 addps xmm6,xmm3 movaps xmm3,xmm4 mulps xmm3,xmm5 subps xmm3,xmm6 movaps xmm6,xmm4 mulps xmm6,xmm2 shufps xmm6,xmm6,$b1 movaps dqword ptr [rsp+112],xmm5 movaps xmm5,dqword ptr [rsp+64] movaps dqword ptr [rsp+128],xmm7 movaps xmm7,xmm6 mulps xmm7,xmm5 addps xmm7,xmm3 movaps xmm3,xmm6 shufps xmm3,xmm3,$4e movaps dqword ptr [rsp+144],xmm4 movaps xmm4,xmm5 mulps xmm5,xmm3 movaps dqword ptr [rsp+160],xmm4 movaps xmm4,xmm6 movaps xmm6,xmm7 subps xmm6,xmm5 movaps xmm5,xmm0 movaps xmm7,dqword ptr [rsp+16] subps xmm5,xmm7 shufps xmm5,xmm5,$4e movaps xmm7,dqword ptr [rsp+80] mulps xmm4,xmm7 mulps xmm3,xmm7 subps xmm5,xmm4 mulps xmm2,xmm7 addps xmm3,xmm5 shufps xmm2,xmm2,$b1 movaps xmm4,xmm2 shufps xmm4,xmm4,$4e movaps xmm5,dqword ptr [rsp+144] movaps xmm0,xmm6 movaps xmm6,xmm5 mulps xmm5,xmm2 mulps xmm6,xmm4 addps xmm5,xmm3 movaps xmm3,xmm4 movaps xmm4,xmm5 subps xmm4,xmm6 movaps xmm5,dqword ptr [rsp+48] movaps xmm6,dqword ptr [rsp+32] subps xmm5,xmm6 shufps xmm5,xmm5,$4e movaps xmm6,[rsp+128] mulps xmm6,xmm7 subps xmm6,xmm5 movaps xmm5,dqword ptr [rsp+112] mulps xmm7,xmm5 subps xmm6,xmm7 movaps xmm5,dqword ptr [rsp+160] mulps xmm2,xmm5 mulps xmm5,xmm3 subps xmm6,xmm2 movaps xmm2,xmm5 addps xmm2,xmm6 movaps xmm6,xmm0 movaps xmm0,xmm1 movaps xmm1,dqword ptr [rsp] movaps xmm3,xmm0 rcpss xmm5,xmm0 mulss xmm0,xmm5 mulss xmm0,xmm5 addss xmm5,xmm5 subss xmm5,xmm0 movaps xmm0,xmm5 addss xmm5,xmm5 mulss xmm0,xmm0 mulss xmm3,xmm0 subss xmm5,xmm3 shufps xmm5,xmm5,$00 mulps xmm1,xmm5 mulps xmm4,xmm5 mulps xmm6,xmm5 mulps xmm5,xmm2 movups dqword ptr [result+0],xmm1 movups dqword ptr [result+16],xmm4 movups dqword ptr [result+32],xmm6 movups dqword ptr [result+48],xmm5 mov rsp,r9 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave0] movups xmm7,dqword ptr [StackSave1] {-$endif} end; {$else} var t0,t4,t8,t12,d:TpvScalar; begin t0:=(((RawComponents[1,1]*RawComponents[2,2]*RawComponents[3,3])-(RawComponents[1,1]*RawComponents[2,3]*RawComponents[3,2]))-(RawComponents[2,1]*RawComponents[1,2]*RawComponents[3,3])+(RawComponents[2,1]*RawComponents[1,3]*RawComponents[3,2])+(RawComponents[3,1]*RawComponents[1,2]*RawComponents[2,3]))-(RawComponents[3,1]*RawComponents[1,3]*RawComponents[2,2]); t4:=((((-(RawComponents[1,0]*RawComponents[2,2]*RawComponents[3,3]))+(RawComponents[1,0]*RawComponents[2,3]*RawComponents[3,2])+(RawComponents[2,0]*RawComponents[1,2]*RawComponents[3,3]))-(RawComponents[2,0]*RawComponents[1,3]*RawComponents[3,2]))-(RawComponents[3,0]*RawComponents[1,2]*RawComponents[2,3]))+(RawComponents[3,0]*RawComponents[1,3]*RawComponents[2,2]); t8:=((((RawComponents[1,0]*RawComponents[2,1]*RawComponents[3,3])-(RawComponents[1,0]*RawComponents[2,3]*RawComponents[3,1]))-(RawComponents[2,0]*RawComponents[1,1]*RawComponents[3,3]))+(RawComponents[2,0]*RawComponents[1,3]*RawComponents[3,1])+(RawComponents[3,0]*RawComponents[1,1]*RawComponents[2,3]))-(RawComponents[3,0]*RawComponents[1,3]*RawComponents[2,1]); t12:=((((-(RawComponents[1,0]*RawComponents[2,1]*RawComponents[3,2]))+(RawComponents[1,0]*RawComponents[2,2]*RawComponents[3,1])+(RawComponents[2,0]*RawComponents[1,1]*RawComponents[3,2]))-(RawComponents[2,0]*RawComponents[1,2]*RawComponents[3,1]))-(RawComponents[3,0]*RawComponents[1,1]*RawComponents[2,2]))+(RawComponents[3,0]*RawComponents[1,2]*RawComponents[2,1]); d:=(RawComponents[0,0]*t0)+(RawComponents[0,1]*t4)+(RawComponents[0,2]*t8)+(RawComponents[0,3]*t12); if d<>0.0 then begin d:=1.0/d; result.RawComponents[0,0]:=t0*d; result.RawComponents[0,1]:=(((((-(RawComponents[0,1]*RawComponents[2,2]*RawComponents[3,3]))+(RawComponents[0,1]*RawComponents[2,3]*RawComponents[3,2])+(RawComponents[2,1]*RawComponents[0,2]*RawComponents[3,3]))-(RawComponents[2,1]*RawComponents[0,3]*RawComponents[3,2]))-(RawComponents[3,1]*RawComponents[0,2]*RawComponents[2,3]))+(RawComponents[3,1]*RawComponents[0,3]*RawComponents[2,2]))*d; result.RawComponents[0,2]:=(((((RawComponents[0,1]*RawComponents[1,2]*RawComponents[3,3])-(RawComponents[0,1]*RawComponents[1,3]*RawComponents[3,2]))-(RawComponents[1,1]*RawComponents[0,2]*RawComponents[3,3]))+(RawComponents[1,1]*RawComponents[0,3]*RawComponents[3,2])+(RawComponents[3,1]*RawComponents[0,2]*RawComponents[1,3]))-(RawComponents[3,1]*RawComponents[0,3]*RawComponents[1,2]))*d; result.RawComponents[0,3]:=(((((-(RawComponents[0,1]*RawComponents[1,2]*RawComponents[2,3]))+(RawComponents[0,1]*RawComponents[1,3]*RawComponents[2,2])+(RawComponents[1,1]*RawComponents[0,2]*RawComponents[2,3]))-(RawComponents[1,1]*RawComponents[0,3]*RawComponents[2,2]))-(RawComponents[2,1]*RawComponents[0,2]*RawComponents[1,3]))+(RawComponents[2,1]*RawComponents[0,3]*RawComponents[1,2]))*d; result.RawComponents[1,0]:=t4*d; result.RawComponents[1,1]:=((((RawComponents[0,0]*RawComponents[2,2]*RawComponents[3,3])-(RawComponents[0,0]*RawComponents[2,3]*RawComponents[3,2]))-(RawComponents[2,0]*RawComponents[0,2]*RawComponents[3,3])+(RawComponents[2,0]*RawComponents[0,3]*RawComponents[3,2])+(RawComponents[3,0]*RawComponents[0,2]*RawComponents[2,3]))-(RawComponents[3,0]*RawComponents[0,3]*RawComponents[2,2]))*d; result.RawComponents[1,2]:=(((((-(RawComponents[0,0]*RawComponents[1,2]*RawComponents[3,3]))+(RawComponents[0,0]*RawComponents[1,3]*RawComponents[3,2])+(RawComponents[1,0]*RawComponents[0,2]*RawComponents[3,3]))-(RawComponents[1,0]*RawComponents[0,3]*RawComponents[3,2]))-(RawComponents[3,0]*RawComponents[0,2]*RawComponents[1,3]))+(RawComponents[3,0]*RawComponents[0,3]*RawComponents[1,2]))*d; result.RawComponents[1,3]:=(((((RawComponents[0,0]*RawComponents[1,2]*RawComponents[2,3])-(RawComponents[0,0]*RawComponents[1,3]*RawComponents[2,2]))-(RawComponents[1,0]*RawComponents[0,2]*RawComponents[2,3]))+(RawComponents[1,0]*RawComponents[0,3]*RawComponents[2,2])+(RawComponents[2,0]*RawComponents[0,2]*RawComponents[1,3]))-(RawComponents[2,0]*RawComponents[0,3]*RawComponents[1,2]))*d; result.RawComponents[2,0]:=t8*d; result.RawComponents[2,1]:=(((((-(RawComponents[0,0]*RawComponents[2,1]*RawComponents[3,3]))+(RawComponents[0,0]*RawComponents[2,3]*RawComponents[3,1])+(RawComponents[2,0]*RawComponents[0,1]*RawComponents[3,3]))-(RawComponents[2,0]*RawComponents[0,3]*RawComponents[3,1]))-(RawComponents[3,0]*RawComponents[0,1]*RawComponents[2,3]))+(RawComponents[3,0]*RawComponents[0,3]*RawComponents[2,1]))*d; result.RawComponents[2,2]:=(((((RawComponents[0,0]*RawComponents[1,1]*RawComponents[3,3])-(RawComponents[0,0]*RawComponents[1,3]*RawComponents[3,1]))-(RawComponents[1,0]*RawComponents[0,1]*RawComponents[3,3]))+(RawComponents[1,0]*RawComponents[0,3]*RawComponents[3,1])+(RawComponents[3,0]*RawComponents[0,1]*RawComponents[1,3]))-(RawComponents[3,0]*RawComponents[0,3]*RawComponents[1,1]))*d; result.RawComponents[2,3]:=(((((-(RawComponents[0,0]*RawComponents[1,1]*RawComponents[2,3]))+(RawComponents[0,0]*RawComponents[1,3]*RawComponents[2,1])+(RawComponents[1,0]*RawComponents[0,1]*RawComponents[2,3]))-(RawComponents[1,0]*RawComponents[0,3]*RawComponents[2,1]))-(RawComponents[2,0]*RawComponents[0,1]*RawComponents[1,3]))+(RawComponents[2,0]*RawComponents[0,3]*RawComponents[1,1]))*d; result.RawComponents[3,0]:=t12*d; result.RawComponents[3,1]:=(((((RawComponents[0,0]*RawComponents[2,1]*RawComponents[3,2])-(RawComponents[0,0]*RawComponents[2,2]*RawComponents[3,1]))-(RawComponents[2,0]*RawComponents[0,1]*RawComponents[3,2]))+(RawComponents[2,0]*RawComponents[0,2]*RawComponents[3,1])+(RawComponents[3,0]*RawComponents[0,1]*RawComponents[2,2]))-(RawComponents[3,0]*RawComponents[0,2]*RawComponents[2,1]))*d; result.RawComponents[3,2]:=(((((-(RawComponents[0,0]*RawComponents[1,1]*RawComponents[3,2]))+(RawComponents[0,0]*RawComponents[1,2]*RawComponents[3,1])+(RawComponents[1,0]*RawComponents[0,1]*RawComponents[3,2]))-(RawComponents[1,0]*RawComponents[0,2]*RawComponents[3,1]))-(RawComponents[3,0]*RawComponents[0,1]*RawComponents[1,2]))+(RawComponents[3,0]*RawComponents[0,2]*RawComponents[1,1]))*d; result.RawComponents[3,3]:=(((((RawComponents[0,0]*RawComponents[1,1]*RawComponents[2,2])-(RawComponents[0,0]*RawComponents[1,2]*RawComponents[2,1]))-(RawComponents[1,0]*RawComponents[0,1]*RawComponents[2,2]))+(RawComponents[1,0]*RawComponents[0,2]*RawComponents[2,1])+(RawComponents[2,0]*RawComponents[0,1]*RawComponents[1,2]))-(RawComponents[2,0]*RawComponents[0,2]*RawComponents[1,1]))*d; end; end; {$ifend} function TpvMatrix4x4.Transpose:TpvMatrix4x4; {$if defined(SIMD) and defined(cpu386)} asm movups xmm0,dqword ptr [eax+0] movups xmm4,dqword ptr [eax+16] movups xmm2,dqword ptr [eax+32] movups xmm5,dqword ptr [eax+48] movaps xmm1,xmm0 movaps xmm3,xmm2 unpcklps xmm0,xmm4 unpckhps xmm1,xmm4 unpcklps xmm2,xmm5 unpckhps xmm3,xmm5 movaps xmm4,xmm0 movaps xmm6,xmm1 shufps xmm0,xmm2,$44 // 01000100b shufps xmm4,xmm2,$ee // 11101110b shufps xmm1,xmm3,$44 // 01000100b shufps xmm6,xmm3,$ee // 11101110b movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm4 movups dqword ptr [result+32],xmm1 movups dqword ptr [result+48],xmm6 end; {$elseif defined(SIMD) and defined(cpux64)} {-$ifdef Windows} var StackSave:array[0..3] of single; {-$endif} asm {-$ifdef Windows} movups dqword ptr [StackSave],xmm6 {-$endif} //{$ifdef Windows} movups xmm0,dqword ptr [rcx+0] movups xmm4,dqword ptr [rcx+16] movups xmm2,dqword ptr [rcx+32] movups xmm5,dqword ptr [rcx+48] (*{$else} movups xmm0,dqword ptr [rdi+0] movups xmm4,dqword ptr [rdi+16] movups xmm2,dqword ptr [rdi+32] movups xmm5,dqword ptr [rdi+48] {$endif}*) movaps xmm1,xmm0 movaps xmm3,xmm2 unpcklps xmm0,xmm4 unpckhps xmm1,xmm4 unpcklps xmm2,xmm5 unpckhps xmm3,xmm5 movaps xmm4,xmm0 movaps xmm6,xmm1 shufps xmm0,xmm2,$44 // 01000100b shufps xmm4,xmm2,$ee // 11101110b shufps xmm1,xmm3,$44 // 01000100b shufps xmm6,xmm3,$ee // 11101110b movups dqword ptr [result+0],xmm0 movups dqword ptr [result+16],xmm4 movups dqword ptr [result+32],xmm1 movups dqword ptr [result+48],xmm6 {-$ifdef Windows} movups xmm6,dqword ptr [StackSave] {-$endif} end; {$else} begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[1,0]; result.RawComponents[0,2]:=RawComponents[2,0]; result.RawComponents[0,3]:=RawComponents[3,0]; result.RawComponents[1,0]:=RawComponents[0,1]; result.RawComponents[1,1]:=RawComponents[1,1]; result.RawComponents[1,2]:=RawComponents[2,1]; result.RawComponents[1,3]:=RawComponents[3,1]; result.RawComponents[2,0]:=RawComponents[0,2]; result.RawComponents[2,1]:=RawComponents[1,2]; result.RawComponents[2,2]:=RawComponents[2,2]; result.RawComponents[2,3]:=RawComponents[3,2]; result.RawComponents[3,0]:=RawComponents[0,3]; result.RawComponents[3,1]:=RawComponents[1,3]; result.RawComponents[3,2]:=RawComponents[2,3]; result.RawComponents[3,3]:=RawComponents[3,3]; end; {$ifend} function TpvMatrix4x4.EulerAngles:TpvVector3; var v0,v1:TpvVector3; begin if abs((-1.0)-RawComponents[0,2])<EPSILON then begin result.x:=0.0; result.y:=HalfPI; result.z:=ArcTan2(RawComponents[1,0],RawComponents[2,0]); end else if abs(1.0-RawComponents[0,2])<EPSILON then begin result.x:=0.0; result.y:=-HalfPI; result.z:=ArcTan2(-RawComponents[1,0],-RawComponents[2,0]); end else begin v0.x:=-ArcSin(RawComponents[0,2]); v1.x:=PI-v0.x; v0.y:=ArcTan2(RawComponents[1,2]/cos(v0.x),RawComponents[2,2]/cos(v0.x)); v1.y:=ArcTan2(RawComponents[1,2]/cos(v1.x),RawComponents[2,2]/cos(v1.x)); v0.z:=ArcTan2(RawComponents[0,1]/cos(v0.x),RawComponents[0,0]/cos(v0.x)); v1.z:=ArcTan2(RawComponents[0,1]/cos(v1.x),RawComponents[0,0]/cos(v1.x)); if v0.SquaredLength<v1.SquaredLength then begin result:=v0; end else begin result:=v1; end; end; end; function TpvMatrix4x4.Normalize:TpvMatrix4x4; begin result.Right.xyz:=Right.xyz.Normalize; result.RawComponents[0,3]:=RawComponents[0,3]; result.Up.xyz:=Up.xyz.Normalize; result.RawComponents[1,3]:=RawComponents[1,3]; result.Forwards.xyz:=Forwards.xyz.Normalize; result.RawComponents[2,3]:=RawComponents[2,3]; result.Translation:=Translation; end; function TpvMatrix4x4.OrthoNormalize:TpvMatrix4x4; begin result.Normal.xyz:=Normal.xyz.Normalize; result.Tangent.xyz:=(Tangent.xyz-(result.Normal.xyz*Tangent.xyz.Dot(result.Normal.xyz))).Normalize; result.Bitangent.xyz:=result.Normal.xyz.Cross(result.Tangent.xyz).Normalize; result.Bitangent.xyz:=result.Bitangent.xyz-(result.Normal.xyz*result.Bitangent.xyz.Dot(result.Normal.xyz)); result.Bitangent.xyz:=(result.Bitangent.xyz-(result.Tangent.xyz*result.Bitangent.xyz.Dot(result.Tangent.xyz))).Normalize; result.Tangent.xyz:=result.Bitangent.xyz.Cross(result.Normal.xyz).Normalize; result.Normal.xyz:=result.Tangent.xyz.Cross(result.Bitangent.xyz).Normalize; result.RawComponents[0,3]:=RawComponents[0,3]; result.RawComponents[1,3]:=RawComponents[1,3]; result.RawComponents[2,3]:=RawComponents[2,3]; result.RawComponents[3,3]:=RawComponents[3,3]; result.RawComponents[3,0]:=RawComponents[3,0]; result.RawComponents[3,1]:=RawComponents[3,1]; result.RawComponents[3,2]:=RawComponents[3,2]; end; function TpvMatrix4x4.RobustOrthoNormalize(const Tolerance:TpvScalar=1e-3):TpvMatrix4x4; var Bisector,Axis:TpvVector3; begin begin if Normal.xyz.Length<Tolerance then begin // Degenerate case, compute new Normal.xyz Normal.xyz:=Tangent.xyz.Cross(Bitangent.xyz); if Normal.xyz.Length<Tolerance then begin result.Tangent.xyz:=TpvVector3.XAxis; result.Bitangent.xyz:=TpvVector3.YAxis; result.Normal.xyz:=TpvVector3.ZAxis; result.RawComponents[0,3]:=RawComponents[0,3]; result.RawComponents[1,3]:=RawComponents[1,3]; result.RawComponents[2,3]:=RawComponents[2,3]; result.RawComponents[3,3]:=RawComponents[3,3]; result.RawComponents[3,0]:=RawComponents[3,0]; result.RawComponents[3,1]:=RawComponents[3,1]; result.RawComponents[3,2]:=RawComponents[3,2]; exit; end; end; result.Normal.xyz:=Normal.xyz.Normalize; end; begin // Project Tangent.xyz and Bitangent.xyz onto the Normal.xyz orthogonal plane result.Tangent.xyz:=Tangent.xyz-(result.Normal.xyz*Tangent.xyz.Dot(result.Normal.xyz)); result.Bitangent.xyz:=Bitangent.xyz-(result.Normal.xyz*Bitangent.xyz.Dot(result.Normal.xyz)); end; begin // Check for several degenerate cases if result.Tangent.xyz.Length<Tolerance then begin if result.Bitangent.xyz.Length<Tolerance then begin result.Tangent.xyz:=result.Normal.xyz.Normalize; if (result.Tangent.xyz.x<=result.Tangent.xyz.y) and (result.Tangent.xyz.x<=result.Tangent.xyz.z) then begin result.Tangent.xyz:=TpvVector3.XAxis; end else if (result.Tangent.xyz.y<=result.Tangent.xyz.x) and (result.Tangent.xyz.y<=result.Tangent.xyz.z) then begin result.Tangent.xyz:=TpvVector3.YAxis; end else begin result.Tangent.xyz:=TpvVector3.ZAxis; end; result.Tangent.xyz:=result.Tangent.xyz-(result.Normal.xyz*result.Tangent.xyz.Dot(result.Normal.xyz)); result.Bitangent.xyz:=result.Normal.xyz.Cross(result.Tangent.xyz).Normalize; end else begin result.Tangent.xyz:=result.Bitangent.xyz.Cross(result.Normal.xyz).Normalize; end; end else begin result.Tangent.xyz:=result.Tangent.xyz.Normalize; if result.Bitangent.xyz.Length<Tolerance then begin result.Bitangent.xyz:=result.Normal.xyz.Cross(result.Tangent.xyz).Normalize; end else begin result.Bitangent.xyz:=result.Bitangent.xyz.Normalize; Bisector:=result.Tangent.xyz+result.Bitangent.xyz; if Bisector.Length<Tolerance then begin Bisector:=result.Tangent.xyz; end else begin Bisector:=Bisector.Normalize; end; Axis:=Bisector.Cross(result.Normal.xyz).Normalize; if Axis.Dot(Tangent.xyz)>0.0 then begin result.Tangent.xyz:=(Bisector+Axis).Normalize; result.Bitangent.xyz:=(Bisector-Axis).Normalize; end else begin result.Tangent.xyz:=(Bisector-Axis).Normalize; result.Bitangent.xyz:=(Bisector+Axis).Normalize; end; end; end; end; result.Bitangent.xyz:=result.Normal.xyz.Cross(result.Tangent.xyz).Normalize; result.Tangent.xyz:=result.Bitangent.xyz.Cross(result.Normal.xyz).Normalize; result.Normal.xyz:=result.Tangent.xyz.Cross(result.Bitangent.xyz).Normalize; result.RawComponents[0,3]:=RawComponents[0,3]; result.RawComponents[1,3]:=RawComponents[1,3]; result.RawComponents[2,3]:=RawComponents[2,3]; result.RawComponents[3,3]:=RawComponents[3,3]; result.RawComponents[3,0]:=RawComponents[3,0]; result.RawComponents[3,1]:=RawComponents[3,1]; result.RawComponents[3,2]:=RawComponents[3,2]; end; function TpvMatrix4x4.ToQuaternion:TpvQuaternion; var t,s:TpvScalar; begin t:=RawComponents[0,0]+(RawComponents[1,1]+RawComponents[2,2]); if t>2.9999999 then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end else if t>0.0000001 then begin s:=sqrt(1.0+t)*2.0; result.x:=(RawComponents[1,2]-RawComponents[2,1])/s; result.y:=(RawComponents[2,0]-RawComponents[0,2])/s; result.z:=(RawComponents[0,1]-RawComponents[1,0])/s; result.w:=s*0.25; end else if (RawComponents[0,0]>RawComponents[1,1]) and (RawComponents[0,0]>RawComponents[2,2]) then begin s:=sqrt(1.0+(RawComponents[0,0]-(RawComponents[1,1]+RawComponents[2,2])))*2.0; result.x:=s*0.25; result.y:=(RawComponents[1,0]+RawComponents[0,1])/s; result.z:=(RawComponents[2,0]+RawComponents[0,2])/s; result.w:=(RawComponents[1,2]-RawComponents[2,1])/s; end else if RawComponents[1,1]>RawComponents[2,2] then begin s:=sqrt(1.0+(RawComponents[1,1]-(RawComponents[0,0]+RawComponents[2,2])))*2.0; result.x:=(RawComponents[1,0]+RawComponents[0,1])/s; result.y:=s*0.25; result.z:=(RawComponents[2,1]+RawComponents[1,2])/s; result.w:=(RawComponents[2,0]-RawComponents[0,2])/s; end else begin s:=sqrt(1.0+(RawComponents[2,2]-(RawComponents[0,0]+RawComponents[1,1])))*2.0; result.x:=(RawComponents[2,0]+RawComponents[0,2])/s; result.y:=(RawComponents[2,1]+RawComponents[1,2])/s; result.z:=s*0.25; result.w:=(RawComponents[0,1]-RawComponents[1,0])/s; end; result:=result.Normalize; end; function TpvMatrix4x4.ToQTangent:TpvQuaternion; const Threshold=1.0/32767.0; var Scale,t,s,Renormalization:TpvScalar; begin if ((((((RawComponents[0,0]*RawComponents[1,1]*RawComponents[2,2])+ (RawComponents[0,1]*RawComponents[1,2]*RawComponents[2,0]) )+ (RawComponents[0,2]*RawComponents[1,0]*RawComponents[2,1]) )- (RawComponents[0,2]*RawComponents[1,1]*RawComponents[2,0]) )- (RawComponents[0,1]*RawComponents[1,0]*RawComponents[2,2]) )- (RawComponents[0,0]*RawComponents[1,2]*RawComponents[2,1]) )<0.0 then begin // Reflection matrix, so flip y axis in case the tangent frame encodes a reflection Scale:=-1.0; RawComponents[2,0]:=-RawComponents[2,0]; RawComponents[2,1]:=-RawComponents[2,1]; RawComponents[2,2]:=-RawComponents[2,2]; end else begin // Rotation matrix, so nothing is doing to do Scale:=1.0; end; begin // Convert to quaternion t:=RawComponents[0,0]+(RawComponents[1,1]+RawComponents[2,2]); if t>2.9999999 then begin result.x:=0.0; result.y:=0.0; result.z:=0.0; result.w:=1.0; end else if t>0.0000001 then begin s:=sqrt(1.0+t)*2.0; result.x:=(RawComponents[1,2]-RawComponents[2,1])/s; result.y:=(RawComponents[2,0]-RawComponents[0,2])/s; result.z:=(RawComponents[0,1]-RawComponents[1,0])/s; result.w:=s*0.25; end else if (RawComponents[0,0]>RawComponents[1,1]) and (RawComponents[0,0]>RawComponents[2,2]) then begin s:=sqrt(1.0+(RawComponents[0,0]-(RawComponents[1,1]+RawComponents[2,2])))*2.0; result.x:=s*0.25; result.y:=(RawComponents[1,0]+RawComponents[0,1])/s; result.z:=(RawComponents[2,0]+RawComponents[0,2])/s; result.w:=(RawComponents[1,2]-RawComponents[2,1])/s; end else if RawComponents[1,1]>RawComponents[2,2] then begin s:=sqrt(1.0+(RawComponents[1,1]-(RawComponents[0,0]+RawComponents[2,2])))*2.0; result.x:=(RawComponents[1,0]+RawComponents[0,1])/s; result.y:=s*0.25; result.z:=(RawComponents[2,1]+RawComponents[1,2])/s; result.w:=(RawComponents[2,0]-RawComponents[0,2])/s; end else begin s:=sqrt(1.0+(RawComponents[2,2]-(RawComponents[0,0]+RawComponents[1,1])))*2.0; result.x:=(RawComponents[2,0]+RawComponents[0,2])/s; result.y:=(RawComponents[2,1]+RawComponents[1,2])/s; result.z:=s*0.25; result.w:=(RawComponents[0,1]-RawComponents[1,0])/s; end; result:=result.Normalize; end; begin // Make sure, that we don't end up with 0 as w component if abs(result.w)<=Threshold then begin Renormalization:=sqrt(1.0-sqr(Threshold)); result.x:=result.x*Renormalization; result.y:=result.y*Renormalization; result.z:=result.z*Renormalization; if result.w>0.0 then begin result.w:=Threshold; end else begin result.w:=-Threshold; end; end; end; if ((Scale<0.0) and (result.w>=0.0)) or ((Scale>=0.0) and (result.w<0.0)) then begin // Encode reflection into quaternion's w element by making sign of w negative, // if y axis needs to be flipped, otherwise it stays positive result.x:=-result.x; result.y:=-result.y; result.z:=-result.z; result.w:=-result.w; end; end; function TpvMatrix4x4.ToMatrix3x3:TpvMatrix3x3; begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[0,1]; result.RawComponents[0,2]:=RawComponents[0,2]; result.RawComponents[1,0]:=RawComponents[1,0]; result.RawComponents[1,1]:=RawComponents[1,1]; result.RawComponents[1,2]:=RawComponents[1,2]; result.RawComponents[2,0]:=RawComponents[2,0]; result.RawComponents[2,1]:=RawComponents[2,1]; result.RawComponents[2,2]:=RawComponents[2,2]; end; function TpvMatrix4x4.ToRotation:TpvMatrix4x4; begin result.RawComponents[0,0]:=RawComponents[0,0]; result.RawComponents[0,1]:=RawComponents[0,1]; result.RawComponents[0,2]:=RawComponents[0,2]; result.RawComponents[0,3]:=0.0; result.RawComponents[1,0]:=RawComponents[1,0]; result.RawComponents[1,1]:=RawComponents[1,1]; result.RawComponents[1,2]:=RawComponents[1,2]; result.RawComponents[1,3]:=0.0; result.RawComponents[2,0]:=RawComponents[2,0]; result.RawComponents[2,1]:=RawComponents[2,1]; result.RawComponents[2,2]:=RawComponents[2,2]; result.RawComponents[2,3]:=0.0; result.RawComponents[3,0]:=0.0; result.RawComponents[3,1]:=0.0; result.RawComponents[3,2]:=0.0; result.RawComponents[3,3]:=1.0; end; function TpvMatrix4x4.SimpleLerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=(self*(1.0-t))+(b*t); end; end; function TpvMatrix4x4.SimpleNlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; var InvT:TpvScalar; Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.xyz.Length, Up.xyz.Length, Forwards.xyz.Length).Lerp(TpvVector3.Create(b.Right.xyz.Length, b.Up.xyz.Length, b.Forwards.xyz.Length), t); result:=TpvMatrix4x4.CreateFromQuaternion(Normalize.ToQuaternion.Nlerp(b.Normalize.ToQuaternion,t)); result.Right.xyz:=result.Right.xyz*Scale.x; result.Up.xyz:=result.Up.xyz*Scale.y; result.Forwards.xyz:=result.Forwards.xyz*Scale.z; result.Translation:=Translation.Lerp(b.Translation,t); InvT:=1.0-t; result[0,3]:=(RawComponents[0,3]*InvT)+(b.RawComponents[0,3]*t); result[1,3]:=(RawComponents[1,3]*InvT)+(b.RawComponents[1,3]*t); result[2,3]:=(RawComponents[2,3]*InvT)+(b.RawComponents[2,3]*t); end; end; function TpvMatrix4x4.SimpleSlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; var InvT:TpvScalar; Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.xyz.Length, Up.xyz.Length, Forwards.xyz.Length).Lerp(TpvVector3.Create(b.Right.xyz.Length, b.Up.xyz.Length, b.Forwards.xyz.Length), t); result:=TpvMatrix4x4.CreateFromQuaternion(Normalize.ToQuaternion.Slerp(b.Normalize.ToQuaternion,t)); result.Right.xyz:=result.Right.xyz*Scale.x; result.Up.xyz:=result.Up.xyz*Scale.y; result.Forwards.xyz:=result.Forwards.xyz*Scale.z; result.Translation:=Translation.Lerp(b.Translation,t); InvT:=1.0-t; result[0,3]:=(RawComponents[0,3]*InvT)+(b.RawComponents[0,3]*t); result[1,3]:=(RawComponents[1,3]*InvT)+(b.RawComponents[1,3]*t); result[2,3]:=(RawComponents[2,3]*InvT)+(b.RawComponents[2,3]*t); end; end; function TpvMatrix4x4.SimpleElerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; var InvT:TpvScalar; Scale:TpvVector3; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin Scale:=TpvVector3.Create(Right.xyz.Length, Up.xyz.Length, Forwards.xyz.Length).Lerp(TpvVector3.Create(b.Right.xyz.Length, b.Up.xyz.Length, b.Forwards.xyz.Length), t); result:=TpvMatrix4x4.CreateFromQuaternion(Normalize.ToQuaternion.Elerp(b.Normalize.ToQuaternion,t)); result.Right.xyz:=result.Right.xyz*Scale.x; result.Up.xyz:=result.Up.xyz*Scale.y; result.Forwards.xyz:=result.Forwards.xyz*Scale.z; result.Translation:=Translation.Lerp(b.Translation,t); InvT:=1.0-t; result[0,3]:=(RawComponents[0,3]*InvT)+(b.RawComponents[0,3]*t); result[1,3]:=(RawComponents[1,3]*InvT)+(b.RawComponents[1,3]*t); result[2,3]:=(RawComponents[2,3]*InvT)+(b.RawComponents[2,3]*t); end; end; function TpvMatrix4x4.SimpleSqlerp(const aB,aC,aD:TpvMatrix4x4;const aTime:TpvScalar):TpvMatrix4x4; begin result:=SimpleSlerp(aD,aTime).SimpleSlerp(aB.SimpleSlerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvMatrix4x4.Lerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix4x4.CreateRecomposed(Decompose.Lerp(b.Decompose,t)); end; end; function TpvMatrix4x4.Nlerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix4x4.CreateRecomposed(Decompose.Nlerp(b.Decompose,t)); end; end; function TpvMatrix4x4.Slerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix4x4.CreateRecomposed(Decompose.Slerp(b.Decompose,t)); end; end; function TpvMatrix4x4.Elerp(const b:TpvMatrix4x4;const t:TpvScalar):TpvMatrix4x4; begin if t<=0.0 then begin result:=self; end else if t>=1.0 then begin result:=b; end else begin result:=TpvMatrix4x4.CreateRecomposed(Decompose.Elerp(b.Decompose,t)); end; end; function TpvMatrix4x4.Sqlerp(const aB,aC,aD:TpvMatrix4x4;const aTime:TpvScalar):TpvMatrix4x4; begin result:=Slerp(aD,aTime).Slerp(aB.Slerp(aC,aTime),(2.0*aTime)*(1.0-aTime)); end; function TpvMatrix4x4.MulInverse({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; var d:TpvScalar; begin d:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[2,1]*RawComponents[1,2])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[2,0]*RawComponents[1,2]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[2,0]*RawComponents[1,1]))); if d<>0.0 then begin d:=1.0/d; end; result.x:=((a.x*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))+(a.y*((RawComponents[1,2]*RawComponents[2,0])-(RawComponents[1,0]*RawComponents[2,2])))+(a.z*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))))*d; result.y:=((RawComponents[0,0]*((a.y*RawComponents[2,2])-(a.z*RawComponents[2,1])))+(RawComponents[0,1]*((a.z*RawComponents[2,0])-(a.x*RawComponents[2,2])))+(RawComponents[0,2]*((a.x*RawComponents[2,1])-(a.y*RawComponents[2,0]))))*d; result.z:=((RawComponents[0,0]*((RawComponents[1,1]*a.z)-(RawComponents[1,2]*a.y)))+(RawComponents[0,1]*((RawComponents[1,2]*a.x)-(RawComponents[1,0]*a.z)))+(RawComponents[0,2]*((RawComponents[1,0]*a.y)-(RawComponents[1,1]*a.x))))*d; end; function TpvMatrix4x4.MulInverse({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; var d:TpvScalar; begin d:=((RawComponents[0,0]*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[2,1]*RawComponents[1,2])))- (RawComponents[0,1]*((RawComponents[1,0]*RawComponents[2,2])-(RawComponents[2,0]*RawComponents[1,2]))))+ (RawComponents[0,2]*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[2,0]*RawComponents[1,1]))); if d<>0.0 then begin d:=1.0/d; end; result.x:=((a.x*((RawComponents[1,1]*RawComponents[2,2])-(RawComponents[1,2]*RawComponents[2,1])))+(a.y*((RawComponents[1,2]*RawComponents[2,0])-(RawComponents[1,0]*RawComponents[2,2])))+(a.z*((RawComponents[1,0]*RawComponents[2,1])-(RawComponents[1,1]*RawComponents[2,0]))))*d; result.y:=((RawComponents[0,0]*((a.y*RawComponents[2,2])-(a.z*RawComponents[2,1])))+(RawComponents[0,1]*((a.z*RawComponents[2,0])-(a.x*RawComponents[2,2])))+(RawComponents[0,2]*((a.x*RawComponents[2,1])-(a.y*RawComponents[2,0]))))*d; result.z:=((RawComponents[0,0]*((RawComponents[1,1]*a.z)-(RawComponents[1,2]*a.y)))+(RawComponents[0,1]*((RawComponents[1,2]*a.x)-(RawComponents[1,0]*a.z)))+(RawComponents[0,2]*((RawComponents[1,0]*a.y)-(RawComponents[1,1]*a.x))))*d; result.w:=a.w; end; function TpvMatrix4x4.MulInverted({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; var p:TpvVector3; begin p.x:=a.x-RawComponents[3,0]; p.y:=a.y-RawComponents[3,1]; p.z:=a.z-RawComponents[3,2]; result.x:=(RawComponents[0,0]*p.x)+(RawComponents[0,1]*p.y)+(RawComponents[0,2]*p.z); result.y:=(RawComponents[1,0]*p.x)+(RawComponents[1,1]*p.y)+(RawComponents[1,2]*p.z); result.z:=(RawComponents[2,0]*p.x)+(RawComponents[2,1]*p.y)+(RawComponents[2,2]*p.z); end; function TpvMatrix4x4.MulInverted({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; var p:TpvVector3; begin p.x:=a.x-RawComponents[3,0]; p.y:=a.y-RawComponents[3,1]; p.z:=a.z-RawComponents[3,2]; result.x:=(RawComponents[0,0]*p.x)+(RawComponents[0,1]*p.y)+(RawComponents[0,2]*p.z); result.y:=(RawComponents[1,0]*p.x)+(RawComponents[1,1]*p.y)+(RawComponents[1,2]*p.z); result.z:=(RawComponents[2,0]*p.x)+(RawComponents[2,1]*p.y)+(RawComponents[2,2]*p.z); result.w:=a.w; end; function TpvMatrix4x4.MulBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; begin result.x:=(RawComponents[0,0]*a.x)+(RawComponents[1,0]*a.y)+(RawComponents[2,0]*a.z); result.y:=(RawComponents[0,1]*a.x)+(RawComponents[1,1]*a.y)+(RawComponents[2,1]*a.z); result.z:=(RawComponents[0,2]*a.x)+(RawComponents[1,2]*a.y)+(RawComponents[2,2]*a.z); end; function TpvMatrix4x4.MulBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; begin result.x:=(RawComponents[0,0]*a.x)+(RawComponents[1,0]*a.y)+(RawComponents[2,0]*a.z); result.y:=(RawComponents[0,1]*a.x)+(RawComponents[1,1]*a.y)+(RawComponents[2,1]*a.z); result.z:=(RawComponents[0,2]*a.x)+(RawComponents[1,2]*a.y)+(RawComponents[2,2]*a.z); result.w:=a.w; end; function TpvMatrix4x4.MulTransposedBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; begin result.x:=(RawComponents[0,0]*a.x)+(RawComponents[0,1]*a.y)+(RawComponents[0,2]*a.z); result.y:=(RawComponents[1,0]*a.x)+(RawComponents[1,1]*a.y)+(RawComponents[1,2]*a.z); result.z:=(RawComponents[2,0]*a.x)+(RawComponents[2,1]*a.y)+(RawComponents[2,2]*a.z); end; function TpvMatrix4x4.MulTransposedBasis({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; begin result.x:=(RawComponents[0,0]*a.x)+(RawComponents[0,1]*a.y)+(RawComponents[0,2]*a.z); result.y:=(RawComponents[1,0]*a.x)+(RawComponents[1,1]*a.y)+(RawComponents[1,2]*a.z); result.z:=(RawComponents[2,0]*a.x)+(RawComponents[2,1]*a.y)+(RawComponents[2,2]*a.z); result.w:=a.w; end; function TpvMatrix4x4.MulHomogen({$ifdef fpc}constref{$else}const{$endif} a:TpvVector3):TpvVector3; var Temporary:TpvVector4; begin Temporary:=self*TpvVector4.Create(a,1.0); Temporary:=Temporary/Temporary.w; result:=Temporary.xyz; end; function TpvMatrix4x4.MulHomogen({$ifdef fpc}constref{$else}const{$endif} a:TpvVector4):TpvVector4; begin result:=self*a; result:=result/result.w; end; function TpvMatrix4x4.Decompose:TpvDecomposedMatrix4x4; var LocalMatrix,PerspectiveMatrix:TpvMatrix4x4; BasisMatrix:TpvMatrix3x3; begin if RawComponents[3,3]=0.0 then begin result.Valid:=false; end else if (RawComponents[0,0]=1.0) and (RawComponents[0,1]=0.0) and (RawComponents[0,2]=0.0) and (RawComponents[0,3]=0.0) and (RawComponents[1,0]=0.0) and (RawComponents[1,1]=1.0) and (RawComponents[1,2]=0.0) and (RawComponents[1,3]=0.0) and (RawComponents[2,0]=0.0) and (RawComponents[2,1]=0.0) and (RawComponents[2,2]=1.0) and (RawComponents[2,3]=0.0) and (RawComponents[3,0]=0.0) and (RawComponents[3,1]=0.0) and (RawComponents[3,2]=0.0) and (RawComponents[3,3]=1.0) then begin result.Perspective:=TpvVector4.Create(0.0,0.0,0.0,1.0); result.Translation:=TpvVector3.Create(0.0,0.0,0.0); result.Scale:=TpvVector3.Create(1.0,1.0,1.0); result.Skew:=TpvVector3.Create(0.0,0.0,0.0); result.Rotation:=TpvQuaternion.Create(0.0,0.0,0.0,1.0); result.Valid:=true; end else begin LocalMatrix.Tangent:=Tangent/RawComponents[3,3]; LocalMatrix.Bitangent:=Bitangent/RawComponents[3,3]; LocalMatrix.Normal:=Normal/RawComponents[3,3]; LocalMatrix.Translation:=Translation/RawComponents[3,3]; PerspectiveMatrix:=LocalMatrix; PerspectiveMatrix.RawComponents[0,3]:=0.0; PerspectiveMatrix.RawComponents[1,3]:=0.0; PerspectiveMatrix.RawComponents[2,3]:=0.0; PerspectiveMatrix.RawComponents[3,3]:=1.0; if PerspectiveMatrix.Determinant=0.0 then begin result.Valid:=false; end else begin if (LocalMatrix.RawComponents[0,3]<>0.0) or (LocalMatrix.RawComponents[1,3]<>0.0) or (LocalMatrix.RawComponents[2,3]<>0.0) then begin result.Perspective:=PerspectiveMatrix.Inverse.Transpose*TpvVector4.Create(LocalMatrix.RawComponents[0,3], LocalMatrix.RawComponents[1,3], LocalMatrix.RawComponents[2,3], LocalMatrix.RawComponents[3,3]); LocalMatrix.RawComponents[0,3]:=0.0; LocalMatrix.RawComponents[1,3]:=0.0; LocalMatrix.RawComponents[2,3]:=0.0; LocalMatrix.RawComponents[3,3]:=1.0; end else begin result.Perspective.x:=0.0; result.Perspective.y:=0.0; result.Perspective.z:=0.0; result.Perspective.w:=1.0; end; result.Translation:=LocalMatrix.Translation.xyz; LocalMatrix.Translation.xyz:=TpvVector3.Create(0.0,0.0,0.0); BasisMatrix:=ToMatrix3x3; result.Scale.x:=BasisMatrix.Right.Length; BasisMatrix.Right:=BasisMatrix.Right.Normalize; result.Skew.x:=BasisMatrix.Right.Dot(BasisMatrix.Up); BasisMatrix.Up:=BasisMatrix.Up-(BasisMatrix.Right*result.Skew.x); result.Scale.y:=BasisMatrix.Up.Length; BasisMatrix.Up:=BasisMatrix.Up.Normalize; result.Skew.x:=result.Skew.x/result.Scale.y; result.Skew.y:=BasisMatrix.Right.Dot(BasisMatrix.Forwards); BasisMatrix.Forwards:=BasisMatrix.Forwards-(BasisMatrix.Right*result.Skew.y); result.Skew.z:=BasisMatrix.Up.Dot(BasisMatrix.Forwards); BasisMatrix.Forwards:=BasisMatrix.Forwards-(BasisMatrix.Up*result.Skew.z); result.Scale.z:=BasisMatrix.Forwards.Length; BasisMatrix.Forwards:=BasisMatrix.Forwards.Normalize; result.Skew.yz:=result.Skew.yz/result.Scale.z; if BasisMatrix.Right.Dot(BasisMatrix.Up.Cross(BasisMatrix.Forwards))<0.0 then begin result.Scale.x:=-result.Scale.x; BasisMatrix:=-BasisMatrix; end; result.Rotation:=BasisMatrix.ToQuaternion; result.Valid:=true; end; end; end; constructor TpvDualQuaternion.Create(const pQ0,PQ1:TpvQuaternion); begin RawQuaternions[0]:=pQ0; RawQuaternions[1]:=pQ1; end; constructor TpvDualQuaternion.CreateFromRotationTranslationScale(const pRotation:TpvQuaternion;const pTranslation:TpvVector3;const pScale:TpvScalar); begin RawQuaternions[0]:=pRotation.Normalize; RawQuaternions[1]:=((0.5/RawQuaternions[0].Length)*RawQuaternions[0])*TpvQuaternion.Create(pTranslation.x,pTranslation.y,pTranslation.z,0.0); RawQuaternions[0]:=RawQuaternions[0]*pScale; end; constructor TpvDualQuaternion.CreateFromMatrix(const pMatrix:TpvMatrix4x4); begin RawQuaternions[0]:=pMatrix.ToQuaternion; RawQuaternions[1]:=((0.5/RawQuaternions[0].Length)*RawQuaternions[0])*TpvQuaternion.Create(pMatrix.Translation.x,pMatrix.Translation.y,pMatrix.Translation.z,0.0); RawQuaternions[0]:=RawQuaternions[0]*((pMatrix.Right.xyz.Length+pMatrix.Up.xyz.Length+pMatrix.Forwards.xyz.Length)/3.0); end; class operator TpvDualQuaternion.Implicit(const a:TpvMatrix4x4):TpvDualQuaternion; begin result:=TpvDualQuaternion.CreateFromMatrix(a); end; class operator TpvDualQuaternion.Explicit(const a:TpvMatrix4x4):TpvDualQuaternion; begin result:=TpvDualQuaternion.CreateFromMatrix(a); end; class operator TpvDualQuaternion.Implicit(const a:TpvDualQuaternion):TpvMatrix4x4; var Scale:TpvScalar; begin Scale:=a.RawQuaternions[0].Length; result:=TpvMatrix4x4.CreateFromQuaternion(a.RawQuaternions[0].Normalize); result.Right.xyz:=result.Right.xyz*Scale; result.Up.xyz:=result.Up.xyz*Scale; result.Forwards.xyz:=result.Forwards.xyz*Scale; result.Translation.xyz:=TpvQuaternion((2.0*a.RawQuaternions[0].Conjugate)*a.RawQuaternions[1]).Vector.xyz; end; class operator TpvDualQuaternion.Explicit(const a:TpvDualQuaternion):TpvMatrix4x4; var Scale:TpvScalar; begin Scale:=a.RawQuaternions[0].Length; result:=TpvMatrix4x4.CreateFromQuaternion(a.RawQuaternions[0].Normalize); result.Right.xyz:=result.Right.xyz*Scale; result.Up.xyz:=result.Up.xyz*Scale; result.Forwards.xyz:=result.Forwards.xyz*Scale; result.Translation.xyz:=TpvQuaternion((2.0*a.RawQuaternions[0].Conjugate)*a.RawQuaternions[1]).Vector.xyz; end; class operator TpvDualQuaternion.Equal(const a,b:TpvDualQuaternion):boolean; begin result:=(a.RawQuaternions[0]=b.RawQuaternions[0]) and (a.RawQuaternions[1]=b.RawQuaternions[1]); end; class operator TpvDualQuaternion.NotEqual(const a,b:TpvDualQuaternion):boolean; begin result:=(a.RawQuaternions[0]<>b.RawQuaternions[0]) or (a.RawQuaternions[1]<>b.RawQuaternions[1]); end; class operator TpvDualQuaternion.Add({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]+b.RawQuaternions[0]; result.RawQuaternions[1]:=a.RawQuaternions[1]+b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Subtract({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]-b.RawQuaternions[0]; result.RawQuaternions[1]:=a.RawQuaternions[1]-b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]*b.RawQuaternions[0]; result.RawQuaternions[1]:=((a.RawQuaternions[0]*b.RawQuaternions[1])/a.RawQuaternions[0].Length)+(a.RawQuaternions[1]*b.RawQuaternions[1]); end; class operator TpvDualQuaternion.Multiply(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]*b; result.RawQuaternions[1]:=a.RawQuaternions[1]*b; end; class operator TpvDualQuaternion.Multiply(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a*b.RawQuaternions[0]; result.RawQuaternions[1]:=a*b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector3):TpvVector3; begin result:=TpvQuaternion(a.RawQuaternions[0].Conjugate*((2.0*a.RawQuaternions[1])+(TpvQuaternion.Create(b.x,b.y,b.z,0.0)*a.RawQuaternions[0]))).Vector.xyz; end; class operator TpvDualQuaternion.Multiply(const a:TpvVector3;const b:TpvDualQuaternion):TpvVector3; begin result:=b.Inverse*a; end; class operator TpvDualQuaternion.Multiply({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion;{$ifdef fpc}constref{$else}const{$endif} b:TpvVector4):TpvVector4; begin result.xyz:=TpvQuaternion(a.RawQuaternions[0].Conjugate*((2.0*a.RawQuaternions[1])+(TpvQuaternion.Create(b.x,b.y,b.z,0.0)*a.RawQuaternions[0]))).Vector.xyz; result.w:=1.0; end; class operator TpvDualQuaternion.Multiply(const a:TpvVector4;const b:TpvDualQuaternion):TpvVector4; begin result:=b.Inverse*a; end; class operator TpvDualQuaternion.Divide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]/b.RawQuaternions[0]; result.RawQuaternions[1]:=a.RawQuaternions[1]/b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Divide(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]/b; result.RawQuaternions[1]:=a.RawQuaternions[1]/b; end; class operator TpvDualQuaternion.Divide(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a/b.RawQuaternions[0]; result.RawQuaternions[1]:=a/b.RawQuaternions[1]; end; class operator TpvDualQuaternion.IntDivide({$ifdef fpc}constref{$else}const{$endif} a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]/b.RawQuaternions[0]; result.RawQuaternions[1]:=a.RawQuaternions[1]/b.RawQuaternions[1]; end; class operator TpvDualQuaternion.IntDivide(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0]/b; result.RawQuaternions[1]:=a.RawQuaternions[1]/b; end; class operator TpvDualQuaternion.IntDivide(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a/b.RawQuaternions[0]; result.RawQuaternions[1]:=a/b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Modulus(const a,b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0] mod b.RawQuaternions[0]; result.RawQuaternions[1]:=a.RawQuaternions[1] mod b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Modulus(const a:TpvDualQuaternion;const b:TpvScalar):TpvDualQuaternion; begin result.RawQuaternions[0]:=a.RawQuaternions[0] mod b; result.RawQuaternions[1]:=a.RawQuaternions[1] mod b; end; class operator TpvDualQuaternion.Modulus(const a:TpvScalar;const b:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=a mod b.RawQuaternions[0]; result.RawQuaternions[1]:=a mod b.RawQuaternions[1]; end; class operator TpvDualQuaternion.Negative({$ifdef fpc}constref{$else}const{$endif} a:TpvDualQuaternion):TpvDualQuaternion; begin result.RawQuaternions[0]:=-a.RawQuaternions[0]; result.RawQuaternions[1]:=-a.RawQuaternions[1]; end; class operator TpvDualQuaternion.Positive(const a:TpvDualQuaternion):TpvDualQuaternion; begin result:=a; end; function TpvDualQuaternion.Flip:TpvDualQuaternion; begin result.RawQuaternions[0]:=RawQuaternions[0].Flip; result.RawQuaternions[1]:=RawQuaternions[1].Flip; end; function TpvDualQuaternion.Conjugate:TpvDualQuaternion; begin result.RawQuaternions[0].x:=-RawQuaternions[0].x; result.RawQuaternions[0].y:=-RawQuaternions[0].y; result.RawQuaternions[0].z:=-RawQuaternions[0].z; result.RawQuaternions[0].w:=RawQuaternions[0].w; result.RawQuaternions[1].x:=RawQuaternions[1].x; result.RawQuaternions[1].y:=RawQuaternions[1].y; result.RawQuaternions[1].z:=RawQuaternions[1].z; result.RawQuaternions[1].w:=-RawQuaternions[1].w; end; function TpvDualQuaternion.Inverse:TpvDualQuaternion; begin result.RawQuaternions[0]:=RawQuaternions[0].Conjugate; result.RawQuaternions[1]:=((-result.RawQuaternions[0])*RawQuaternions[1])*result.RawQuaternions[0]; result:=result/RawQuaternions[0].Length; end; function TpvDualQuaternion.Normalize:TpvDualQuaternion; var Scale:TpvScalar; begin Scale:=RawQuaternions[0].Length; result.RawQuaternions[0]:=RawQuaternions[0]/Scale; result.RawQuaternions[1]:=RawQuaternions[1]/Scale; result.RawQuaternions[1]:=result.RawQuaternions[1]-(result.RawQuaternions[0].Dot(result.RawQuaternions[1])*result.RawQuaternions[0]); end; constructor TpvSegment.Create(const p0,p1:TpvVector3); begin Points[0]:=p0; Points[1]:=p1; end; function TpvSegment.SquaredDistanceTo(const p:TpvVector3):TpvScalar; var pq,pp:TpvVector3; e,f:TpvScalar; begin pq:=Points[1]-Points[0]; pp:=p-Points[0]; e:=pp.Dot(pq); if e<=0.0 then begin result:=pp.SquaredLength; end else begin f:=pq.SquaredLength; if e<f then begin result:=pp.SquaredLength-(sqr(e)/f); end else begin result:=(p-Points[1]).SquaredLength; end; end; end; function TpvSegment.SquaredDistanceTo(const p:TpvVector3;out Nearest:TpvVector3):TpvScalar; var t,DotUV:TpvScalar; Diff,v:TpvVector3; begin Diff:=p-Points[0]; v:=Points[1]-Points[0]; t:=v.Dot(Diff); if t>0.0 then begin DotUV:=v.SquaredLength; if t<DotUV then begin t:=t/DotUV; Diff:=Diff-(v*t); end else begin t:=1; Diff:=Diff-v; end; end else begin t:=0.0; end; Nearest:=Points[0].Lerp(Points[1],t); result:=Diff.SquaredLength; end; procedure TpvSegment.ClosestPointTo(const p:TpvVector3;out Time:TpvScalar;out ClosestPoint:TpvVector3); var u,v:TpvVector3; begin u:=Points[1]-Points[0]; v:=p-Points[0]; Time:=u.Dot(v)/u.SquaredLength; if Time<=0.0 then begin ClosestPoint:=Points[0]; end else if Time>=1.0 then begin ClosestPoint:=Points[1]; end else begin ClosestPoint:=(Points[0]*(1.0-Time))+(Points[1]*Time); end; end; function TpvSegment.Transform(const Transform:TpvMatrix4x4):TpvSegment; begin result.Points[0]:=Transform*Points[0]; result.Points[1]:=Transform*Points[1]; end; procedure TpvSegment.ClosestPoints(const SegmentB:TpvSegment;out TimeA:TpvScalar;out ClosestPointA:TpvVector3;out TimeB:TpvScalar;out ClosestPointB:TpvVector3); var dA,dB,r:TpvVector3; a,b,c,{d,}e,f,Denominator,aA,aB,bA,bB:TpvScalar; begin dA:=Points[1]-Points[0]; dB:=SegmentB.Points[1]-SegmentB.Points[0]; r:=Points[0]-SegmentB.Points[0]; a:=dA.SquaredLength; e:=dB.SquaredLength; f:=dB.Dot(r); if (a<EPSILON) and (e<EPSILON) then begin // segment a and b are both points TimeA:=0.0; TimeB:=0.0; ClosestPointA:=Points[0]; ClosestPointB:=SegmentB.Points[0]; end else begin if a<EPSILON then begin // segment a is a point TimeA:=0.0; TimeB:=f/e; if TimeB<0.0 then begin TimeB:=0.0; end else if TimeB>1.0 then begin TimeB:=1.0; end; end else begin c:=dA.Dot(r); if e<EPSILON then begin // segment b is a point TimeA:=-(c/a); if TimeA<0.0 then begin TimeA:=0.0; end else if TimeA>1.0 then begin TimeA:=1.0; end; TimeB:=0.0; end else begin b:=dA.Dot(dB); Denominator:=(a*e)-sqr(b); if Denominator<EPSILON then begin // segments are parallel aA:=dB.Dot(Points[0]); aB:=dB.Dot(Points[1]); bA:=dB.Dot(SegmentB.Points[0]); bB:=dB.Dot(SegmentB.Points[1]); if (aA<=bA) and (aB<=bA) then begin // segment A is completely "before" segment B if aB>aA then begin TimeA:=1.0; end else begin TimeA:=0.0; end; TimeB:=0.0; end else if (aA>=bB) and (aB>=bB) then begin // segment B is completely "before" segment A if aB>aA then begin TimeA:=0.0; end else begin TimeA:=1.0; end; TimeB:=1.0; end else begin // segments A and B overlap, use midpoint of shared length if aA>aB then begin f:=aA; aA:=aB; aB:=f; end; f:=(Min(aB,bB)+Max(aA,bA))*0.5; TimeB:=(f-bA)/e; ClosestPointB:=SegmentB.Points[0]+(dB*TimeB); ClosestPointTo(ClosestPointB,TimeB,ClosestPointA); exit; end; end else begin // general case TimeA:=((b*f)-(c*e))/Denominator; if TimeA<0.0 then begin TimeA:=0.0; end else if TimeA>1.0 then begin TimeA:=1.0; end; TimeB:=((b*TimeA)+f)/e; if TimeB<0.0 then begin TimeB:=0.0; TimeA:=-(c/a); if TimeA<0.0 then begin TimeA:=0.0; end else if TimeA>1.0 then begin TimeA:=1.0; end; end else if TimeB>1.0 then begin TimeB:=1.0; TimeA:=(b-c)/a; if TimeA<0.0 then begin TimeA:=0.0; end else if TimeA>1.0 then begin TimeA:=1.0; end; end; end; end; end; ClosestPointA:=Points[0]+(dA*TimeA); ClosestPointB:=SegmentB.Points[0]+(dB*TimeB); end; end; function TpvSegment.Intersect(const SegmentB:TpvSegment;out TimeA,TimeB:TpvScalar;out IntersectionPoint:TpvVector3):boolean; var PointA:TpvVector3; begin ClosestPoints(SegmentB,TimeA,PointA,TimeB,IntersectionPoint); result:=(PointA-IntersectionPoint).SquaredLength<EPSILON; end; function TpvRelativeSegment.SquaredSegmentDistanceTo(const pOtherRelativeSegment:TpvRelativeSegment;out t0,t1:TpvScalar):TpvScalar; var kDiff:TpvVector3; fA00,fA01,fA11,fB0,fC,fDet,fB1,fS,fT,fSqrDist,fTmp,fInvDet:TpvScalar; begin kDiff:=self.Origin-pOtherRelativeSegment.Origin; fA00:=self.Delta.SquaredLength; fA01:=-self.Delta.Dot(pOtherRelativeSegment.Delta); fA11:=pOtherRelativeSegment.Delta.SquaredLength; fB0:=kDiff.Dot(self.Delta); fC:=kDiff.SquaredLength; fDet:=abs((fA00*fA11)-(fA01*fA01)); if fDet>=EPSILON then begin // line segments are not parallel fB1:=-kDiff.Dot(pOtherRelativeSegment.Delta); fS:=(fA01*fB1)-(fA11*fB0); fT:=(fA01*fB0)-(fA00*fB1); if fS>=0.0 then begin if fS<=fDet then begin if fT>=0.0 then begin if fT<=fDet then begin // region 0 (interior) // minimum at two interior points of 3D lines fInvDet:=1.0/fDet; fS:=fS*fInvDet; fT:=fT*fInvDet; fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2.0*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2.0*fB1)))+fC; end else begin // region 3 (side) fT:=1.0; fTmp:=fA01+fB0; if fTmp>=0.0 then begin fS:=0.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else if (-fTmp)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fB1+fTmp)); end else begin fS:=-fTmp/fA00; fSqrDist:=fTmp*fS+fA11+(2.0*fB1)+fC; end; end; end else begin // region 7 (side) fT:=0.0; if fB0>=0.0 then begin fS:=0.0; fSqrDist:=fC; end else if (-fB0)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end; end else begin if fT>=0.0 then begin if fT<=fDet then begin // region 1 (side) fS:=1.0; fTmp:=fA01+fB1; if fTmp>=0.0 then begin fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else if (-fTmp)>=fA11 then begin fT:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp)); end else begin fT:=(-fTmp)/fA11; fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC; end; end else begin // region 2 (corner) fTmp:=fA01+fB0; if (-fTmp)<=fA00 then begin fT:=1.0; if fTmp>=0.0 then begin fS:=0.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fS:=(-fTmp)/fA00; fSqrDist:=(fTmp*fS)+fA11+(2.0*fB1)+fC; end; end else begin fS:=1.0; fTmp:=fA01+fB1; if fTmp>=0.0 then begin fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else if (-fTmp)>=fA11 then begin fT:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp)); end else begin fT:=(-fTmp)/fA11; fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC; end; end; end; end else begin // region 8 (corner) if (-fB0)<fA00 then begin fT:=0.0; if fB0>=0.0 then begin fS:=0.0; fSqrDist:=fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end else begin fS:=1.0; fTmp:=fA01+fB1; if fTmp>=0.0 then begin fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else if (-fTmp)>=fA11 then begin fT:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp)); end else begin fT:=(-fTmp)/fA11; fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC; end; end; end; end; end else begin if fT>=0.0 then begin if fT<=fDet then begin // region 5 (side) fS:=0.0; if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else if (-fB1)>=fA11 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=fB1*fT+fC; end end else begin // region 4 (corner) fTmp:=fA01+fB0; if fTmp<0.0 then begin fT:=1.0; if (-fTmp)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fB1+fTmp)); end else begin fS:=(-fTmp)/fA00; fSqrDist:=fTmp*fS+fA11+(2.0*fB1)+fC; end; end else begin fS:=0.0; if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else if (-fB1)>=fA11 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=(fB1*fT)+fC; end; end; end; end else begin // region 6 (corner) if fB0<0.0 then begin fT:=0.0; if (-fB0)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end else begin fS:=0.0; if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else if (-fB1)>=fA11 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=(fB1*fT)+fC; end; end; end; end; end else begin // line segments are parallel if fA01>0.0 then begin // direction vectors form an obtuse angle if fB0>=0.0 then begin fS:=0.0; fT:=0.0; fSqrDist:=fC; end else if (-fB0)<=fA00 then begin fS:=(-fB0)/fA00; fT:=0.0; fSqrDist:=(fB0*fS)+fC; end else begin fB1:=-kDiff.Dot(pOtherRelativeSegment.Delta); fS:=1.0; fTmp:=fA00+fB0; if (-fTmp)>=fA01 then begin fT:=1.0; fSqrDist:=fA00+fA11+fC+(2.0*(fA01+fB0+fB1)); end else begin fT:=(-fTmp)/fA01; fSqrDist:=fA00+(2.0*fB0)+fC+(fT*((fA11*fT)+(2.0*(fA01+fB1)))); end; end; end else begin // direction vectors form an acute angle if (-fB0)>=fA00 then begin fS:=1.0; fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else if fB0<=0.0 then begin fS:=(-fB0)/fA00; fT:=0.0; fSqrDist:=(fB0*fS)+fC; end else begin fB1:=-kDiff.Dot(pOtherRelativeSegment.Delta); fS:=0.0; if fB0>=(-fA01) then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB0)/fA01; fSqrDist:=fC+(fT*((2.0)*fB1)+(fA11*fT)); end; end; end; end; t0:=fS; t1:=fT; result:=abs(fSqrDist); end; constructor TpvTriangle.Create(const pA,pB,pC:TpvVector3); begin Points[0]:=pA; Points[1]:=pB; Points[2]:=pC; Normal:=((pB-pA).Cross(pC-pA)).Normalize; end; function TpvTriangle.Contains(const p:TpvVector3):boolean; var vA,vB,vC:TpvVector3; dAB,dAC,dBC:TpvScalar; begin vA:=Points[0]-p; vB:=Points[1]-p; vC:=Points[2]-p; dAB:=vA.Dot(vB); dAC:=vA.Dot(vC); dBC:=vB.Dot(vC); if ((dBC*dAC)-(vC.SquaredLength*dAB))<0.0 then begin result:=false; end else begin result:=((dAB*dBC)-(dAC*vB.SquaredLength))>=0.0; end; end; procedure TpvTriangle.ProjectToVector(const Vector:TpvVector3;out TriangleMin,TriangleMax:TpvScalar); var Projection:TpvScalar; begin Projection:=Vector.Dot(Points[0]); TriangleMin:=Projection; TriangleMax:=Projection; Projection:=Vector.Dot(Points[1]); TriangleMin:=Min(TriangleMin,Projection); TriangleMax:=Max(TriangleMax,Projection); Projection:=Vector.Dot(Points[2]); TriangleMin:=Min(TriangleMin,Projection); TriangleMax:=Max(TriangleMax,Projection); end; function TpvTriangle.ProjectToPoint(var pPoint:TpvVector3;out s,t:TpvScalar):TpvScalar; var Diff,Edge0,Edge1:TpvVector3; A00,A01,A11,B0,C,Det,B1,SquaredDistance,InvDet,Tmp0,Tmp1,Numer,Denom:TpvScalar; begin Diff:=Points[0]-pPoint; Edge0:=Points[1]-Points[0]; Edge1:=Points[2]-Points[0]; A00:=Edge0.SquaredLength; A01:=Edge0.Dot(Edge1); A11:=Edge1.SquaredLength; B0:=Diff.Dot(Edge0); B1:=Diff.Dot(Edge1); C:=Diff.SquaredLength; Det:=max(abs((A00*A11)-(A01*A01)),EPSILON); s:=(A01*B1)-(A11*B0); t:=(A01*B0)-(A00*B1); if (s+t)<=Det then begin if s<0.0 then begin if t<0.0 then begin // region 4 if B0<0.0 then begin t:=0.0; if (-B0)>=A00 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end else begin s:=0.0; if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else if (-B1)>=A11 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else begin // region 3 s:=0.0; if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else if (-B1)>=A11 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else if t<0.0 then begin // region 5 t:=0.0; if B0>=0.0 then begin s:=0.0; SquaredDistance:=C; end else if (-B0)>=A00 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end else begin // region 0 // minimum at interior point InvDet:=1.0/Det; s:=s*InvDet; t:=t*InvDet; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end else begin if s<0.0 then begin // region 2 Tmp0:=A01+B0; Tmp1:=A11+B1; if Tmp1>Tmp0 then begin Numer:=Tmp1-Tmp0; Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin s:=1.0; t:=0.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=Numer/Denom; t:=1.0-s; SquaredDistance:=(s*((A00*s)+(A01*t)+(2*B0)))+(t*((A01*s)+(A11*t)+(2*B1)))+C; end; end else begin s:=0.0; if Tmp1<=0.0 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else if t<0.0 then begin // region 6 Tmp0:=A01+B1; Tmp1:=A00+B0; if Tmp1>Tmp0 then begin Numer:=Tmp1-Tmp0; Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin t:=1.0; s:=0.0; SquaredDistance:=A11+(2*B1)+C; end else begin t:=Numer/Denom; s:=1.0-t; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end else begin t:=0.0; if Tmp1<=0.0 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else if B0>=0.0 then begin s:=0.0; SquaredDistance:=C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end; end else begin // region 1 Numer:=((A11+B1)-A01)-B0; if Numer<=0.0 then begin s:=0.0; t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin s:=1.0; t:=0.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=Numer/Denom; t:=1.0-s; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end; end; end; pPoint.x:=Points[0].x+((Edge0.x*s)+(Edge1.x*t)); pPoint.y:=Points[0].y+((Edge0.y*s)+(Edge1.y*t)); pPoint.z:=Points[0].z+((Edge0.z*s)+(Edge1.z*t)); result:=abs(SquaredDistance); end; function TpvTriangle.SegmentIntersect(const Segment:TpvSegment;out Time:TpvScalar;out IntersectionPoint:TpvVector3):boolean; var Switched:boolean; d,t,v,w:TpvScalar; vAB,vAC,pBA,vApA,e,n:TpvVector3; s:TpvSegment; begin result:=false; Time:=NaN; IntersectionPoint:=TpvVector3.Origin; Switched:=false; vAB:=Points[1]-Points[0]; vAC:=Points[2]-Points[0]; pBA:=Segment.Points[0]-Segment.Points[1]; n:=vAB.Cross(vAC); d:=n.Dot(pBA); if abs(d)<EPSILON then begin exit; // segment is parallel end else if d<0.0 then begin s.Points[0]:=Segment.Points[1]; s.Points[1]:=Segment.Points[0]; Switched:=true; pBA:=s.Points[0]-s.Points[1]; d:=-d; end else begin s:=Segment; end; vApA:=s.Points[0]-Points[0]; t:=n.Dot(vApA); e:=pBA.Cross(vApA); v:=vAC.Dot(e); if (v<0.0) or (v>d) then begin exit; // intersects outside triangle end; w:=-vAB.Dot(e); if (w<0.0) or ((v+w)>d) then begin exit; // intersects outside triangle end; d:=1.0/d; t:=t*d; v:=v*d; w:=w*d; Time:=t; IntersectionPoint:=Points[0]+((vAB*v)+(vAC*w)); if Switched then begin Time:=1.0-Time; end; result:=(Time>=0.0) and (Time<=1.0); end; function TpvTriangle.ClosestPointTo(const Point:TpvVector3;out ClosestPoint:TpvVector3):boolean; var u,v,w,d1,d2,d3,d4,d5,d6,Denominator:TpvScalar; vAB,vAC,vAp,vBp,vCp:TpvVector3; begin result:=false; vAB:=Points[1]-Points[0]; vAC:=Points[2]-Points[0]; vAp:=Point-Points[0]; d1:=vAB.Dot(vAp); d2:=vAC.Dot(vAp); if (d1<=0.0) and (d2<=0.0) then begin ClosestPoint:=Points[0]; // closest point is vertex A exit; end; vBp:=Point-Points[1]; d3:=vAB.Dot(vBp); d4:=vAC.Dot(vBp); if (d3>=0.0) and (d4<=d3) then begin ClosestPoint:=Points[1]; // closest point is vertex B exit; end; w:=(d1*d4)-(d3*d2); if (w<=0.0) and (d1>=0.0) and (d3<=0.0) then begin // closest point is along edge 1-2 ClosestPoint:=Points[0]+(vAB*(d1/(d1-d3))); exit; end; vCp:=Point-Points[2]; d5:=vAB.Dot(vCp); d6:=vAC.Dot(vCp); if (d6>=0.0) and (d5<=d6) then begin ClosestPoint:=Points[2]; // closest point is vertex C exit; end; v:=(d5*d2)-(d1*d6); if (v<=0.0) and (d2>=0.0) and (d6<=0.0) then begin // closest point is along edge 1-3 ClosestPoint:=Points[0]+(vAC*(d2/(d2-d6))); exit; end; u:=(d3*d6)-(d5*d4); if (u<=0.0) and ((d4-d3)>=0.0) and ((d5-d6)>=0.0) then begin // closest point is along edge 2-3 ClosestPoint:=Points[1]+((Points[2]-Points[1])*((d4-d3)/((d4-d3)+(d5-d6)))); exit; end; Denominator:=1.0/(u+v+w); ClosestPoint:=Points[0]+((vAB*(v*Denominator))+(vAC*(w*Denominator))); result:=true; end; function TpvTriangle.ClosestPointTo(const Segment:TpvSegment;out Time:TpvScalar;out pClosestPointOnSegment,pClosestPointOnTriangle:TpvVector3):boolean; var MinDist,dtri,d1,d2,sa,sb,dist:TpvScalar; pAInside,pBInside:boolean; pa,pb:TpvVector3; Edge:TpvSegment; begin result:=SegmentIntersect(Segment,Time,pClosestPointOnTriangle); if result then begin // segment intersects triangle pClosestPointOnSegment:=pClosestPointOnTriangle; end else begin MinDist:=MAX_SCALAR; pClosestPointOnSegment:=TpvVector3.Origin; dtri:=Normal.Dot(Points[0]); pAInside:=Contains(Segment.Points[0]); pBInside:=Contains(Segment.Points[1]); if pAInside and pBInside then begin // both points inside triangle d1:=Normal.Dot(Segment.Points[0])-dtri; d2:=Normal.Dot(Segment.Points[1])-dtri; if abs(d2-d1)<EPSILON then begin // segment is parallel to triangle pClosestPointOnSegment:=(Segment.Points[0]+Segment.Points[1])*0.5; MinDist:=d1; Time:=0.5; end else if abs(d1)<abs(d2) then begin pClosestPointOnSegment:=Segment.Points[0]; MinDist:=d1; Time:=0.0; end else begin pClosestPointOnSegment:=Segment.Points[1]; MinDist:=d2; Time:=1.0; end; pClosestPointOnTriangle:=pClosestPointOnSegment+(Normal*(-MinDist)); result:=true; exit; end else if pAInside then begin // one point is inside triangle pClosestPointOnSegment:=Segment.Points[0]; Time:=0.0; MinDist:=Normal.Dot(pClosestPointOnSegment)-dtri; pClosestPointOnTriangle:=pClosestPointOnSegment+(Normal*(-MinDist)); MinDist:=sqr(MinDist); end else if pBInside then begin // one point is inside triangle pClosestPointOnSegment:=Segment.Points[1]; Time:=1.0; MinDist:=Normal.Dot(pClosestPointOnSegment)-dtri; pClosestPointOnTriangle:=pClosestPointOnSegment+(Normal*(-MinDist)); MinDist:=sqr(MinDist); end; // test edge 1 Edge.Points[0]:=Points[0]; Edge.Points[1]:=Points[1]; Segment.ClosestPoints(Edge,sa,pa,sb,pb); Dist:=(pa-pb).SquaredLength; if Dist<MinDist then begin MinDist:=Dist; Time:=sa; pClosestPointOnSegment:=pa; pClosestPointOnTriangle:=pb; end; // test edge 2 Edge.Points[0]:=Points[1]; Edge.Points[1]:=Points[2]; Segment.ClosestPoints(Edge,sa,pa,sb,pb); Dist:=(pa-pb).SquaredLength; if Dist<MinDist then begin MinDist:=Dist; Time:=sa; pClosestPointOnSegment:=pa; pClosestPointOnTriangle:=pb; end; // test edge 3 Edge.Points[0]:=Points[2]; Edge.Points[1]:=Points[0]; Segment.ClosestPoints(Edge,sa,pa,sb,pb); Dist:=(pa-pb).SquaredLength; if Dist<MinDist then begin // MinDist:=Dist; Time:=sa; pClosestPointOnSegment:=pa; pClosestPointOnTriangle:=pb; end; end; end; function TpvTriangle.GetClosestPointTo(const pPoint:TpvVector3;out ClosestPoint:TpvVector3;out s,t:TpvScalar):TpvScalar; var Diff,Edge0,Edge1:TpvVector3; A00,A01,A11,B0,C,Det,B1,SquaredDistance,InvDet,Tmp0,Tmp1,Numer,Denom:TpvScalar; begin Diff:=Points[0]-pPoint; Edge0:=Points[1]-Points[0]; Edge1:=Points[2]-Points[0]; A00:=Edge0.SquaredLength; A01:=Edge0.Dot(Edge1); A11:=Edge1.SquaredLength; B0:=Diff.Dot(Edge0); B1:=Diff.Dot(Edge1); C:=Diff.SquaredLength; Det:=max(abs((A00*A11)-(A01*A01)),EPSILON); s:=(A01*B1)-(A11*B0); t:=(A01*B0)-(A00*B1); if (s+t)<=Det then begin if s<0.0 then begin if t<0.0 then begin // region 4 if B0<0.0 then begin t:=0.0; if (-B0)>=A00 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end else begin s:=0.0; if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else if (-B1)>=A11 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else begin // region 3 s:=0.0; if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else if (-B1)>=A11 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else if t<0.0 then begin // region 5 t:=0.0; if B0>=0.0 then begin s:=0.0; SquaredDistance:=C; end else if (-B0)>=A00 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end else begin // region 0 // minimum at interior point InvDet:=1.0/Det; s:=s*InvDet; t:=t*InvDet; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end else begin if s<0.0 then begin // region 2 Tmp0:=A01+B0; Tmp1:=A11+B1; if Tmp1>Tmp0 then begin Numer:=Tmp1-Tmp0; Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin s:=1.0; t:=0.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=Numer/Denom; t:=1.0-s; SquaredDistance:=(s*((A00*s)+(A01*t)+(2*B0)))+(t*((A01*s)+(A11*t)+(2*B1)))+C; end; end else begin s:=0.0; if Tmp1<=0.0 then begin t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else if B1>=0.0 then begin t:=0.0; SquaredDistance:=C; end else begin t:=(-B1)/A11; SquaredDistance:=(B1*t)+C; end; end; end else if t<0.0 then begin // region 6 Tmp0:=A01+B1; Tmp1:=A00+B0; if Tmp1>Tmp0 then begin Numer:=Tmp1-Tmp0; Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin t:=1.0; s:=0.0; SquaredDistance:=A11+(2*B1)+C; end else begin t:=Numer/Denom; s:=1.0-t; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end else begin t:=0.0; if Tmp1<=0.0 then begin s:=1.0; SquaredDistance:=A00+(2.0*B0)+C; end else if B0>=0.0 then begin s:=0.0; SquaredDistance:=C; end else begin s:=(-B0)/A00; SquaredDistance:=(B0*s)+C; end; end; end else begin // region 1 Numer:=((A11+B1)-A01)-B0; if Numer<=0.0 then begin s:=0.0; t:=1.0; SquaredDistance:=A11+(2.0*B1)+C; end else begin Denom:=A00-(2.0*A01)+A11; if Numer>=Denom then begin s:=1.0; t:=0.0; SquaredDistance:=A00+(2.0*B0)+C; end else begin s:=Numer/Denom; t:=1.0-s; SquaredDistance:=(s*((A00*s)+(A01*t)+(2.0*B0)))+(t*((A01*s)+(A11*t)+(2.0*B1)))+C; end; end; end; end; ClosestPoint.x:=Points[0].x+((Edge0.x*s)+(Edge1.x*t)); ClosestPoint.y:=Points[0].y+((Edge0.y*s)+(Edge1.y*t)); ClosestPoint.z:=Points[0].z+((Edge0.z*s)+(Edge1.z*t)); result:=abs(SquaredDistance); end; function TpvTriangle.GetClosestPointTo(const pPoint:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; var s,t:TpvScalar; begin result:=GetClosestPointTo(pPoint,ClosestPoint,s,t); end; function TpvTriangle.DistanceTo(const Point:TpvVector3):TpvScalar; var SegmentTriangle:TpvSegmentTriangle; s,t:TpvScalar; begin SegmentTriangle.Origin:=Points[0]; SegmentTriangle.Edge0:=Points[1]-Points[0]; SegmentTriangle.Edge1:=Points[2]-Points[0]; SegmentTriangle.Edge2:=SegmentTriangle.Edge1-SegmentTriangle.Edge0; {result:=}SegmentTriangle.SquaredPointTriangleDistance(Point,s,t); {if result>EPSILON then begin result:=sqrt(result); end else if result<EPSILON then begin result:=-sqrt(-result); end else begin result:=0; end;} result:=Point.DistanceTo(SegmentTriangle.Origin+((SegmentTriangle.Edge0*s)+(SegmentTriangle.Edge1*t))); end; function TpvTriangle.SquaredDistanceTo(const Point:TpvVector3):TpvScalar; var SegmentTriangle:TpvSegmentTriangle; s,t:TpvScalar; begin SegmentTriangle.Origin:=Points[0]; SegmentTriangle.Edge0:=Points[1]-Points[0]; SegmentTriangle.Edge1:=Points[2]-Points[0]; SegmentTriangle.Edge2:=SegmentTriangle.Edge1-SegmentTriangle.Edge0; result:=SegmentTriangle.SquaredPointTriangleDistance(Point,s,t); end; function TpvTriangle.RayIntersection(const RayOrigin,RayDirection:TpvVector3;var Time,u,v:TpvScalar):boolean; var e0,e1,p,t,q:TpvVector3; Determinant,InverseDeterminant:TpvScalar; begin result:=false; e0.x:=Points[1].x-Points[0].x; e0.y:=Points[1].y-Points[0].y; e0.z:=Points[1].z-Points[0].z; e1.x:=Points[2].x-Points[0].x; e1.y:=Points[2].y-Points[0].y; e1.z:=Points[2].z-Points[0].z; p.x:=(RayDirection.y*e1.z)-(RayDirection.z*e1.y); p.y:=(RayDirection.z*e1.x)-(RayDirection.x*e1.z); p.z:=(RayDirection.x*e1.y)-(RayDirection.y*e1.x); Determinant:=(e0.x*p.x)+(e0.y*p.y)+(e0.z*p.z); if Determinant<EPSILON then begin exit; end; t.x:=RayOrigin.x-Points[0].x; t.y:=RayOrigin.y-Points[0].y; t.z:=RayOrigin.z-Points[0].z; u:=(t.x*p.x)+(t.y*p.y)+(t.z*p.z); if (u<0.0) or (u>Determinant) then begin exit; end; q.x:=(t.y*e0.z)-(t.z*e0.y); q.y:=(t.z*e0.x)-(t.x*e0.z); q.z:=(t.x*e0.y)-(t.y*e0.x); v:=(RayDirection.x*q.x)+(RayDirection.y*q.y)+(RayDirection.z*q.z); if (v<0.0) or ((u+v)>Determinant) then begin exit; end; Time:=(e1.x*q.x)+(e1.y*q.y)+(e1.z*q.z); if abs(Determinant)<EPSILON then begin Determinant:=0.01; end; InverseDeterminant:=1.0/Determinant; Time:=Time*InverseDeterminant; u:=u*InverseDeterminant; v:=v*InverseDeterminant; result:=true; end; function TpvSegmentTriangle.RelativeSegmentIntersection(const ppvSegment:TpvRelativeSegment;out tS,tT0,tT1:TpvScalar):boolean; var u,v,t,a,f:TpvScalar; e1,e2,p,s,q:TpvVector3; begin result:=false; tS:=0.0; tT0:=0.0; tT1:=0.0; e1:=Edge0; e2:=Edge1; p:=ppvSegment.Delta.Cross(e2); a:=e1.Dot(p); if abs(a)<EPSILON then begin exit; end; f:=1.0/a; s:=ppvSegment.Origin-Origin; u:=f*s.Dot(p); if (u<0.0) or (u>1.0) then begin exit; end; q:=s.Cross(e1); v:=f*ppvSegment.Delta.Dot(q); if (v<0.0) or ((u+v)>1.0) then begin exit; end; t:=f*e2.Dot(q); if (t<0.0) or (t>1.0) then begin exit; end; tS:=t; tT0:=u; tT1:=v; result:=true; end; function TpvSegmentTriangle.SquaredPointTriangleDistance(const pPoint:TpvVector3;out pfSParam,pfTParam:TpvScalar):TpvScalar; var kDiff:TpvVector3; fA00,fA01,fA11,fB0,fC,fDet,fB1,fS,fT,fSqrDist,fInvDet,fTmp0,fTmp1,fNumer,fDenom:TpvScalar; begin kDiff:=self.Origin-pPoint; fA00:=self.Edge0.SquaredLength; fA01:=self.Edge0.Dot(self.Edge1); fA11:=self.Edge1.SquaredLength; fB0:=kDiff.Dot(self.Edge0); fB1:=kDiff.Dot(self.Edge1); fC:=kDiff.SquaredLength; fDet:=max(abs((fA00*fA11)-(fA01*fA01)),EPSILON); fS:=(fA01*fB1)-(fA11*fB0); fT:=(fA01*fB0)-(fA00*fB1); if (fS+fT)<=fDet then begin if fS<0.0 then begin if fT<0.0 then begin // region 4 if fB0<0.0 then begin fT:=0.0; if (-fB0)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end else begin fS:=0.0; if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else if (-fB1)>=fA11 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=(fB1*fT)+fC; end; end; end else begin // region 3 fS:=0.0; if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else if (-fB1)>=fA11 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=(fB1*fT)+fC; end; end; end else if fT<0.0 then begin // region 5 fT:=0.0; if fB0>=0.0 then begin fS:=0.0; fSqrDist:=fC; end else if (-fB0)>=fA00 then begin fS:=1.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end else begin // region 0 // minimum at interior point fInvDet:=1.0/fDet; fS:=fS*fInvDet; fT:=fT*fInvDet; fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2.0*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2.0*fB1)))+fC; end; end else begin if fS<0.0 then begin // region 2 fTmp0:=fA01+fB0; fTmp1:=fA11+fB1; if fTmp1>fTmp0 then begin fNumer:=fTmp1-fTmp0; fDenom:=fA00-(2.0*fA01)+fA11; if fNumer>=fDenom then begin fS:=1.0; fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=fNumer/fDenom; fT:=1.0-fS; fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2*fB1)))+fC; end; end else begin fS:=0.0; if fTmp1<=0.0 then begin fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else if fB1>=0.0 then begin fT:=0.0; fSqrDist:=fC; end else begin fT:=(-fB1)/fA11; fSqrDist:=(fB1*fT)+fC; end; end; end else if fT<0.0 then begin // region 6 fTmp0:=fA01+fB1; fTmp1:=fA00+fB0; if fTmp1>fTmp0 then begin fNumer:=fTmp1-fTmp0; fDenom:=fA00-(2.0*fA01)+fA11; if fNumer>=fDenom then begin fT:=1.0; fS:=0.0; fSqrDist:=fA11+(2*fB1)+fC; end else begin fT:=fNumer/fDenom; fS:=1.0-fT; fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2.0*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2.0*fB1)))+fC; end; end else begin fT:=0.0; if fTmp1<=0.0 then begin fS:=1.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else if fB0>=0.0 then begin fS:=0.0; fSqrDist:=fC; end else begin fS:=(-fB0)/fA00; fSqrDist:=(fB0*fS)+fC; end; end; end else begin // region 1 fNumer:=((fA11+fB1)-fA01)-fB0; if fNumer<=0.0 then begin fS:=0.0; fT:=1.0; fSqrDist:=fA11+(2.0*fB1)+fC; end else begin fDenom:=fA00-(2.0*fA01)+fA11; if fNumer>=fDenom then begin fS:=1.0; fT:=0.0; fSqrDist:=fA00+(2.0*fB0)+fC; end else begin fS:=fNumer/fDenom; fT:=1.0-fS; fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2.0*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2.0*fB1)))+fC; end; end; end; end; pfSParam:=fS; pfTParam:=fT; result:=abs(fSqrDist); end; function TpvSegmentTriangle.SquaredDistanceTo(const ppvRelativeSegment:TpvRelativeSegment;out segT,triT0,triT1:TpvScalar):TpvScalar; var s,t,u,distEdgeSq,startTriSq,endTriSq:TpvScalar; tseg:TpvRelativeSegment; begin result:=INFINITY; if RelativeSegmentIntersection(ppvRelativeSegment,segT,triT0,triT1) then begin segT:=0.0; triT0:=0.0; triT1:=0.0; result:=0.0; exit; end; tseg.Origin:=Origin; tseg.Delta:=Edge0; distEdgeSq:=ppvRelativeSegment.SquaredSegmentDistanceTo(tseg,s,t); if distEdgeSq<result then begin result:=distEdgeSq; segT:=s; triT0:=t; triT1:=0.0; end; tseg.Delta:=Edge1; distEdgeSq:=ppvRelativeSegment.SquaredSegmentDistanceTo(tseg,s,t); if distEdgeSq<result then begin result:=distEdgeSq; segT:=s; triT0:=0.0; triT1:=t; end; tseg.Origin:=Origin+Edge1; tseg.Delta:=Edge2; distEdgeSq:=ppvRelativeSegment.SquaredSegmentDistanceTo(tseg,s,t); if distEdgeSq<result then begin result:=distEdgeSq; segT:=s; triT0:=1.0-t; triT1:=t; end; startTriSq:=SquaredPointTriangleDistance(ppvRelativeSegment.Origin,t,u); if startTriSq<result then begin result:=startTriSq; segT:=0.0; triT0:=t; triT1:=u; end; endTriSq:=SquaredPointTriangleDistance(ppvRelativeSegment.Origin+ppvRelativeSegment.Delta,t,u); if endTriSq<result then begin result:=endTriSq; segT:=1.0; triT0:=t; triT1:=u; end; end; procedure TpvOBB.ProjectToVector(const Vector:TpvVector3;out OBBMin,OBBMax:TpvScalar); var ProjectionCenter,ProjectionRadius:TpvScalar; begin ProjectionCenter:=Center.Dot(Vector); ProjectionRadius:=abs(Vector.Dot(Axis[0])*HalfExtents.x)+ abs(Vector.Dot(Axis[1])*HalfExtents.y)+ abs(Vector.Dot(Axis[2])*HalfExtents.z); OBBMin:=ProjectionCenter-ProjectionRadius; OBBMax:=ProjectionCenter+ProjectionRadius; end; function TpvOBB.Intersect(const aWith:TpvOBB;const aThreshold:TpvScalar):boolean; function Check(const aRelativePosition,aAxis:TpvVector3):boolean; {$ifdef fpc}inline;{$endif} begin result:=abs(aRelativePosition.Dot(aAxis))<= ((abs((Axis[0]*HalfExtents.x).Dot(aAxis))+ abs((Axis[1]*HalfExtents.y).Dot(aAxis))+ abs((Axis[2]*HalfExtents.z).Dot(aAxis))+ abs((aWith.Axis[0]*aWith.HalfExtents.x).Dot(aAxis))+ abs((aWith.Axis[1]*aWith.HalfExtents.y).Dot(aAxis))+ abs((aWith.Axis[2]*aWith.HalfExtents.z).Dot(aAxis)))+ aThreshold); end; var RelativePosition:TpvVector3; begin RelativePosition:=aWith.Center-Center; result:=Check(RelativePosition,Axis[0]) and Check(RelativePosition,Axis[1]) and Check(RelativePosition,Axis[2]) and Check(RelativePosition,aWith.Axis[0]) and Check(RelativePosition,aWith.Axis[1]) and Check(RelativePosition,aWith.Axis[2]) and Check(RelativePosition,Axis[0].Cross(aWith.Axis[0])) and Check(RelativePosition,Axis[0].Cross(aWith.Axis[1])) and Check(RelativePosition,Axis[0].Cross(aWith.Axis[2])) and Check(RelativePosition,Axis[1].Cross(aWith.Axis[0])) and Check(RelativePosition,Axis[1].Cross(aWith.Axis[1])) and Check(RelativePosition,Axis[1].Cross(aWith.Axis[2])) and Check(RelativePosition,Axis[2].Cross(aWith.Axis[0])) and Check(RelativePosition,Axis[2].Cross(aWith.Axis[1])) and Check(RelativePosition,Axis[2].Cross(aWith.Axis[2])); end; function TpvOBB.RelativeSegmentIntersection(const ppvRelativeSegment:TpvRelativeSegment;out fracOut:TpvScalar;out posOut,NormalOut:TpvVector3):boolean; var min_,max_,e,f,t1,t2,t:TpvScalar; p{,h}:TpvVector3; dirMax,dirMin,dir:TpvInt32; begin result:=false; fracOut:=1e+34; posOut:=TpvVector3.Origin; normalOut:=TpvVector3.Origin; min_:=-1e+34; max_:=1e+34; p:=Center-ppvRelativeSegment.Origin; //h:=HalfExtents; dirMax:=0; dirMin:=0; for dir:=0 to 2 do begin e:=Axis[Dir].Dot(p); f:=Axis[Dir].Dot(ppvRelativeSegment.Delta); if abs(f)>EPSILON then begin t1:=(e+HalfExtents.RawComponents[dir])/f; t2:=(e-HalfExtents.RawComponents[dir])/f; if t1>t2 then begin t:=t1; t1:=t2; t2:=t; end; if min_<t1 then begin min_:=t1; dirMin:=dir; end; if max_>t2 then begin max_:=t2; dirMax:=dir; end; if (min_>max_) or (max_<0.0) then begin exit; end; end else if (((-e)-HalfExtents.RawComponents[dir])>0.0) or (((-e)+HalfExtents.RawComponents[dir])<0.0) then begin exit; end; end; if min_>0.0 then begin dir:=dirMin; fracOut:=min_; end else begin dir:=dirMax; fracOut:=max_; end; fracOut:=Min(Max(fracOut,0.0),1.0); posOut:=ppvRelativeSegment.Origin+(ppvRelativeSegment.Delta*fracOut); if Axis[dir].Dot(ppvRelativeSegment.Delta)>0.0 then begin normalOut:=-Axis[dir]; end else begin normalOut:=Axis[dir]; end; result:=true; end; function TpvOBB.TriangleIntersection(const Triangle:TpvTriangle;out Position,Normal:TpvVector3;out Penetration:TpvScalar):boolean; const OBBEdges:array[0..11,0..1] of TpvInt32= ((0,1), (0,3), (0,4), (1,2), (1,5), (2,3), (2,6), (3,7), (4,5), (4,7), (5,6), (6,7)); ModuloThree:array[0..5] of TpvInt32=(0,1,2,0,1,2); var OBBVertices:array[0..7] of TpvVector3; TriangleVertices,TriangleEdges:array[0..2] of TpvVector3; TriangleNormal,BestAxis,CurrentAxis,v,p,n,pt0,pt1:TpvVector3; BestPenetration,CurrentPenetration,tS,tT0,tT1:TpvScalar; BestAxisIndex,i,j:TpvInt32; seg,s1,s2:TpvRelativeSegment; SegmentTriangle:TpvSegmentTriangle; begin result:=false; // --- OBBVertices[0]:=self.Center+(self.Axis[0]*(-self.HalfExtents.x))+(self.Axis[1]*(-self.HalfExtents.y))+(self.Axis[2]*(-self.HalfExtents.z)); // +-- OBBVertices[1]:=self.Center+(self.Axis[0]*self.HalfExtents.x)+(self.Axis[1]*(-self.HalfExtents.y))+(self.Axis[2]*(-self.HalfExtents.z)); // ++- OBBVertices[2]:=self.Center+(self.Axis[0]*self.HalfExtents.x)+(self.Axis[1]*self.HalfExtents.y)+(self.Axis[2]*(-self.HalfExtents.z)); // -+- OBBVertices[3]:=self.Center+(self.Axis[0]*(-self.HalfExtents.x))+(self.Axis[1]*self.HalfExtents.y)+(self.Axis[2]*(-self.HalfExtents.z)); // --+ OBBVertices[4]:=self.Center+(self.Axis[0]*(-self.HalfExtents.x))+(self.Axis[1]*(-self.HalfExtents.y))+(self.Axis[2]*self.HalfExtents.z); // +-+ OBBVertices[5]:=self.Center+(self.Axis[0]*self.HalfExtents.x)+(self.Axis[1]*(-self.HalfExtents.y))+(self.Axis[2]*self.HalfExtents.z); // +++ OBBVertices[6]:=self.Center+(self.Axis[0]*self.HalfExtents.x)+(self.Axis[1]*self.HalfExtents.y)+(self.Axis[2]*self.HalfExtents.z); // -++ OBBVertices[7]:=self.Center+(self.Axis[0]*(-self.HalfExtents.x))+(self.Axis[1]*(-self.HalfExtents.y))+(self.Axis[2]*self.HalfExtents.z); TriangleVertices[0]:=Triangle.Points[0]; TriangleVertices[1]:=Triangle.Points[1]; TriangleVertices[2]:=Triangle.Points[2]; TriangleEdges[0]:=Triangle.Points[1]-Triangle.Points[0]; TriangleEdges[1]:=Triangle.Points[2]-Triangle.Points[1]; TriangleEdges[2]:=Triangle.Points[0]-Triangle.Points[2]; TriangleNormal:=TriangleEdges[0].Cross(TriangleEdges[1]).Normalize; BestPenetration:=0; BestAxis:=TpvVector3.Origin; BestAxisIndex:=-1; for i:=0 to 2 do begin CurrentPenetration:=DoSpanIntersect(@OBBVertices[0],8,@TriangleVertices[0],3,self.Axis[i],CurrentAxis); if CurrentPenetration<0.0 then begin exit; end else if (i=0) or (CurrentPenetration<BestPenetration) then begin BestPenetration:=CurrentPenetration; BestAxis:=CurrentAxis; BestAxisIndex:=i; end; end; CurrentPenetration:=DoSpanIntersect(@OBBVertices[0],8,@TriangleVertices[0],3,TriangleNormal,CurrentAxis); if CurrentPenetration<0.0 then begin exit; end else if CurrentPenetration<BestPenetration then begin BestPenetration:=CurrentPenetration; BestAxis:=CurrentAxis; BestAxisIndex:=3; end; for i:=0 to 2 do begin for j:=0 to 2 do begin CurrentPenetration:=DoSpanIntersect(@OBBVertices[0],8,@TriangleVertices[0],3,self.Axis[i].Cross(TriangleEdges[j]),CurrentAxis); if CurrentPenetration<0.0 then begin exit; end else if CurrentPenetration<BestPenetration then begin BestPenetration:=CurrentPenetration; BestAxis:=CurrentAxis; BestAxisIndex:=((i*3)+j)+4; end; end; end; Penetration:=BestPenetration; Normal:=BestAxis; if BestAxisIndex>=0 then begin j:=0; v:=TpvVector3.Origin; SegmentTriangle.Origin:=Triangle.Points[0]; SegmentTriangle.Edge0:=Triangle.Points[1]-Triangle.Points[0]; SegmentTriangle.Edge1:=Triangle.Points[2]-Triangle.Points[0]; for i:=0 to 11 do begin seg.Origin:=OBBVertices[OBBEdges[i,0]]; seg.Delta:=OBBVertices[OBBEdges[i,1]]-OBBVertices[OBBEdges[i,0]]; if SegmentTriangle.RelativeSegmentIntersection(seg,tS,tT0,tT1) then begin v:=v+seg.Origin+(seg.Delta*tS); inc(j); end; end; for i:=0 to 2 do begin pt0:=TriangleVertices[i]; pt1:=TriangleVertices[ModuloThree[i+1]]; s1.Origin:=pt0; s1.Delta:=pt1-pt0; s2.Origin:=pt1; s2.Delta:=pt0-pt1; if RelativeSegmentIntersection(s1,tS,p,n) then begin v:=v+p; inc(j); end; if RelativeSegmentIntersection(s2,tS,p,n) then begin v:=v+p; inc(j); end; end; if j>0 then begin Position:=v/j; end else begin ClosestPointToOBB(self,(Triangle.Points[0]+Triangle.Points[1]+Triangle.Points[2])/3.0,Position); end; end; result:=true; end; function TpvOBB.TriangleIntersection(const ppvTriangle:TpvTriangle;const MTV:PpvVector3=nil):boolean; var TriangleEdges:array[0..2] of TpvVector3; TriangleNormal{,d},ProjectionVector:TpvVector3; TriangleMin,TriangleMax,OBBMin,OBBMax,Projection,BestOverlap,Overlap:TpvScalar; OBBAxisIndex,TriangleEdgeIndex:TpvInt32; BestAxis,TheAxis:TpvVector3; begin result:=false; TriangleEdges[0]:=ppvTriangle.Points[1]-ppvTriangle.Points[0]; TriangleEdges[1]:=ppvTriangle.Points[2]-ppvTriangle.Points[0]; TriangleEdges[2]:=ppvTriangle.Points[2]-ppvTriangle.Points[1]; TriangleNormal:=TriangleEdges[0].Cross(TriangleEdges[1]); //d:=TriangleEdges[0]-Center; TriangleMin:=TriangleNormal.Dot(ppvTriangle.Points[0]); TriangleMax:=TriangleMin; ProjectToVector(TriangleNormal,OBBMin,OBBMax); if (TriangleMin>OBBMax) or (TriangleMax<OBBMin) then begin exit; end; BestAxis:=TriangleNormal; BestOverlap:=GetOverlap(OBBMin,OBBMax,TriangleMin,TriangleMax); for OBBAxisIndex:=0 to 2 do begin TheAxis:=self.Axis[OBBAxisIndex]; ppvTriangle.ProjectToVector(TheAxis,TriangleMin,TriangleMax); Projection:=TheAxis.Dot(Center); OBBMin:=Projection-HalfExtents.RawComponents[OBBAxisIndex]; OBBMax:=Projection+HalfExtents.RawComponents[OBBAxisIndex]; if (TriangleMin>OBBMax) or (TriangleMax<OBBMin) then begin exit; end; Overlap:=GetOverlap(OBBMin,OBBMax,TriangleMin,TriangleMax); if Overlap<BestOverlap then begin BestAxis:=TheAxis; BestOverlap:=Overlap; end; end; for OBBAxisIndex:=0 to 2 do begin for TriangleEdgeIndex:=0 to 2 do begin ProjectionVector:=TriangleEdges[TriangleEdgeIndex].Cross(Axis[OBBAxisIndex]); ProjectToVector(ProjectionVector,OBBMin,OBBMax); ppvTriangle.ProjectToVector(ProjectionVector,TriangleMin,TriangleMax); if (TriangleMin>OBBMax) or (TriangleMax<OBBMin) then begin exit; end; Overlap:=GetOverlap(OBBMin,OBBMax,TriangleMin,TriangleMax); if Overlap<BestOverlap then begin BestAxis:=ProjectionVector; BestOverlap:=Overlap; end; end; end; if assigned(MTV) then begin MTV^:=BestAxis*BestOverlap; end; result:=true; end; constructor TpvAABB.Create(const pMin,pMax:TpvVector3); begin Min:=pMin; Max:=pMax; end; constructor TpvAABB.CreateFromOBB(const OBB:TpvOBB); var t:TpvVector3; begin t.x:=abs((OBB.Matrix[0,0]*OBB.HalfExtents.x)+(OBB.Matrix[1,0]*OBB.HalfExtents.y)+(OBB.Matrix[2,0]*OBB.HalfExtents.z)); t.y:=abs((OBB.Matrix[0,1]*OBB.HalfExtents.x)+(OBB.Matrix[1,1]*OBB.HalfExtents.y)+(OBB.Matrix[2,1]*OBB.HalfExtents.z)); t.z:=abs((OBB.Matrix[0,2]*OBB.HalfExtents.x)+(OBB.Matrix[1,2]*OBB.HalfExtents.y)+(OBB.Matrix[2,2]*OBB.HalfExtents.z)); Min.x:=OBB.Center.x-t.x; Min.y:=OBB.Center.y-t.y; Min.z:=OBB.Center.z-t.z; Max.x:=OBB.Center.x+t.x; Max.y:=OBB.Center.y+t.y; Max.z:=OBB.Center.z+t.z; end; function TpvAABB.Cost:TpvScalar; begin result:=(Max.x-Min.x)+(Max.y-Min.y)+(Max.z-Min.z); // Manhattan distance end; function TpvAABB.Volume:TpvScalar; begin result:=(Max.x-Min.x)*(Max.y-Min.y)*(Max.z-Min.z); // Volume end; function TpvAABB.Area:TpvScalar; begin result:=2.0*((abs(Max.x-Min.x)*abs(Max.y-Min.y))+ (abs(Max.y-Min.y)*abs(Max.z-Min.z))+ (abs(Max.x-Min.x)*abs(Max.z-Min.z))); end; function TpvAABB.Center:TpvVector3; begin result:=(Min+Max)*0.5; end; function TpvAABB.Flip:TpvAABB; var a,b:TpvVector3; begin a:=Min.Flip; b:=Max.Flip; result.Min.x:=Math.Min(a.x,b.x); result.Min.y:=Math.Min(a.y,b.y); result.Min.z:=Math.Min(a.z,b.z); result.Max.x:=Math.Max(a.x,b.x); result.Max.y:=Math.Max(a.y,b.y); result.Max.z:=Math.Max(a.z,b.z); end; function TpvAABB.SquareMagnitude:TpvScalar; begin result:=sqr(Max.x-Min.x)+(Max.y-Min.y)+sqr(Max.z-Min.z); end; function TpvAABB.Resize(const f:TpvScalar):TpvAABB; var v:TpvVector3; begin v:=(Max-Min)*f; result.Min:=Min-v; result.Max:=Max+v; end; function TpvAABB.Combine(const WithAABB:TpvAABB):TpvAABB; begin result.Min.x:=Math.Min(Min.x,WithAABB.Min.x); result.Min.y:=Math.Min(Min.y,WithAABB.Min.y); result.Min.z:=Math.Min(Min.z,WithAABB.Min.z); result.Max.x:=Math.Max(Max.x,WithAABB.Max.x); result.Max.y:=Math.Max(Max.y,WithAABB.Max.y); result.Max.z:=Math.Max(Max.z,WithAABB.Max.z); end; function TpvAABB.CombineVector3(v:TpvVector3):TpvAABB; begin result.Min.x:=Math.Min(Min.x,v.x); result.Min.y:=Math.Min(Min.y,v.y); result.Min.z:=Math.Min(Min.z,v.z); result.Max.x:=Math.Max(Max.x,v.x); result.Max.y:=Math.Max(Max.y,v.y); result.Max.z:=Math.Max(Max.z,v.z); end; function TpvAABB.DistanceTo(const ToAABB:TpvAABB):TpvScalar; begin result:=0.0; if Min.x>ToAABB.Max.x then begin result:=result+sqr(ToAABB.Max.x-Min.x); end else if ToAABB.Min.x>Max.x then begin result:=result+sqr(Max.x-ToAABB.Min.x); end; if Min.y>ToAABB.Max.y then begin result:=result+sqr(ToAABB.Max.y-Min.y); end else if ToAABB.Min.y>Max.y then begin result:=result+sqr(Max.y-ToAABB.Min.y); end; if Min.z>ToAABB.Max.z then begin result:=result+sqr(ToAABB.Max.z-Min.z); end else if ToAABB.Min.z>Max.z then begin result:=result+sqr(Max.z-ToAABB.Min.z); end; if result>0.0 then begin result:=sqrt(result); end; end; function TpvAABB.Radius:TpvScalar; begin result:=Math.Max(Min.DistanceTo((Min+Max)*0.5),Max.DistanceTo((Min+Max)*0.5)); end; function TpvAABB.Compare(const WithAABB:TpvAABB):boolean; begin result:=(Min=WithAABB.Min) and (Max=WithAABB.Max); end; function TpvAABB.Intersect(const aWith:TpvOBB;const aThreshold:TpvScalar):boolean; var OBBCenterToAABBCenter,AABBHalfExtents:TpvVector3; begin OBBCenterToAABBCenter:=aWith.Center-Min.Lerp(Max,0.5); AABBHalfExtents:=(Max-Min)*0.5; result:=((abs(OBBCenterToAABBCenter.Dot(aWith.Axis[0]))-AABBHalfExtents.Dot(aWith.Axis[0]))<=(aWith.HalfExtents.Dot(aWith.Axis[0])+aThreshold)) and ((abs(OBBCenterToAABBCenter.Dot(aWith.Axis[1]))-AABBHalfExtents.Dot(aWith.Axis[1]))<=(aWith.HalfExtents.Dot(aWith.Axis[1])+aThreshold)) and ((abs(OBBCenterToAABBCenter.Dot(aWith.Axis[2]))-AABBHalfExtents.Dot(aWith.Axis[2]))<=(aWith.HalfExtents.Dot(aWith.Axis[2])+aThreshold)); end; function TpvAABB.Intersect(const WithAABB:TpvAABB;Threshold:TpvScalar):boolean; begin result:=(((Max.x+Threshold)>=(WithAABB.Min.x-Threshold)) and ((Min.x-Threshold)<=(WithAABB.Max.x+Threshold))) and (((Max.y+Threshold)>=(WithAABB.Min.y-Threshold)) and ((Min.y-Threshold)<=(WithAABB.Max.y+Threshold))) and (((Max.z+Threshold)>=(WithAABB.Min.z-Threshold)) and ((Min.z-Threshold)<=(WithAABB.Max.z+Threshold))); end; class function TpvAABB.Intersect(const aAABBMin,aAABBMax:TpvVector3;const WithAABB:TpvAABB;Threshold:TpvScalar):boolean; begin result:=(((aAABBMax.x+Threshold)>=(WithAABB.Min.x-Threshold)) and ((aAABBMin.x-Threshold)<=(WithAABB.Max.x+Threshold))) and (((aAABBMax.y+Threshold)>=(WithAABB.Min.y-Threshold)) and ((aAABBMin.y-Threshold)<=(WithAABB.Max.y+Threshold))) and (((aAABBMax.z+Threshold)>=(WithAABB.Min.z-Threshold)) and ((aAABBMin.z-Threshold)<=(WithAABB.Max.z+Threshold))); end; function TpvAABB.Contains(const AABB:TpvAABB;const aThreshold:TpvScalar=EPSILON):boolean; begin result:=((Min.x-aThreshold)<=(AABB.Min.x+aThreshold)) and ((Min.y-aThreshold)<=(AABB.Min.y+aThreshold)) and ((Min.z-aThreshold)<=(AABB.Min.z+aThreshold)) and ((Max.x+aThreshold)>=(AABB.Min.x-aThreshold)) and ((Max.y+aThreshold)>=(AABB.Min.y-aThreshold)) and ((Max.z+aThreshold)>=(AABB.Min.z-aThreshold)) and ((Min.x-aThreshold)<=(AABB.Max.x+aThreshold)) and ((Min.y-aThreshold)<=(AABB.Max.y+aThreshold)) and ((Min.z-aThreshold)<=(AABB.Max.z+aThreshold)) and ((Max.x+aThreshold)>=(AABB.Max.x-aThreshold)) and ((Max.y+aThreshold)>=(AABB.Max.y-aThreshold)) and ((Max.z+aThreshold)>=(AABB.Max.z-aThreshold)); end; class function TpvAABB.Contains(const aAABBMin,aAABBMax:TpvVector3;const aAABB:TpvAABB;const aThreshold:TpvScalar=EPSILON):boolean; begin result:=((aAABBMin.x-aThreshold)<=(aAABB.Min.x+aThreshold)) and ((aAABBMin.y-aThreshold)<=(aAABB.Min.y+aThreshold)) and ((aAABBMin.z-aThreshold)<=(aAABB.Min.z+aThreshold)) and ((aAABBMax.x+aThreshold)>=(aAABB.Min.x-aThreshold)) and ((aAABBMax.y+aThreshold)>=(aAABB.Min.y-aThreshold)) and ((aAABBMax.z+aThreshold)>=(aAABB.Min.z-aThreshold)) and ((aAABBMin.x-aThreshold)<=(aAABB.Max.x+aThreshold)) and ((aAABBMin.y-aThreshold)<=(aAABB.Max.y+aThreshold)) and ((aAABBMin.z-aThreshold)<=(aAABB.Max.z+aThreshold)) and ((aAABBMax.x+aThreshold)>=(aAABB.Max.x-aThreshold)) and ((aAABBMax.y+aThreshold)>=(aAABB.Max.y-aThreshold)) and ((aAABBMax.z+aThreshold)>=(aAABB.Max.z-aThreshold)); end; function TpvAABB.Contains(const Vector:TpvVector3):boolean; begin result:=((Vector.x>=(Min.x-EPSILON)) and (Vector.x<=(Max.x+EPSILON))) and ((Vector.y>=(Min.y-EPSILON)) and (Vector.y<=(Max.y+EPSILON))) and ((Vector.z>=(Min.z-EPSILON)) and (Vector.z<=(Max.z+EPSILON))); end; class function TpvAABB.Contains(const aAABBMin,aAABBMax,aVector:TpvVector3):boolean; begin result:=((aVector.x>=(aAABBMin.x-EPSILON)) and (aVector.x<=(aAABBMax.x+EPSILON))) and ((aVector.y>=(aAABBMin.y-EPSILON)) and (aVector.y<=(aAABBMax.y+EPSILON))) and ((aVector.z>=(aAABBMin.z-EPSILON)) and (aVector.z<=(aAABBMax.z+EPSILON))); end; function TpvAABB.Contains(const aOBB:TpvOBB):boolean; var Axes:array[0..3] of TpvVector3; begin Axes[0]:=aOBB.Axis[0]*aOBB.HalfExtents.x; Axes[1]:=aOBB.Axis[1]*aOBB.HalfExtents.y; Axes[2]:=aOBB.Axis[2]*aOBB.HalfExtents.z; Axes[3]:=Axes[0]+Axes[1]+Axes[2]; result:=Contains(aOBB.Center-Axes[0]) and Contains(aOBB.Center-Axes[1]) and Contains(aOBB.Center-Axes[2]) and Contains(aOBB.Center-Axes[3]) and Contains(aOBB.Center+Axes[0]) and Contains(aOBB.Center+Axes[1]) and Contains(aOBB.Center+Axes[2]) and Contains(aOBB.Center+Axes[3]); end; function TpvAABB.Touched(const Vector:TpvVector3;const Threshold:TpvScalar=1e-5):boolean; begin result:=((Vector.x>=(Min.x-Threshold)) and (Vector.x<=(Max.x+Threshold))) and ((Vector.y>=(Min.y-Threshold)) and (Vector.y<=(Max.y+Threshold))) and ((Vector.z>=(Min.z-Threshold)) and (Vector.z<=(Max.z+Threshold))); end; function TpvAABB.GetIntersection(const WithAABB:TpvAABB):TpvAABB; begin result.Min.x:=Math.Max(Min.x,WithAABB.Min.x); result.Min.y:=Math.Max(Min.y,WithAABB.Min.y); result.Min.z:=Math.Max(Min.z,WithAABB.Min.z); result.Max.x:=Math.Min(Max.x,WithAABB.Max.x); result.Max.y:=Math.Min(Max.y,WithAABB.Max.y); result.Max.z:=Math.Min(Max.z,WithAABB.Max.z); end; function TpvAABB.FastRayIntersection(const Origin,Direction:TpvVector3):boolean; var t0,t1:TpvVector3; begin // Although it might seem this doesn't address edge cases where // Direction.{x,y,z} equals zero, it is indeed correct. This is // because the comparisons still work as expected when infinities // emerge from zero division. Rays that are parallel to an axis // and positioned outside the box will lead to tmin being infinity // or tmax turning into negative infinity, yet for rays located // within the box, the values for tmin and tmax will remain unchanged. t0:=(Min-Origin)/Direction; t1:=(Max-Origin)/Direction; result:=Math.Max(0.0,Math.Max(Math.Max(Math.Min(Math.Min(t0.x,t1.x),Infinity), Math.Min(Math.Min(t0.y,t1.y),Infinity)), Math.Min(Math.Min(t0.z,t1.z),Infinity)))<= Math.Min(Math.Min(Math.Max(Math.Max(t0.x,t1.x),NegInfinity), Math.Max(Math.Max(t0.y,t1.y),NegInfinity)), Math.Max(Math.Max(t0.z,t1.z),NegInfinity)); end; {var Center,BoxExtents,Diff:TpvVector3; begin Center:=(Min+Max)*0.5; BoxExtents:=Center-Min; Diff:=Origin-Center; result:=not ((((abs(Diff.x)>BoxExtents.x) and ((Diff.x*Direction.x)>=0)) or ((abs(Diff.y)>BoxExtents.y) and ((Diff.y*Direction.y)>=0)) or ((abs(Diff.z)>BoxExtents.z) and ((Diff.z*Direction.z)>=0))) or ((abs((Direction.y*Diff.z)-(Direction.z*Diff.y))>((BoxExtents.y*abs(Direction.z))+(BoxExtents.z*abs(Direction.y)))) or (abs((Direction.z*Diff.x)-(Direction.x*Diff.z))>((BoxExtents.x*abs(Direction.z))+(BoxExtents.z*abs(Direction.x)))) or (abs((Direction.x*Diff.y)-(Direction.y*Diff.x))>((BoxExtents.x*abs(Direction.y))+(BoxExtents.y*abs(Direction.x)))))); end;} class function TpvAABB.FastRayIntersection(const aAABBMin,aAABBMax:TpvVector3;const Origin,Direction:TpvVector3):boolean; var t0,t1:TpvVector3; begin // Although it might seem this doesn't address edge cases where // Direction.{x,y,z} equals zero, it is indeed correct. This is // because the comparisons still work as expected when infinities // emerge from zero division. Rays that are parallel to an axis // and positioned outside the box will lead to tmin being infinity // or tmax turning into negative infinity, yet for rays located // within the box, the values for tmin and tmax will remain unchanged. t0:=(aAABBMin-Origin)/Direction; t1:=(aAABBMax-Origin)/Direction; result:=Math.Max(0.0,Math.Max(Math.Max(Math.Min(Math.Min(t0.x,t1.x),Infinity), Math.Min(Math.Min(t0.y,t1.y),Infinity)), Math.Min(Math.Min(t0.z,t1.z),Infinity)))<= Math.Min(Math.Min(Math.Max(Math.Max(t0.x,t1.x),NegInfinity), Math.Max(Math.Max(t0.y,t1.y),NegInfinity)), Math.Max(Math.Max(t0.z,t1.z),NegInfinity)); end; {var Center,BoxExtents,Diff:TpvVector3; begin Center:=(aAABBMin+aAABBMax)*0.5; BoxExtents:=Center-aAABBMin; Diff:=Origin-Center; result:=not ((((abs(Diff.x)>BoxExtents.x) and ((Diff.x*Direction.x)>=0)) or ((abs(Diff.y)>BoxExtents.y) and ((Diff.y*Direction.y)>=0)) or ((abs(Diff.z)>BoxExtents.z) and ((Diff.z*Direction.z)>=0))) or ((abs((Direction.y*Diff.z)-(Direction.z*Diff.y))>((BoxExtents.y*abs(Direction.z))+(BoxExtents.z*abs(Direction.y)))) or (abs((Direction.z*Diff.x)-(Direction.x*Diff.z))>((BoxExtents.x*abs(Direction.z))+(BoxExtents.z*abs(Direction.x)))) or (abs((Direction.x*Diff.y)-(Direction.y*Diff.x))>((BoxExtents.x*abs(Direction.y))+(BoxExtents.y*abs(Direction.x)))))); end;} function TpvAABB.RayIntersectionHitDistance(const Origin,Direction:TpvVector3;var HitDist:TpvScalar):boolean; var DirFrac:TpvVector3; t:array[0..5] of TpvScalar; tMin,tMax:TpvScalar; begin DirFrac.x:=1.0/Direction.x; DirFrac.y:=1.0/Direction.y; DirFrac.z:=1.0/Direction.z; t[0]:=(Min.x-Origin.x)*DirFrac.x; t[1]:=(Max.x-Origin.x)*DirFrac.x; t[2]:=(Min.y-Origin.y)*DirFrac.y; t[3]:=(Max.y-Origin.y)*DirFrac.y; t[4]:=(Min.z-Origin.z)*DirFrac.z; t[5]:=(Max.z-Origin.z)*DirFrac.z; tMin:=Math.Max(Math.Max(Math.Min(t[0],t[1]),Math.Min(t[2],t[3])),Math.Min(t[4],t[5])); tMax:=Math.Min(Math.Min(Math.Max(t[0],t[1]),Math.Max(t[2],t[3])),Math.Max(t[4],t[5])); if (tMax<0) or (tMin>tMax) then begin HitDist:=tMax; result:=false; end else begin HitDist:=tMin; result:=true; end; end; function TpvAABB.RayIntersectionHitPoint(const Origin,Direction:TpvVector3;out HitPoint:TpvVector3):boolean; const RIGHT=0; LEFT=1; MIDDLE=2; var i,WhicHPlane:TpvInt32; Inside:longbool; Quadrant:array[0..2] of TpvInt32; MaxT,CandidatePlane:TpvVector3; begin Inside:=true; for i:=0 to 2 do begin if Origin.RawComponents[i]<Min.RawComponents[i] then begin Quadrant[i]:=LEFT; CandidatePlane.RawComponents[i]:=Min.RawComponents[i]; Inside:=false; end else if Origin.RawComponents[i]>Max.RawComponents[i] then begin Quadrant[i]:=RIGHT; CandidatePlane.RawComponents[i]:=Max.RawComponents[i]; Inside:=false; end else begin Quadrant[i]:=MIDDLE; end; end; if Inside then begin HitPoint:=Origin; result:=true; end else begin for i:=0 to 2 do begin if (Quadrant[i]<>MIDDLE) and (Direction.RawComponents[i]<>0.0) then begin MaxT.RawComponents[i]:=(CandidatePlane.RawComponents[i]-Origin.RawComponents[i])/Direction.RawComponents[i]; end else begin MaxT.RawComponents[i]:=-1.0; end; end; WhichPlane:=0; for i:=1 to 2 do begin if MaxT.RawComponents[WhichPlane]<MaxT.RawComponents[i] then begin WhichPlane:=i; end; end; if MaxT.RawComponents[WhichPlane]<0.0 then begin result:=false; end else begin for i:=0 to 2 do begin if WhichPlane<>i then begin HitPoint.RawComponents[i]:=Origin.RawComponents[i]+(MaxT.RawComponents[WhichPlane]*Direction.RawComponents[i]); if (HitPoint.RawComponents[i]<Min.RawComponents[i]) or (HitPoint.RawComponents[i]>Min.RawComponents[i]) then begin result:=false; exit; end; end else begin HitPoint.RawComponents[i]:=CandidatePlane.RawComponents[i]; end; end; result:=true; end; end; end; function TpvAABB.RayIntersection(const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; var InvDirection,a,b:TpvVector3; TimeMin,TimeMax:TpvScalar; begin InvDirection:=TpvVector3.AllAxis/Direction; a:=(Min-Origin)*InvDirection; b:=(Max-Origin)*InvDirection; TimeMin:=Math.Max(Math.Max(Math.Min(a.x,b.x),Math.Min(a.y,b.y)),Math.Min(a.z,b.z)); TimeMax:=Math.Min(Math.Min(Math.Max(a.x,b.x),Math.Max(a.y,b.y)),Math.Max(a.z,b.z)); if (TimeMax<0.0) or (TimeMin>TimeMax) then begin Time:=TimeMax; result:=false; end else begin if TimeMin<0.0 then begin Time:=TimeMax; end else begin Time:=TimeMin; end; result:=true; end; end; class function TpvAABB.RayIntersection(const aAABBMin,aAABBMax:TpvVector3;const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; var InvDirection,a,b:TpvVector3; TimeMin,TimeMax:TpvScalar; begin InvDirection:=TpvVector3.AllAxis/Direction; a:=(aAABBMin-Origin)*InvDirection; b:=(aAABBMax-Origin)*InvDirection; TimeMin:=Math.Max(Math.Max(Math.Min(a.x,b.x),Math.Min(a.y,b.y)),Math.Min(a.z,b.z)); TimeMax:=Math.Min(Math.Min(Math.Max(a.x,b.x),Math.Max(a.y,b.y)),Math.Max(a.z,b.z)); if (TimeMax<0.0) or (TimeMin>TimeMax) then begin Time:=TimeMax; result:=false; end else begin if TimeMin<0.0 then begin Time:=TimeMax; end else begin Time:=TimeMin; end; result:=true; end; end; function TpvAABB.LineIntersection(const StartPoint,EndPoint:TpvVector3):boolean; var Direction,InvDirection,a,b:TpvVector3; Len,TimeMin,TimeMax:TpvScalar; begin if Contains(StartPoint) or Contains(EndPoint) then begin result:=true; end else begin Direction:=EndPoint-StartPoint; Len:=Direction.Length; if Len<>0.0 then begin Direction:=Direction/Len; end; InvDirection:=TpvVector3.AllAxis/Direction; a:=((Min-TpvVector3.InlineableCreate(EPSILON,EPSILON,EPSILON))-StartPoint)*InvDirection; b:=((Max+TpvVector3.InlineableCreate(EPSILON,EPSILON,EPSILON))-StartPoint)*InvDirection; TimeMin:=Math.Max(Math.Max(Math.Min(a.x,a.y),Math.Min(a.z,b.x)),Math.Min(b.y,b.z)); TimeMax:=Math.Min(Math.Min(Math.Max(a.x,a.y),Math.Max(a.z,b.x)),Math.Max(b.y,b.z)); result:=((TimeMin<=TimeMax) and (TimeMax>=0.0)) and (TimeMin<=(Len+EPSILON)); end; end; class function TpvAABB.LineIntersection(const aAABBMin,aAABBMax:TpvVector3;const StartPoint,EndPoint:TpvVector3):boolean; var Direction,InvDirection,a,b:TpvVector3; Len,TimeMin,TimeMax:TpvScalar; begin if TpvAABB.Contains(aAABBMin,aAABBMax,StartPoint) or TpvAABB.Contains(aAABBMin,aAABBMax,EndPoint) then begin result:=true; end else begin Direction:=EndPoint-StartPoint; Len:=Direction.Length; if Len<>0.0 then begin Direction:=Direction/Len; end; InvDirection:=TpvVector3.AllAxis/Direction; a:=((aAABBMin-TpvVector3.InlineableCreate(EPSILON,EPSILON,EPSILON))-StartPoint)*InvDirection; b:=((aAABBMax+TpvVector3.InlineableCreate(EPSILON,EPSILON,EPSILON))-StartPoint)*InvDirection; TimeMin:=Math.Max(Math.Max(Math.Min(a.x,a.y),Math.Min(a.z,b.x)),Math.Min(b.y,b.z)); TimeMax:=Math.Min(Math.Min(Math.Max(a.x,a.y),Math.Max(a.z,b.x)),Math.Max(b.y,b.z)); result:=((TimeMin<=TimeMax) and (TimeMax>=0.0)) and (TimeMin<=(Len+EPSILON)); end; end; function TpvAABB.TriangleIntersection(const Triangle:TpvTriangle):boolean; function FindMin(const a,b,c:TpvScalar):TpvScalar; //{$ifdef CAN_INLINE}inline;{$endif} begin result:=a; if result>b then begin result:=b; end; if result>c then begin result:=c; end; end; function FindMax(const a,b,c:TpvScalar):TpvScalar; //{$ifdef CAN_INLINE}inline;{$endif} begin result:=a; if result<b then begin result:=b; end; if result<c then begin result:=c; end; end; function PlaneBoxOverlap(const Normal:TpvVector3;d:TpvFloat;MaxBox:TpvVector3):boolean; //{$ifdef CAN_INLINE}inline;{$endif} var vmin,vmax:TpvVector3; begin if Normal.x>0 then begin vmin.x:=-MaxBox.x; vmax.x:=MaxBox.x; end else begin vmin.x:=MaxBox.x; vmax.x:=-MaxBox.x; end; if Normal.y>0 then begin vmin.y:=-MaxBox.y; vmax.y:=MaxBox.y; end else begin vmin.y:=MaxBox.y; vmax.y:=-MaxBox.y; end; if Normal.z>0 then begin vmin.z:=-MaxBox.z; vmax.z:=MaxBox.z; end else begin vmin.z:=MaxBox.z; vmax.z:=-MaxBox.z; end; if (Normal.Dot(vmin)+d)>0 then begin result:=false; end else if (Normal.Dot(vmax)+d)>=0 then begin result:=true; end else begin result:=false; end; end; var BoxCenter,BoxHalfSize,Normal,v0,v1,v2,e0,e1,e2:TpvVector3; fex,fey,fez,Distance,r:TpvFloat; function AxisTestX01(a,b,fa,fb:TpvFloat):boolean; var p0,p2,pmin,pmax,Radius:TpvFloat; begin p0:=(a*v0.y)-(b*v0.z); p2:=(a*v2.y)-(b*v2.z); if p0<p2 then begin pmin:=p0; pmax:=p2; end else begin pmin:=p2; pmax:=p0; end; Radius:=(fa*BoxHalfSize.y)+(fb*BoxHalfSize.z); result:=not ((pmin>Radius) or (pmax<(-radius))); end; function AxisTestX2(a,b,fa,fb:TpvFloat):boolean; var p0,p1,pmin,pmax,Radius:TpvFloat; begin p0:=(a*v0.y)-(b*v0.z); p1:=(a*v1.y)-(b*v1.z); if p0<p1 then begin pmin:=p0; pmax:=p1; end else begin pmin:=p1; pmax:=p0; end; Radius:=(fa*BoxHalfSize.y)+(fb*BoxHalfSize.z); result:=not ((pmin>Radius) or (pmax<(-radius))); end; function AxisTestY02(a,b,fa,fb:TpvFloat):boolean; var p0,p2,pmin,pmax,Radius:TpvFloat; begin p0:=(-(a*v0.x))+(b*v0.z); p2:=(-(a*v2.x))+(b*v2.z); if p0<p2 then begin pmin:=p0; pmax:=p2; end else begin pmin:=p2; pmax:=p0; end; Radius:=(fa*BoxHalfSize.x)+(fb*BoxHalfSize.z); result:=not ((pmin>Radius) or (pmax<(-radius))); end; function AxisTestY1(a,b,fa,fb:TpvFloat):boolean; var p0,p1,pmin,pmax,Radius:TpvFloat; begin p0:=(-(a*v0.x))+(b*v0.z); p1:=(-(a*v1.x))+(b*v1.z); if p0<p1 then begin pmin:=p0; pmax:=p1; end else begin pmin:=p1; pmax:=p0; end; Radius:=(fa*BoxHalfSize.x)+(fb*BoxHalfSize.z); result:=not ((pmin>Radius) or (pmax<(-radius))); end; function AxisTestZ12(a,b,fa,fb:TpvFloat):boolean; var p1,p2,pmin,pmax,Radius:TpvFloat; begin p1:=(a*v1.x)-(b*v1.y); p2:=(a*v2.x)-(b*v2.y); if p2<p1 then begin pmin:=p2; pmax:=p1; end else begin pmin:=p1; pmax:=p2; end; Radius:=(fa*BoxHalfSize.x)+(fb*BoxHalfSize.y); result:=not ((pmin>Radius) or (pmax<(-radius))); end; function AxisTestZ0(a,b,fa,fb:TpvFloat):boolean; var p0,p1,pmin,pmax,Radius:TpvFloat; begin p0:=(a*v0.x)-(b*v0.y); p1:=(a*v1.x)-(b*v1.y); if p0<p1 then begin pmin:=p0; pmax:=p1; end else begin pmin:=p1; pmax:=p0; end; Radius:=(fa*BoxHalfSize.x)+(fb*BoxHalfSize.y); result:=not ((pmin>Radius) or (pmax<(-radius))); end; procedure FindMinMax(const a,b,c:TpvFloat;var omin,omax:TpvFloat); begin omin:=a; if omin>b then begin omin:=b; end; if omin>c then begin omin:=c; end; omax:=a; if omax<b then begin omax:=b; end; if omax<c then begin omax:=c; end; end; begin BoxCenter:=(Min+Max)*0.5; BoxHalfSize:=(Max-Min)*0.5; v0:=Triangle.Points[0]-BoxCenter; v1:=Triangle.Points[1]-BoxCenter; v2:=Triangle.Points[2]-BoxCenter; e0:=v1-v0; e1:=v2-v1; e2:=v0-v2; fex:=abs(e0.x); fey:=abs(e0.y); fez:=abs(e0.z); if (not AxisTestX01(e0.z,e0.y,fez,fey)) or (not AxisTestY02(e0.z,e0.x,fez,fex)) or (not AxisTestZ12(e0.y,e0.x,fey,fex)) then begin result:=false; exit; end; fex:=abs(e1.x); fey:=abs(e1.y); fez:=abs(e1.z); if (not AxisTestX01(e1.z,e1.y,fez,fey)) or (not AxisTestY02(e1.z,e1.x,fez,fex)) or (not AxisTestZ0(e1.y,e1.x,fey,fex)) then begin result:=false; exit; end; fex:=abs(e2.x); fey:=abs(e2.y); fez:=abs(e2.z); if (not AxisTestX2(e2.z,e2.y,fez,fey)) or (not AxisTestY1(e2.z,e2.x,fez,fex)) or (not AxisTestZ12(e2.y,e2.x,fey,fex)) then begin result:=false; exit; end; if ((FindMin(v0.x,v1.x,v2.x)>BoxHalfSize.x) or (FindMax(v0.x,v1.x,v2.x)<(-BoxHalfSize.x))) or ((FindMin(v0.y,v1.y,v2.y)>BoxHalfSize.y) or (FindMax(v0.y,v1.y,v2.y)<(-BoxHalfSize.y))) or ((FindMin(v0.z,v1.z,v2.z)>BoxHalfSize.z) or (FindMax(v0.z,v1.z,v2.z)<(-BoxHalfSize.z))) then begin result:=false; exit; end; Normal:=e0.Cross(e1); Distance:=abs(Normal.Dot(v0)); r:=(BoxHalfSize.x*abs(Normal.x))+(BoxHalfSize.y*abs(Normal.y))+(BoxHalfSize.z*abs(Normal.z)); result:=Distance<=r;//PlaneBoxOverlap(Normal,-Normal.Dot(v0),BoxHalfSize); end; function TpvAABB.Transform(const Transform:TpvMatrix3x3):TpvAABB; var i,j:TpvInt32; a,b:TpvScalar; begin result.Min.x:=0.0; result.Min.y:=0.0; result.Min.z:=0.0; result.Max.x:=0.0; result.Max.y:=0.0; result.Max.z:=0.0; for i:=0 to 2 do begin for j:=0 to 2 do begin a:=Transform[j,i]*Min.RawComponents[j]; b:=Transform[j,i]*Max.RawComponents[j]; if a<b then begin result.Min.RawComponents[i]:=result.Min.RawComponents[i]+a; result.Max.RawComponents[i]:=result.Max.RawComponents[i]+b; end else begin result.Min.RawComponents[i]:=result.Min.RawComponents[i]+b; result.Max.RawComponents[i]:=result.Max.RawComponents[i]+a; end; end; end; end; function TpvAABB.Transform(const Transform:TpvMatrix4x4):TpvAABB; var i,j:TpvInt32; a,b:TpvScalar; begin result.Min.x:=Transform[3,0]; result.Min.y:=Transform[3,1]; result.Min.z:=Transform[3,2]; result.Max:=result.Min; for i:=0 to 2 do begin for j:=0 to 2 do begin a:=Transform[j,i]*Min.RawComponents[j]; b:=Transform[j,i]*Max.RawComponents[j]; if a<b then begin result.Min.RawComponents[i]:=result.Min.RawComponents[i]+a; result.Max.RawComponents[i]:=result.Max.RawComponents[i]+b; end else begin result.Min.RawComponents[i]:=result.Min.RawComponents[i]+b; result.Max.RawComponents[i]:=result.Max.RawComponents[i]+a; end; end; end; end; function TpvAABB.MatrixMul(const Transform:TpvMatrix3x3):TpvAABB; var Rotation:TpvMatrix3x3; v:array[0..7] of TpvVector3; Center,MinVector,MaxVector:TpvVector3; i:TpvInt32; begin Center:=(Min+Max)*0.5; MinVector:=Min-Center; MaxVector:=Max-Center; v[0]:=Transform*TpvVector3.Create(MinVector.x,MinVector.y,MinVector.z); v[1]:=Transform*TpvVector3.Create(MaxVector.x,MinVector.y,MinVector.z); v[2]:=Transform*TpvVector3.Create(MaxVector.x,MaxVector.y,MinVector.z); v[3]:=Transform*TpvVector3.Create(MaxVector.x,MaxVector.y,MaxVector.z); v[4]:=Transform*TpvVector3.Create(MinVector.x,MaxVector.y,MaxVector.z); v[5]:=Transform*TpvVector3.Create(MinVector.x,MinVector.y,MaxVector.z); v[6]:=Transform*TpvVector3.Create(MaxVector.x,MinVector.y,MaxVector.z); v[7]:=Transform*TpvVector3.Create(MinVector.x,MaxVector.y,MinVector.z); result.Min:=v[0]; result.Max:=v[0]; for i:=0 to 7 do begin if result.Min.x>v[i].x then begin result.Min.x:=v[i].x; end; if result.Min.y>v[i].y then begin result.Min.y:=v[i].y; end; if result.Min.z>v[i].z then begin result.Min.z:=v[i].z; end; if result.Max.x<v[i].x then begin result.Max.x:=v[i].x; end; if result.Max.y<v[i].y then begin result.Max.y:=v[i].y; end; if result.Max.z<v[i].z then begin result.Max.z:=v[i].z; end; end; result.Min:=result.Min+Center; result.Max:=result.Max+Center; end; function TpvAABB.MatrixMul(const Transform:TpvMatrix4x4):TpvAABB; var Rotation:TpvMatrix4x4; v:array[0..7] of TpvVector3; Center,NewCenter,MinVector,MaxVector:TpvVector3; i:TpvInt32; begin Rotation:=TpvMatrix4x4.CreateRotation(Transform); Center:=(Min+Max)*0.5; MinVector:=Min-Center; MaxVector:=Max-Center; NewCenter:=Center+(Transform*TpvVector3.Origin); v[0]:=Rotation*TpvVector3.Create(MinVector.x,MinVector.y,MinVector.z); v[1]:=Rotation*TpvVector3.Create(MaxVector.x,MinVector.y,MinVector.z); v[2]:=Rotation*TpvVector3.Create(MaxVector.x,MaxVector.y,MinVector.z); v[3]:=Rotation*TpvVector3.Create(MaxVector.x,MaxVector.y,MaxVector.z); v[4]:=Rotation*TpvVector3.Create(MinVector.x,MaxVector.y,MaxVector.z); v[5]:=Rotation*TpvVector3.Create(MinVector.x,MinVector.y,MaxVector.z); v[6]:=Rotation*TpvVector3.Create(MaxVector.x,MinVector.y,MaxVector.z); v[7]:=Rotation*TpvVector3.Create(MinVector.x,MaxVector.y,MinVector.z); result.Min:=v[0]; result.Max:=v[0]; for i:=0 to 7 do begin if result.Min.x>v[i].x then begin result.Min.x:=v[i].x; end; if result.Min.y>v[i].y then begin result.Min.y:=v[i].y; end; if result.Min.z>v[i].z then begin result.Min.z:=v[i].z; end; if result.Max.x<v[i].x then begin result.Max.x:=v[i].x; end; if result.Max.y<v[i].y then begin result.Max.y:=v[i].y; end; if result.Max.z<v[i].z then begin result.Max.z:=v[i].z; end; end; result.Min:=result.Min+NewCenter; result.Max:=result.Max+NewCenter; end; function TpvAABB.ScissorRect(out Scissor:TpvClipRect;const mvp:TpvMatrix4x4;const vp:TpvClipRect;zcull:boolean):boolean; var p:TpvVector4; i,x,y,z_far,z_near:TpvInt32; begin z_near:=0; z_far:=0; for i:=0 to 7 do begin // Get bound edge point p.x:=MinMax[i and 1].x; p.y:=MinMax[(i shr 1) and 1].y; p.z:=MinMax[(i shr 2) and 1].z; p.w:=1.0; // Project p:=mvp*p; p.x:=p.x/p.w; p.y:=p.y/p.w; p.z:=p.z/p.w; // Convert to screen space p.x:=vp[0]+(vp[2]*((p.x+1.0)*0.5)); p.y:=vp[1]+(vp[3]*((p.y+1.0)*0.5)); p.z:=(p.z+1.0)*0.5; if zcull then begin if p.z<-EPSILON then begin inc(z_far); end else if p.z>(1.0+EPSILON) then begin inc(z_near); end; end; // Round to integer values x:=round(p.x); y:=round(p.y); // Clip if x<vp[0] then begin x:=vp[0]; end; if x>(vp[0]+vp[2]) then begin x:=vp[0]+vp[2]; end; if y<vp[1] then begin y:=vp[1]; end; if y>(vp[1]+vp[3]) then begin y:=vp[1]+vp[3]; end; // Extend if i=0 then begin Scissor[0]:=x; Scissor[1]:=y; Scissor[2]:=x; Scissor[3]:=y; end else begin if x<Scissor[0] then begin Scissor[0]:=x; end; if y<Scissor[1] then begin Scissor[1]:=y; end; if x>Scissor[2] then begin Scissor[2]:=x; end; if y>Scissor[3] then begin Scissor[3]:=y; end; end; end; if (z_far=8) or (z_near=8) then begin result:=false; end else if (z_near>0) and (z_near<8) then begin result:=true; Scissor[0]:=vp[0]; Scissor[1]:=vp[1]; Scissor[2]:=vp[0]+vp[2]; Scissor[3]:=vp[1]+vp[3]; end else begin result:=true; end; end; function TpvAABB.ScissorRect(out Scissor:TpvFloatClipRect;const mvp:TpvMatrix4x4;const vp:TpvFloatClipRect;zcull:boolean):boolean; var p:TpvVector4; i,z_far,z_near:TpvInt32; begin z_near:=0; z_far:=0; for i:=0 to 7 do begin // Get bound edge point p.x:=MinMax[i and 1].x; p.y:=MinMax[(i shr 1) and 1].y; p.z:=MinMax[(i shr 2) and 1].z; p.w:=1.0; // Project p:=mvp*p; p.x:=p.x/p.w; p.y:=p.y/p.w; p.z:=p.z/p.w; // Convert to screen space p.x:=vp[0]+(vp[2]*((p.x+1.0)*0.5)); p.y:=vp[1]+(vp[3]*((p.y+1.0)*0.5)); p.z:=(p.z+1.0)*0.5; if zcull then begin if p.z<-EPSILON then begin inc(z_far); end else if p.z>(1.0+EPSILON) then begin inc(z_near); end; end; // Clip if p.x<vp[0] then begin p.x:=vp[0]; end; if p.x>(vp[0]+vp[2]) then begin p.x:=vp[0]+vp[2]; end; if p.y<vp[1] then begin p.y:=vp[1]; end; if p.y>(vp[1]+vp[3]) then begin p.y:=vp[1]+vp[3]; end; // Extend if i=0 then begin Scissor[0]:=p.x; Scissor[1]:=p.y; Scissor[2]:=p.x; Scissor[3]:=p.y; end else begin if p.x<Scissor[0] then begin Scissor[0]:=p.x; end; if p.y<Scissor[1] then begin Scissor[1]:=p.y; end; if p.x>Scissor[2] then begin Scissor[2]:=p.x; end; if p.y>Scissor[3] then begin Scissor[3]:=p.y; end; end; end; if (z_far=8) or (z_near=8) then begin result:=false; end else if (z_near>0) and (z_near<8) then begin result:=true; Scissor[0]:=vp[0]; Scissor[1]:=vp[1]; Scissor[2]:=vp[0]+vp[2]; Scissor[3]:=vp[1]+vp[3]; end else begin result:=true; end; end; function TpvAABB.MovingTest(const aAABBTo,bAABBFrom,bAABBTo:TpvAABB;var t:TpvScalar):boolean; var Axis,AxisSamples,Samples,Sample,FirstSample:TpvInt32; aAABB,bAABB:TpvAABB; f{,MinRadius},Size,Distance,BestDistance:TpvScalar; HasDistance:boolean; begin if Intersect(bAABBFrom) then begin t:=0.0; result:=true; end else begin result:=false; if Combine(aAABBTo).Intersect(bAABBFrom.Combine(bAABBTo)) then begin FirstSample:=0; Samples:=1; for Axis:=0 to 2 do begin if Min.RawComponents[Axis]>aAABBTo.Max.RawComponents[Axis] then begin Distance:=Min.RawComponents[Axis]-aAABBTo.Max.RawComponents[Axis]; end else if aAABBTo.Min.RawComponents[Axis]>Max.RawComponents[Axis] then begin Distance:=aAABBTo.Min.RawComponents[Axis]-Max.RawComponents[Axis]; end else begin Distance:=0; end; Size:=Math.Min(abs(Max.RawComponents[Axis]-Min.RawComponents[Axis]),abs(aAABBTo.Max.RawComponents[Axis]-aAABBTo.Min.RawComponents[Axis])); if Size>0.0 then begin AxisSamples:=round((Distance+Size)/Size); if Samples<AxisSamples then begin Samples:=AxisSamples; end; end; if bAABBFrom.Min.RawComponents[Axis]>bAABBTo.Max.RawComponents[Axis] then begin Distance:=bAABBFrom.Min.RawComponents[Axis]-bAABBTo.Max.RawComponents[Axis]; end else if bAABBTo.Min.RawComponents[Axis]>bAABBFrom.Max.RawComponents[Axis] then begin Distance:=bAABBTo.Min.RawComponents[Axis]-bAABBFrom.Max.RawComponents[Axis]; end else begin Distance:=0; end; Size:=Math.Min(abs(bAABBFrom.Max.RawComponents[Axis]-bAABBFrom.Min.RawComponents[Axis]),abs(bAABBTo.Max.RawComponents[Axis]-bAABBTo.Min.RawComponents[Axis])); if Size>0.0 then begin AxisSamples:=round((Distance+Size)/Size); if Samples<AxisSamples then begin Samples:=AxisSamples; end; end; end; BestDistance:=1e+18; HasDistance:=false; for Sample:=FirstSample to Samples do begin f:=Sample/Samples; aAABB.Min:=Min.Lerp(aAABBTo.Min,f); aAABB.Max:=Max.Lerp(aAABBTo.Max,f); bAABB.Min:=bAABBFrom.Min.Lerp(bAABBTo.Min,f); bAABB.Max:=bAABBFrom.Max.Lerp(bAABBTo.Max,f); if aAABB.Intersect(bAABB) then begin t:=f; result:=true; break; end else begin Distance:=aAABB.DistanceTo(bAABB); if (not HasDistance) and (Distance<BestDistance) then begin BestDistance:=Distance; HasDistance:=true; end else begin break; end; end; end; end; end; end; function TpvAABB.SweepTest(const bAABB:TpvAABB;const aV,bV:TpvVector3;var FirstTime,LastTime:TpvScalar):boolean; var Axis:TpvInt32; v,tMin,tMax:TpvVector3; begin if Intersect(bAABB) then begin FirstTime:=0.0; LastTime:=0.0; result:=true; end else begin v:=bV-aV; for Axis:=0 to 2 do begin if v.RawComponents[Axis]<0.0 then begin tMin.RawComponents[Axis]:=(Max.RawComponents[Axis]-bAABB.Min.RawComponents[Axis])/v.RawComponents[Axis]; tMax.RawComponents[Axis]:=(Min.RawComponents[Axis]-bAABB.Max.RawComponents[Axis])/v.RawComponents[Axis]; end else if v.RawComponents[Axis]>0.0 then begin tMin.RawComponents[Axis]:=(Min.RawComponents[Axis]-bAABB.Max.RawComponents[Axis])/v.RawComponents[Axis]; tMax.RawComponents[Axis]:=(Max.RawComponents[Axis]-bAABB.Min.RawComponents[Axis])/v.RawComponents[Axis]; end else if (Max.RawComponents[Axis]>=bAABB.Min.RawComponents[Axis]) and (Min.RawComponents[Axis]<=bAABB.Max.RawComponents[Axis]) then begin tMin.RawComponents[Axis]:=0.0; tMax.RawComponents[Axis]:=1.0; end else begin result:=false; exit; end; end; FirstTime:=Math.Max(Math.Max(tMin.x,tMin.y),tMin.z); LastTime:=Math.Min(Math.Min(tMax.x,tMax.y),tMax.z); result:=(LastTime>=0.0) and (FirstTime<=1.0) and (FirstTime<=LastTime); end; end; constructor TpvSphere.Create(const pCenter:TpvVector3;const pRadius:TpvScalar); begin Center:=pCenter; Radius:=pRadius; end; constructor TpvSphere.CreateFromAABB(const ppvAABB:TpvAABB); begin Center:=(ppvAABB.Min+ppvAABB.Max)*0.5; Radius:=ppvAABB.Min.DistanceTo(ppvAABB.Max)*0.5; end; constructor TpvSphere.CreateFromFrustum(const zNear,zFar,FOV,AspectRatio:TpvScalar;const Position,Direction:TpvVector3); var ViewLen,Width,Height:TpvScalar; begin ViewLen:=zFar-zNear; Height:=ViewLen*tan((FOV*0.5)*DEG2RAD); Width:=Height*AspectRatio; Radius:=TpvVector3.Create(Width,Height,ViewLen).DistanceTo(TpvVector3.Create(0.0,0.0,zNear+(ViewLen*0.5))); Center:=Position+(Direction*((ViewLen*0.5)+zNear)); end; function TpvSphere.ToAABB(const pScale:TpvScalar=1.0):TpvAABB; begin result.Min.x:=Center.x-(Radius*pScale); result.Min.y:=Center.y-(Radius*pScale); result.Min.z:=Center.z-(Radius*pScale); result.Max.x:=Center.x+(Radius*pScale); result.Max.y:=Center.y+(Radius*pScale); result.Max.z:=Center.z+(Radius*pScale); end; function TpvSphere.Cull(const p:array of TpvPlane):boolean; var i:TpvInt32; begin result:=true; for i:=0 to length(p)-1 do begin if p[i].DistanceTo(Center)<-Radius then begin result:=false; exit; end; end; end; function TpvSphere.Contains(const b:TpvSphere):boolean; begin result:=((Radius+EPSILON)>=(b.Radius-EPSILON)) and ((Center-b.Center).Length<=((Radius+EPSILON)-(b.Radius-EPSILON))); end; function TpvSphere.Contains(const v:TpvVector3):boolean; begin result:=Center.DistanceTo(v)<(Radius+EPSILON); end; function TpvSphere.DistanceTo(const b:TpvSphere):TpvScalar; begin result:=Max((Center-b.Center).Length-(Radius+b.Radius),0.0); end; function TpvSphere.DistanceTo(const b:TpvVector3):TpvScalar; begin result:=Max(Center.DistanceTo(b)-Radius,0.0); end; function TpvSphere.Intersect(const b:TpvSphere):boolean; begin result:=(Center-b.Center).Length<=(Radius+b.Radius+(EPSILON*2.0)); end; function TpvSphere.Intersect(const b:TpvAABB):boolean; var c:TpvVector3; begin c.x:=Min(Max(Center.x,b.Min.x),b.Max.x); c.y:=Min(Max(Center.y,b.Min.y),b.Max.y); c.z:=Min(Max(Center.z,b.Min.z),b.Max.z); result:=(c-Center).SquaredLength<sqr(Radius); end; function TpvSphere.FastRayIntersection(const Origin,Direction:TpvVector3):boolean; var m:TpvVector3; p,d:TpvScalar; begin m:=Origin-Center; p:=-m.Dot(Direction); d:=(sqr(p)-m.SquaredLength)+sqr(Radius); result:=(d>0.0) and ((p+sqrt(d))>0.0); end; function TpvSphere.RayIntersection(const Origin,Direction:TpvVector3;out Time:TpvScalar):boolean; var SphereCenterToRayOrigin:TpvVector3; a,b,c,t1,t2:TpvScalar; begin result:=false; SphereCenterToRayOrigin:=Origin-Center; a:=Direction.SquaredLength; b:=2.0*SphereCenterToRayOrigin.Dot(Direction); c:=SphereCenterToRayOrigin.SquaredLength-sqr(Radius); if SolveQuadraticRoots(a,b,c,t1,t2) then begin if t1<0.0 then begin if t2<0.0 then begin // sphere is behind, abort exit; end else begin // inside sphere Time:=t2; result:=true; end; end else begin if t2<0.0 then begin // inside sphere Time:=t1; end else begin // sphere is ahead, return the nearest value if t1<t2 then begin Time:=t1; end else begin Time:=t2; end; end; result:=true; end; end; end; function TpvSphere.Extends(const WithSphere:TpvSphere):TpvSphere; var x0,y0,z0,r0,x1,y1,z1,r1,xn,yn,zn,dn,t:TpvScalar; begin x0:=Center.x; y0:=Center.y; z0:=Center.z; r0:=Radius; x1:=WithSphere.Center.x; y1:=WithSphere.Center.y; z1:=WithSphere.Center.z; r1:=WithSphere.Radius; xn:=x1-x0; yn:=y1-y0; zn:=z1-z0; dn:=sqrt(sqr(xn)+sqr(yn)+sqr(zn)); if abs(dn)<EPSILON then begin result:=self; exit; end; if (dn+r1)<r0 then begin result:=self; exit; end; result.Radius:=(dn+r0+r1)*0.5; t:=(result.Radius-r0)/dn; result.Center.x:=x0+(xn*t); result.Center.y:=y0+(xn*t); result.Center.z:=z0+(xn*t); end; function TpvSphere.Transform(const Transform:TpvMatrix4x4):TpvSphere; begin result.Center:=Transform*Center; result.Radius:=result.Center.DistanceTo(Transform*TpvVector3.Create(Center.x,Center.y+Radius,Center.z)); end; function TpvSphere.TriangleIntersection(const Triangle:TpvTriangle;out Position,Normal:TpvVector3;out Depth:TpvScalar):boolean; var SegmentTriangle:TpvSegmentTriangle; Dist,d2,s,t:TpvScalar; begin result:=false; if ((Triangle.Normal.Dot(Center)-Triangle.Normal.Dot(Triangle.Points[0]))-Radius)<EPSILON then begin SegmentTriangle.Origin:=Triangle.Points[0]; SegmentTriangle.Edge0:=Triangle.Points[1]-Triangle.Points[0]; SegmentTriangle.Edge1:=Triangle.Points[2]-Triangle.Points[0]; SegmentTriangle.Edge2:=SegmentTriangle.Edge1-SegmentTriangle.Edge0; d2:=SegmentTriangle.SquaredPointTriangleDistance(Center,s,t); if d2<sqr(Radius) then begin Dist:=sqrt(d2); Depth:=Radius-Dist; if Dist>EPSILON then begin Normal:=((Center-(SegmentTriangle.Origin+((SegmentTriangle.Edge0*s)+(SegmentTriangle.Edge1*t))))).Normalize; end else begin Normal:=Triangle.Normal; end; Position:=Center-(Normal*Radius); result:=true; end; end; end; function TpvSphere.TriangleIntersection(const SegmentTriangle:TpvSegmentTriangle;const TriangleNormal:TpvVector3;out Position,Normal:TpvVector3;out Depth:TpvScalar):boolean; var Dist,d2,s,t:TpvScalar; begin result:=false; d2:=SegmentTriangle.SquaredPointTriangleDistance(Center,s,t); if d2<sqr(Radius) then begin Dist:=sqrt(d2); Depth:=Radius-Dist; if Dist>EPSILON then begin Normal:=((Center-(SegmentTriangle.Origin+((SegmentTriangle.Edge0*s)+(SegmentTriangle.Edge1*t))))).Normalize; end else begin Normal:=TriangleNormal; end; Position:=Center-(Normal*Radius); result:=true; end; end; function TpvSphere.SweptIntersection(const SphereB:TpvSphere;const VelocityA,VelocityB:TpvVector3;out TimeFirst,TimeLast:TpvScalar):boolean; var ab,vab:TpvVector3; rab,a,b,c:TpvScalar; begin result:=false; ab:=SphereB.Center-Center; vab:=VelocityB-VelocityA; rab:=Radius+SphereB.Radius; c:=ab.SquaredLength-sqr(rab); if c<=0.0 then begin TimeFirst:=0.0; TimeLast:=0.0; result:=true; end else begin a:=vab.SquaredLength; b:=2.0*vab.Dot(ab); if SolveQuadraticRoots(a,b,c,TimeFirst,TimeLast) then begin if TimeFirst>TimeLast then begin a:=TimeFirst; TimeFirst:=TimeLast; TimeLast:=a; end; result:=(TimeLast>=0.0) and (TimeFirst<=1.0); end; end; end; constructor TpvSphereCoords.CreateFromCartesianVector(const v:TpvVector3); begin Radius:=v.Length; Theta:=ArcCos(v.z/Radius); Phi:=Sign(v.y)*ArcCos(v.x/sqrt(v.x*v.x+v.y*v.y)); end; constructor TpvSphereCoords.CreateFromCartesianVector(const v:TpvVector4); begin Radius:=v.Length; Theta:=ArcCos(v.z/Radius); Phi:=Sign(v.y)*ArcCos(v.x/sqrt(v.x*v.x+v.y*v.y)); end; function TpvSphereCoords.ToCartesianVector:TpvVector3; begin result.x:=Radius*sin(Theta)*cos(Phi); result.y:=Radius*sin(Theta)*sin(Phi); result.z:=Radius*cos(Theta); end; constructor TpvRect.CreateFromVkRect2D(const aFrom:TVkRect2D); begin Left:=aFrom.offset.x; Top:=aFrom.offset.y; Right:=aFrom.offset.x+aFrom.extent.width; Bottom:=aFrom.offset.y+aFrom.extent.height; end; constructor TpvRect.CreateAbsolute(const aLeft,aTop,aRight,aBottom:TpvFloat); begin Left:=aLeft; Top:=aTop; Right:=aRight; Bottom:=aBottom; end; constructor TpvRect.CreateAbsolute(const aLeftTop,aRightBottom:TpvVector2); begin LeftTop:=aLeftTop; RightBottom:=aRightBottom; end; constructor TpvRect.CreateRelative(const aLeft,aTop,aWidth,aHeight:TpvFloat); begin Left:=aLeft; Top:=aTop; Right:=aLeft+aWidth; Bottom:=aTop+aHeight; end; constructor TpvRect.CreateRelative(const aLeftTop,aSize:TpvVector2); begin LeftTop:=aLeftTop; RightBottom:=aLeftTop+aSize; end; class operator TpvRect.Implicit(const a:TVkRect2D):TpvRect; begin result:=TpvRect.CreateFromVkRect2D(a); end; class operator TpvRect.Explicit(const a:TVkRect2D):TpvRect; begin result:=TpvRect.CreateFromVkRect2D(a); end; class operator TpvRect.Implicit(const a:TpvRect):TVkRect2D; begin result:=a.ToVkRect2D; end; class operator TpvRect.Explicit(const a:TpvRect):TVkRect2D; begin result:=a.ToVkRect2D; end; class operator TpvRect.Equal(const a,b:TpvRect):boolean; begin result:=a.Vector4=b.Vector4; end; class operator TpvRect.NotEqual(const a,b:TpvRect):boolean; begin result:=a.Vector4<>b.Vector4; end; function TpvRect.Cost:TpvScalar; begin result:=(Max.x-Min.x)+(Max.y-Min.y); // Manhattan distance end; function TpvRect.Area:TpvScalar; begin result:=abs(Max.x-Min.x)*abs(Max.y-Min.y); end; function TpvRect.Center:TpvVector2; begin result.x:=(Min.x*0.5)+(Max.x*0.5); result.y:=(Min.y*0.5)+(Max.y*0.5); end; function TpvRect.Combine(const aWithRect:TpvRect):TpvRect; begin result.Min.x:=Math.Min(Min.x,aWithRect.Min.x); result.Min.y:=Math.Min(Min.y,aWithRect.Min.y); result.Max.x:=Math.Max(Max.x,aWithRect.Max.x); result.Max.y:=Math.Max(Max.y,aWithRect.Max.y); end; function TpvRect.Combine(const aWithPoint:TpvVector2):TpvRect; begin result.Min.x:=Math.Min(Min.x,aWithPoint.x); result.Min.y:=Math.Min(Min.y,aWithPoint.y); result.Max.x:=Math.Max(Max.x,aWithPoint.x); result.Max.y:=Math.Max(Max.y,aWithPoint.y); end; function TpvRect.Intersect(const aWithRect:TpvRect;Threshold:TpvScalar=EPSILON):boolean; begin result:=(((Max.x+Threshold)>=(aWithRect.Min.x-Threshold)) and ((Min.x-Threshold)<=(aWithRect.Max.x+Threshold))) and (((Max.y+Threshold)>=(aWithRect.Min.y-Threshold)) and ((Min.y-Threshold)<=(aWithRect.Max.y+Threshold))); end; function TpvRect.Contains(const aWithRect:TpvRect;Threshold:TpvScalar=EPSILON):boolean; begin result:=((Min.x-Threshold)<=(aWithRect.Min.x+Threshold)) and ((Min.y-Threshold)<=(aWithRect.Min.y+Threshold)) and ((Max.x+Threshold)>=(aWithRect.Min.x+Threshold)) and ((Max.y+Threshold)>=(aWithRect.Min.y+Threshold)) and ((Min.x-Threshold)<=(aWithRect.Max.x-Threshold)) and ((Min.y-Threshold)<=(aWithRect.Max.y-Threshold)) and ((Max.x+Threshold)>=(aWithRect.Max.x-Threshold)) and ((Max.y+Threshold)>=(aWithRect.Max.y-Threshold)); end; function TpvRect.GetIntersection(const WithAABB:TpvRect):TpvRect; begin result.Min.x:=Math.Max(Min.x,WithAABB.Min.x); result.Min.y:=Math.Max(Min.y,WithAABB.Min.y); result.Max.x:=Math.Min(Max.x,WithAABB.Max.x); result.Max.y:=Math.Min(Max.y,WithAABB.Max.y); end; function TpvRect.Touched(const aPosition:TpvVector2;Threshold:TpvScalar=EPSILON):boolean; begin result:=((aPosition.x>=(Min.x-Threshold)) and (aPosition.x<=(Max.x+Threshold))) and ((aPosition.y>=(Min.y-Threshold)) and (aPosition.y<=(Max.y+Threshold))); end; function TpvRect.ToVkRect2D:TVkRect2D; begin result.offset.x:=trunc(floor(Left)); result.offset.y:=trunc(floor(Top)); result.extent.width:=trunc(ceil(Right-Left)); result.extent.height:=trunc(ceil(Bottom-Top)); end; function TpvRect.GetWidth:TpvFloat; begin result:=Right-Left; end; procedure TpvRect.SetWidth(const aWidth:TpvFloat); begin Right:=Left+aWidth; end; function TpvRect.GetHeight:TpvFloat; begin result:=Bottom-Top; end; procedure TpvRect.SetHeight(const aHeight:TpvFloat); begin Bottom:=Top+aHeight; end; function TpvRect.GetSize:TpvVector2; begin result:=Max-Min; end; procedure TpvRect.SetSize(const aSize:TpvVector2); begin Max:=Min+aSize; end; function Cross(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Cross(b); end; function Cross(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Cross(b); end; function Cross(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Cross(b); end; function Dot(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a*b; end; function Dot(const a,b:TpvVector2):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Dot(b); end; function Dot(const a,b:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Dot(b); end; function Dot(const a,b:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Dot(b); end; function Distance(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=abs(a-b); end; function Distance(const a,b:TpvVector2):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.DistanceTo(b); end; function Distance(const a,b:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.DistanceTo(b); end; function Distance(const a,b:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.DistanceTo(b); end; function Len(const a:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=abs(a); end; function Len(const a:TpvVector2):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Length; end; function Len(const a:TpvVector3):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Length; end; function Len(const a:TpvVector4):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Length; end; function Normalize(const a:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a; end; function Normalize(const a:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Normalize; end; function Normalize(const a:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Normalize; end; function Normalize(const a:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=a.Normalize; end; function Minimum(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Min(a,b); end; function Minimum(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(a.x,b.x); result.y:=Min(a.y,b.y); end; function Minimum(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(a.x,b.x); result.y:=Min(a.y,b.y); result.z:=Min(a.z,b.z); end; function Minimum(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(a.x,b.x); result.y:=Min(a.y,b.y); result.z:=Min(a.z,b.z); result.w:=Min(a.w,b.w); end; function Maximum(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Max(a,b); end; function Maximum(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Max(a.x,b.x); result.y:=Max(a.y,b.y); end; function Maximum(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Max(a.x,b.x); result.y:=Max(a.y,b.y); result.z:=Max(a.z,b.z); end; function Maximum(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Max(a.x,b.x); result.y:=Max(a.y,b.y); result.z:=Max(a.z,b.z); result.w:=Max(a.w,b.w); end; function Pow(const a,b:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Power(a,b); end; function Pow(const a,b:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Power(a.x,b.x); result.y:=Power(a.y,b.y); end; function Pow(const a,b:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Power(a.x,b.x); result.y:=Power(a.y,b.y); result.z:=Power(a.z,b.z); end; function Pow(const a,b:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Power(a.x,b.x); result.y:=Power(a.y,b.y); result.z:=Power(a.z,b.z); result.w:=Power(a.w,b.w); end; function FaceForward(const N,I:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if (N*I)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if N.Dot(I)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if N.Dot(I)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if N.Dot(I)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I,Nref:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if (I*Nref)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I,Nref:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if I.Dot(Nref)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I,Nref:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if I.Dot(Nref)>0.0 then begin result:=-N; end else begin result:=N; end; end; function FaceForward(const N,I,Nref:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if I.Dot(Nref)>0.0 then begin result:=-N; end else begin result:=N; end; end; function Reflect(const I,N:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=I-((2.0*(N*I))*N); end; function Reflect(const I,N:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=I-((2.0*N.Dot(I))*N); end; function Reflect(const I,N:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=I-((2.0*N.Dot(I))*N); end; function Reflect(const I,N:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=I-((2.0*N.Dot(I))*N); end; function Refract(const I,N:TpvScalar;const Eta:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} var NdotI,k:TpvScalar; begin NdotI:=N*I; k:=1.0-(sqr(Eta)*(1.0-sqr(NdotI))); if k>=0.0 then begin result:=((Eta*I)-((Eta*NdotI)+sqrt(k))*N); end else begin result:=0.0; end; end; function Refract(const I,N:TpvVector2;const Eta:TpvScalar):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} var NdotI,k:TpvScalar; begin NdotI:=N.Dot(I); k:=1.0-(sqr(Eta)*(1.0-sqr(NdotI))); if k>=0.0 then begin result:=((Eta*I)-((Eta*NdotI)+sqrt(k))*N); end else begin result:=0.0; end; end; function Refract(const I,N:TpvVector3;const Eta:TpvScalar):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} var NdotI,k:TpvScalar; begin NdotI:=N.Dot(I); k:=1.0-(sqr(Eta)*(1.0-sqr(NdotI))); if k>=0.0 then begin result:=((Eta*I)-((Eta*NdotI)+sqrt(k))*N); end else begin result:=0.0; end; end; function Refract(const I,N:TpvVector4;const Eta:TpvScalar):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} var NdotI,k:TpvScalar; begin NdotI:=N.Dot(I); k:=1.0-(sqr(Eta)*(1.0-sqr(NdotI))); if k>=0.0 then begin result:=((Eta*I)-((Eta*NdotI)+sqrt(k))*N); end else begin result:=0.0; end; end; function Clamp(const Value,MinValue,MaxValue:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Min(Max(Value,MinValue),MaxValue); end; function Clamp(const Value,MinValue,MaxValue:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(Max(Value.x,MinValue.x),MaxValue.x); result.y:=Min(Max(Value.y,MinValue.y),MaxValue.y); end; function Clamp(const Value,MinValue,MaxValue:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(Max(Value.x,MinValue.x),MaxValue.x); result.y:=Min(Max(Value.y,MinValue.y),MaxValue.y); result.z:=Min(Max(Value.z,MinValue.z),MaxValue.z); end; function Clamp(const Value,MinValue,MaxValue:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Min(Max(Value.x,MinValue.x),MaxValue.x); result.y:=Min(Max(Value.y,MinValue.y),MaxValue.y); result.z:=Min(Max(Value.z,MinValue.z),MaxValue.z); result.w:=Min(Max(Value.w,MinValue.w),MaxValue.w); end; function Mix(const a,b,t:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if t<=0.0 then begin result:=a; end else if t>=1.0 then begin result:=b; end else begin result:=(a*(1.0-t))+(b*t); end; end; function Mix(const a,b,t:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Mix(a.x,b.x,t.x); result.y:=Mix(a.y,b.y,t.y); end; function Mix(const a,b,t:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Mix(a.x,b.x,t.x); result.y:=Mix(a.y,b.y,t.y); result.z:=Mix(a.z,b.z,t.z); end; function Mix(const a,b,t:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Mix(a.x,b.x,t.x); result.y:=Mix(a.y,b.y,t.y); result.z:=Mix(a.z,b.z,t.z); result.w:=Mix(a.w,b.w,t.w); end; function Step(const Edge,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin if Value<Edge then begin result:=0.0; end else begin result:=1.0; end; end; function Step(const Edge,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Step(Edge.x,Value.x); result.y:=Step(Edge.y,Value.y); end; function Step(const Edge,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Step(Edge.x,Value.x); result.y:=Step(Edge.y,Value.y); result.z:=Step(Edge.z,Value.z); end; function Step(const Edge,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=Step(Edge.x,Value.x); result.y:=Step(Edge.y,Value.y); result.z:=Step(Edge.z,Value.z); result.w:=Step(Edge.w,Value.w); end; function NearestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<0.5 then begin result:=0.0; end else begin result:=1.0; end; end; function NearestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=NearestStep(Edge0.x,Edge1.x,Value.x); result.y:=NearestStep(Edge0.y,Edge1.y,Value.y); end; function NearestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=NearestStep(Edge0.x,Edge1.x,Value.x); result.y:=NearestStep(Edge0.y,Edge1.y,Value.y); result.z:=NearestStep(Edge0.z,Edge1.z,Value.z); end; function NearestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=NearestStep(Edge0.x,Edge1.x,Value.x); result.y:=NearestStep(Edge0.y,Edge1.y,Value.y); result.z:=NearestStep(Edge0.z,Edge1.z,Value.z); result.w:=NearestStep(Edge0.w,Edge1.w,Value.w); end; function LinearStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<=0.0 then begin result:=0.0; end else if result>=1.0 then begin result:=1.0; end; end; function LinearStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=LinearStep(Edge0.x,Edge1.x,Value.x); result.y:=LinearStep(Edge0.y,Edge1.y,Value.y); end; function LinearStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=LinearStep(Edge0.x,Edge1.x,Value.x); result.y:=LinearStep(Edge0.y,Edge1.y,Value.y); result.z:=LinearStep(Edge0.z,Edge1.z,Value.z); end; function LinearStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=LinearStep(Edge0.x,Edge1.x,Value.x); result.y:=LinearStep(Edge0.y,Edge1.y,Value.y); result.z:=LinearStep(Edge0.z,Edge1.z,Value.z); result.w:=LinearStep(Edge0.w,Edge1.w,Value.w); end; function SmoothStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<=0.0 then begin result:=0.0; end else if result>=1.0 then begin result:=1.0; end else begin result:=sqr(result)*(3.0-(2.0*result)); end; end; function SmoothStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothStep(Edge0.y,Edge1.y,Value.y); end; function SmoothStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothStep(Edge0.y,Edge1.y,Value.y); result.z:=SmoothStep(Edge0.z,Edge1.z,Value.z); end; function SmoothStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothStep(Edge0.y,Edge1.y,Value.y); result.z:=SmoothStep(Edge0.z,Edge1.z,Value.z); result.w:=SmoothStep(Edge0.w,Edge1.w,Value.w); end; function SmootherStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<=0.0 then begin result:=0.0; end else if result>=1.0 then begin result:=1.0; end else begin result:=(sqr(result)*result)*(result*((result*6.0)-15.0)+10); end; end; function SmootherStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmootherStep(Edge0.x,Edge1.x,Value.x); result.y:=SmootherStep(Edge0.y,Edge1.y,Value.y); end; function SmootherStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmootherStep(Edge0.x,Edge1.x,Value.x); result.y:=SmootherStep(Edge0.y,Edge1.y,Value.y); result.z:=SmootherStep(Edge0.z,Edge1.z,Value.z); end; function SmootherStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmootherStep(Edge0.x,Edge1.x,Value.x); result.y:=SmootherStep(Edge0.y,Edge1.y,Value.y); result.z:=SmootherStep(Edge0.z,Edge1.z,Value.z); result.w:=SmootherStep(Edge0.w,Edge1.w,Value.w); end; function SmoothestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<=0.0 then begin result:=0.0; end else if result>=1.0 then begin result:=1.0; end else begin result:=((((-20.0)*sqr(result)*result)+(70.0*sqr(result)))-(84.0*result)+35.0)*sqr(sqr(result)); end; end; function SmoothestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothestStep(Edge0.y,Edge1.y,Value.y); end; function SmoothestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothestStep(Edge0.y,Edge1.y,Value.y); result.z:=SmoothestStep(Edge0.z,Edge1.z,Value.z); end; function SmoothestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SmoothestStep(Edge0.y,Edge1.y,Value.y); result.z:=SmoothestStep(Edge0.z,Edge1.z,Value.z); result.w:=SmoothestStep(Edge0.w,Edge1.w,Value.w); end; function SuperSmoothestStep(const Edge0,Edge1,Value:TpvScalar):TpvScalar; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Value-Edge0)/(Edge1-Edge0); if result<=0.0 then begin result:=0.0; end else if result>=1.0 then begin result:=1.0; end else begin result:=0.5-(cos((0.5-(cos(result*PI)*0.5))*PI)*0.5); end; end; function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector2):TpvVector2; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SuperSmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SuperSmoothestStep(Edge0.y,Edge1.y,Value.y); end; function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector3):TpvVector3; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SuperSmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SuperSmoothestStep(Edge0.y,Edge1.y,Value.y); result.z:=SuperSmoothestStep(Edge0.z,Edge1.z,Value.z); end; function SuperSmoothestStep(const Edge0,Edge1,Value:TpvVector4):TpvVector4; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result.x:=SuperSmoothestStep(Edge0.x,Edge1.x,Value.x); result.y:=SuperSmoothestStep(Edge0.y,Edge1.y,Value.y); result.z:=SuperSmoothestStep(Edge0.z,Edge1.z,Value.z); result.w:=SuperSmoothestStep(Edge0.w,Edge1.w,Value.w); end; procedure DoCalculateInterval(const Vertices:PpvVector3s;const Count:TpvInt32;const Axis:TpvVector3;out OutMin,OutMax:TpvScalar); var Distance:TpvScalar; Index:TpvInt32; begin Distance:=Vertices^[0].Dot(Axis); OutMin:=Distance; OutMax:=Distance; for Index:=1 to Count-1 do begin Distance:=Vertices^[Index].Dot(Axis); if OutMin>Distance then begin OutMin:=Distance; end; if OutMax<Distance then begin OutMax:=Distance; end; end; end; function DoSpanIntersect(const Vertices1:PpvVector3s;const Count1:TpvInt32;const Vertices2:PpvVector3s;const Count2:TpvInt32;const AxisTest:TpvVector3;out AxisPenetration:TpvVector3):TpvScalar; var min1,max1,min2,max2,len1,len2:TpvScalar; begin AxisPenetration:=AxisTest.Normalize; DoCalculateInterval(Vertices1,Count1,AxisPenetration,min1,max1); DoCalculateInterval(Vertices2,Count2,AxisPenetration,min2,max2); if (max1<min2) or (min1>max2) then begin result:=-1.0; end else begin len1:=max1-min1; len2:=max2-min2; if (min1>min2) and (max1<max2) then begin result:=len1+min(abs(min1-min2),abs(max1-max2)); end else if (min2>min1) and (max2<max1) then begin result:=len2+min(abs(min1-min2),abs(max1-max2)); end else begin result:=(len1+len2)-(max(max1,max2)-min(min1,min2)); end; if min2<min1 then begin AxisPenetration:=-AxisPenetration; end; end; end; function BoxGetDistanceToPoint(Point:TpvVector3;const Center,Size:TpvVector3;const InvTransformMatrix,TransformMatrix:TpvMatrix4x4;var ClosestBoxPoint:TpvVector3):TpvScalar; var HalfSize:TpvVector3; begin result:=0; ClosestBoxPoint:=(InvTransformMatrix*Point)-Center; HalfSize.x:=abs(Size.x*0.5); HalfSize.y:=abs(Size.y*0.5); HalfSize.z:=abs(Size.z*0.5); if ClosestBoxPoint.x<-HalfSize.x then begin result:=result+sqr(ClosestBoxPoint.x-(-HalfSize.x)); ClosestBoxPoint.x:=-HalfSize.x; end else if ClosestBoxPoint.x>HalfSize.x then begin result:=result+sqr(ClosestBoxPoint.x-HalfSize.x); ClosestBoxPoint.x:=HalfSize.x; end; if ClosestBoxPoint.y<-HalfSize.y then begin result:=result+sqr(ClosestBoxPoint.y-(-HalfSize.y)); ClosestBoxPoint.y:=-HalfSize.y; end else if ClosestBoxPoint.y>HalfSize.y then begin result:=result+sqr(ClosestBoxPoint.y-HalfSize.y); ClosestBoxPoint.y:=HalfSize.y; end; if ClosestBoxPoint.z<-HalfSize.z then begin result:=result+sqr(ClosestBoxPoint.z-(-HalfSize.z)); ClosestBoxPoint.z:=-HalfSize.z; end else if ClosestBoxPoint.z>HalfSize.z then begin result:=result+sqr(ClosestBoxPoint.z-HalfSize.z); ClosestBoxPoint.z:=HalfSize.z; end; ClosestBoxPoint:=TransformMatrix*(ClosestBoxPoint+Center); end; function GetDistanceFromLine(const p0,p1,p:TpvVector3;var Projected:TpvVector3;const Time:PpvScalar=nil):TpvScalar; var p10:TpvVector3; t:TpvScalar; begin p10:=p1-p0; t:=p10.Length; if t<EPSILON then begin p10:=TpvVector3.Origin; end else begin p10:=p10/t; end; t:=p10.Dot(p-p0); if assigned(Time) then begin Time^:=t; end; Projected:=p0+(p10*t); result:=(p-Projected).Length; end; procedure LineClosestApproach(const pa,ua,pb,ub:TpvVector3;var Alpha,Beta:TpvScalar); var p:TpvVector3; uaub,q1,q2,d:TpvScalar; begin p:=pb-pa; uaub:=ua.Dot(ub); q1:=ua.Dot(p); q2:=ub.Dot(p); d:=1.0-sqr(uaub); if d<EPSILON then begin Alpha:=0; Beta:=0; end else begin d:=1.0/d; Alpha:=(q1+(uaub*q2))*d; Beta:=((uaub*q1)+q2)*d; end; end; procedure ClosestLineBoxPoints(const p1,p2,c:TpvVector3;const ir,r:TpvMatrix4x4;const side:TpvVector3;var lret,bret:TpvVector3); const tanchorepsilon:TpvFloat={$ifdef physicsdouble}1e-307{$else}1e-19{$endif}; var tmp,s,v,sign,v2,h:TpvVector3; region:array[0..2] of TpvInt32; tanchor:array[0..2] of TpvScalar; i:TpvInt32; t,dd2dt,nextt,nextdd2dt:TpvScalar; DoGetAnswer:boolean; begin s:=ir*(p1-c); v:=ir*(p2-p1); for i:=0 to 2 do begin if v.RawComponents[i]<0 then begin s.RawComponents[i]:=-s.RawComponents[i]; v.RawComponents[i]:=-v.RawComponents[i]; sign.RawComponents[i]:=-1; end else begin sign.RawComponents[i]:=1; end; end; v2:=v*v; h:=side*0.5; for i:=0 to 2 do begin if v.RawComponents[i]>tanchorepsilon then begin if s.RawComponents[i]<-h.RawComponents[i] then begin region[i]:=-1; tanchor[i]:=((-h.RawComponents[i])-s.RawComponents[i])/v.RawComponents[i]; end else begin if s.RawComponents[i]>h.RawComponents[i] then begin region[i]:=1; end else begin region[i]:=0; end; tanchor[i]:=(h.RawComponents[i]-s.RawComponents[i])/v.RawComponents[i]; end; end else begin region[i]:=0; tanchor[i]:=2; end; end; t:=0; dd2dt:=0; for i:=0 to 2 do begin if region[i]<>0 then begin dd2dt:=dd2dt-(v2.RawComponents[i]*tanchor[i]); end; end; if dd2dt<0 then begin DoGetAnswer:=false; repeat nextt:=1; for i:=0 to 2 do begin if (tanchor[i]>t) and (tanchor[i]<1) and (tanchor[i]<nextt) then begin nextt:=tanchor[i]; end; end; nextdd2dt:=0; for i:=0 to 2 do begin if region[i]<>0 then begin nextdd2dt:=nextdd2dt+(v2.RawComponents[i]*(nextt-tanchor[i])); end; end; if nextdd2dt>=0 then begin t:=t-(dd2dt/((nextdd2dt-dd2dt)/(nextt-t))); DoGetAnswer:=true; break; end; for i:=0 to 2 do begin if abs(tanchor[i]-nextt)<EPSILON then begin tanchor[i]:=(h.RawComponents[i]-s.RawComponents[i])/v.RawComponents[i]; inc(region[i]); end; end; t:=nextt; dd2dt:=nextdd2dt; until t>=1; if not DoGetAnswer then begin t:=1; end; end; lret:=p1+((p2-p1)*t); for i:=0 to 2 do begin tmp.RawComponents[i]:=sign.RawComponents[i]*(s.RawComponents[i]+(t*v.RawComponents[i])); if tmp.RawComponents[i]<-h.RawComponents[i] then begin tmp.RawComponents[i]:=-h.RawComponents[i]; end else if tmp.RawComponents[i]>h.RawComponents[i] then begin tmp.RawComponents[i]:=h.RawComponents[i]; end; end; bret:=c+(r*tmp); end; procedure ClosestLineSegmentPoints(const a0,a1,b0,b1:TpvVector3;var cp0,cp1:TpvVector3); var a0a1,b0b1,a0b0,a0b1,a1b0,a1b1,n:TpvVector3; la,lb,k,da0,da1,da2,da3,db0,db1,db2,db3,det,Alpha,Beta:TpvScalar; begin a0a1:=a1-a0; b0b1:=b1-b0; a0b0:=b0-a0; da0:=a0a1.Dot(a0b0); db0:=b0b1.Dot(a0b0); if (da0<=0) and (db0>=0) then begin cp0:=a0; cp1:=b0; exit; end; a0b1:=b1-a0; da1:=a0a1.Dot(a0b1); db1:=b0b1.Dot(a0b1); if (da1<=0) and (db1<=0) then begin cp0:=a0; cp1:=b1; exit; end; a1b0:=b0-a1; da2:=a0a1.Dot(a1b0); db2:=b0b1.Dot(a1b0); if (da2>=0) and (db2>=0) then begin cp0:=a1; cp1:=b0; exit; end; a1b1:=b1-a1; da3:=a0a1.Dot(a1b1); db3:=b0b1.Dot(a1b1); if (da3>=0) and (db3<=0) then begin cp0:=a1; cp1:=b1; exit; end; la:=a0a1.Dot(a0a1); if (da0>=0) and (da2<=0) then begin k:=da0/la; n:=a0b0-(a0a1*k); if b0b1.Dot(n)>=0 then begin cp0:=a0+(a0a1*k); cp1:=b0; exit; end; end; if (da1>=0) and (da3<=0) then begin k:=da1/la; n:=a0b1-(a0a1*k); if b0b1.Dot(n)<=0 then begin cp0:=a0+(a0a1*k); cp1:=b1; exit; end; end; lb:=b0b1.Dot(b0b1); if (db0<=0) and (db1>=0) then begin k:=-db0/lb; n:=(b0b1*k)-a0a1; if a0a1.Dot(n)>=0 then begin cp0:=a0; cp1:=b0+(b0b1*k); exit; end; end; if (db2<=0) and (db3>=0) then begin k:=-db2/lb; n:=(b0b1*k)-a1b0; if a0a1.Dot(n)>=0 then begin cp0:=a1; cp1:=b0+(b0b1*k); exit; end; end; k:=a0a1.Dot(b0b1); det:=(la*lb)-sqr(k); if det<=EPSILON then begin cp0:=a0; cp1:=b0; end else begin det:=1/det; Alpha:=((lb*da0)-(k*db0))*det; Beta:=((k*da0)-(la*db0))*det; cp0:=a0+(a0a1*Alpha); cp1:=b0+(b0b1*Beta); end; end; function LineSegmentIntersection(const a0,a1,b0,b1:TpvVector3;const p:PpvVector3=nil):boolean; var da,db,dc,cdadb:TpvVector3; t:TpvScalar; begin result:=false; da:=a1-a0; db:=b1-b0; dc:=b0-a0; cdadb:=da.Cross(db); if abs(cdadb.Dot(dc))>EPSILON then begin // Lines are not coplanar exit; end; t:=dc.Cross(db).Dot(cdadb)/cdadb.SquaredLength; if (t>=0.0) and (t<=1.0) then begin if assigned(p) then begin p^:=a0.Lerp(a1,t); end; result:=true; end; end; function LineLineIntersection(const a0,a1,b0,b1:TpvVector3;const pa:PpvVector3=nil;const pb:PpvVector3=nil;const ta:PpvScalar=nil;const tb:PpvScalar=nil):boolean; var p02,p32,p10:TpvVector3; d0232,d3210,d0210,d3232,d1010,Numerator,Denominator,lta,ltb:TpvScalar; begin result:=false; p32.x:=b1.x-b0.x; p32.y:=b1.y-b0.y; p32.z:=b1.z-b0.z; if (abs(p32.x)<EPSILON) and (abs(p32.y)<EPSILON) and (abs(p32.z)<EPSILON) then begin exit; end; p10.x:=a1.x-a0.x; p10.y:=a1.y-a0.y; p10.z:=a1.z-a0.z; if (abs(p10.x)<EPSILON) and (abs(p10.y)<EPSILON) and (abs(p10.z)<EPSILON) then begin exit; end; p02.x:=a0.x-b0.x; p02.y:=a0.y-b0.y; p02.z:=a0.z-b0.z; d0232:=(p02.x*p32.x)+(p02.y*p32.y)+(p02.z*p32.z); d3210:=(p32.x*p10.x)+(p32.y*p10.y)+(p32.z*p10.z); d0210:=(p02.x*p10.x)+(p02.y*p10.y)+(p02.z*p10.z); d3232:=(p32.x*p32.x)+(p32.y*p32.y)+(p32.z*p32.z); d1010:=(p10.x*p10.x)+(p10.y*p10.y)+(p10.z*p10.z); Denominator:=(d1010*d3232)-(d3210*d3210); if abs(Denominator)<EPSILON then begin exit; end; if assigned(pa) or assigned(pb) or assigned(ta) or assigned(tb) then begin Numerator:=(d0232*d3210)-(d0210*d3232); lta:=Numerator/Denominator; ltb:=(d0232+(d3210*lta))/d3232; if assigned(ta) then begin ta^:=lta; end; if assigned(tb) then begin tb^:=ltb; end; if assigned(pa) then begin pa^:=a0.Lerp(a1,lta); end; if assigned(pb) then begin pb^:=b0.Lerp(b1,ltb); end; end; result:=true; end; function IsPointsSameSide(const p0,p1,Origin,Direction:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Direction.Cross(p0-Origin).Dot(Direction.Cross(p1-Origin))>=0.0; end; function PointInTriangle(const p0,p1,p2,Normal,p:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} var r0,r1,r2:TpvScalar; begin r0:=(p1-p0).Cross(Normal).Dot(p-p0); r1:=(p2-p1).Cross(Normal).Dot(p-p1); r2:=(p0-p2).Cross(Normal).Dot(p-p2); result:=((r0>0.0) and (r1>0.0) and (r2>0.0)) or ((r0<=0.0) and (r1<=0.0) and (r2<=0.0)); end; function PointInTriangle(const p0,p1,p2,p:TpvVector3):boolean; overload; {$ifdef CAN_INLINE}inline;{$endif} begin result:=IsPointsSameSide(p,p0,p1,p2-p1) and IsPointsSameSide(p,p1,p0,p2-p0) and IsPointsSameSide(p,p2,p0,p1-p0); end; function GetOverlap(const MinA,MaxA,MinB,MaxB:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var Mins,Maxs:TpvScalar; begin if (MinA>MaxB) or (MaxA<MinB) then begin result:=0.0; end else begin if MinA<MinB then begin result:=MinB-MaxA; end else begin result:=MinA-MaxB; end; if ((MinB>=MinA) and (MaxB<=MaxA)) or ((MinA>=MinB) and (MaxA<=MaxB)) then begin Mins:=abs(MinA-MinB); Maxs:=abs(MaxA-MaxB); if Mins<Maxs then begin result:=result+Mins; end else begin result:=result+Maxs; end; end; end; end; function OldTriangleTriangleIntersection(const a0,a1,a2,b0,b1,b2:TpvVector3):boolean; const EPSILON=1e-2; LINEEPSILON=1e-6; var Index,NextIndex,RemainingIndex,i,j,k,h:TpvInt32; tS,tT0,tT1:TpvScalar; v:array[0..1,0..2] of TpvVector3; SegmentTriangles:array[0..1] of TpvSegmentTriangle; Segment:TpvRelativeSegment; lv,plv:TpvVector3; OK:boolean; begin result:=false; v[0,0]:=a0; v[0,1]:=a1; v[0,2]:=a2; v[1,0]:=b0; v[1,1]:=b1; v[1,2]:=b2; SegmentTriangles[0].Origin:=a0; SegmentTriangles[0].Edge0:=a1-a0; SegmentTriangles[0].Edge1:=a2-a0; SegmentTriangles[1].Origin:=b0; SegmentTriangles[1].Edge0:=b1-b0; SegmentTriangles[1].Edge1:=b2-b0; for Index:=0 to 2 do begin NextIndex:=Index+1; if NextIndex>2 then begin dec(NextIndex,3); end; RemainingIndex:=NextIndex+1; if RemainingIndex>2 then begin dec(RemainingIndex,3); end; for i:=0 to 3 do begin case i of 0:begin Segment.Origin:=v[0,Index]; Segment.Delta:=v[0,NextIndex]-v[0,Index]; j:=1; end; 1:begin Segment.Origin:=v[1,Index]; Segment.Delta:=v[1,NextIndex]-v[1,Index]; j:=0; end; 2:begin Segment.Origin:=v[0,Index]; Segment.Delta:=((v[0,NextIndex]+v[0,RemainingIndex])*0.5)-v[0,Index]; j:=1; end; else begin Segment.Origin:=v[1,Index]; Segment.Delta:=((v[1,NextIndex]+v[1,RemainingIndex])*0.5)-v[1,Index]; j:=0; end; end; if SegmentTriangles[j].RelativeSegmentIntersection(Segment,tS,tT0,tT1) then begin OK:=true; if i<2 then begin lv:=Segment.Origin+(Segment.Delta*tS); for k:=0 to 2 do begin h:=k+1; if h>2 then begin dec(h,2); end; if GetDistanceFromLine(v[j,k],v[j,h],lv,plv)<EPSILON then begin OK:=false; break; end; end; end; if OK and (((tT0>EPSILON) and (tT0<(1.0-EPSILON))) or ((tT1>EPSILON) and (tT1<(1.0-EPSILON)))) then begin result:=true; exit; end; end; end; end; end; function TriangleTriangleIntersection(const v0,v1,v2,u0,u1,u2:TpvVector3):boolean; const EPSILON=1e-6; procedure SORT(var a,b:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} var c:TpvScalar; begin if a>b then begin c:=a; a:=b; b:=c; end; end; procedure ISECT(const VV0,VV1,VV2,D0,D1,D2:TpvScalar;var isect0,isect1:TpvScalar); {$ifdef CAN_INLINE}inline;{$endif} begin isect0:=VV0+(((VV1-VV0)*D0)/(D0-D1)); isect1:=VV0+(((VV2-VV0)*D0)/(D0-D2)); end; function EDGE_EDGE_TEST(const v0,u0,u1:TpvVector3;const Ax,Ay:TpvScalar;const i0,i1:TpvInt32):boolean; {$ifdef CAN_INLINE}inline;{$endif} var Bx,By,Cx,Cy,e,f,d:TpvScalar; begin result:=false; Bx:=U0.RawComponents[i0]-U1.RawComponents[i0]; By:=U0.RawComponents[i1]-U1.RawComponents[i1]; Cx:=V0.RawComponents[i0]-U0.RawComponents[i0]; Cy:=V0.RawComponents[i1]-U0.RawComponents[i1]; f:=(Ay*Bx)-(Ax*By); d:=(By*Cx)-(Bx*Cy); if ((f>0.0) and (d>=0.0) and (d<=f)) or ((f<0.0) and (d<=0.0) and (d>=f)) then begin e:=(Ax*Cy)-(Ay*Cx); if f>0.0 then begin if (e>=0.0) and (e<=f) then begin result:=true; end; end else begin if (e<=0.0) and (e>=f) then begin result:=true; end; end; end; end; function POINT_IN_TRI(const v0,u0,u1,u2:TpvVector3;const i0,i1:TpvInt32):boolean; var a,b,c,d0,d1,d2:TpvScalar; begin // is T1 completly inside T2? // check if V0 is inside tri(U0,U1,U2) a:=U1.RawComponents[i1]-U0.RawComponents[i1]; b:=-(U1.RawComponents[i0]-U0.RawComponents[i0]); c:=(-(a*U0.RawComponents[i0]))-(b*U0.RawComponents[i1]); d0:=((a*V0.RawComponents[i0])+(b*V0.RawComponents[i1]))+c; a:=U2.RawComponents[i1]-U1.RawComponents[i1]; b:=-(U2.RawComponents[i0]-U1.RawComponents[i0]); c:=(-(a*U1.RawComponents[i0]))-(b*U1.RawComponents[i1]); d1:=((a*V0.RawComponents[i0])+(b*V0.RawComponents[i1]))+c; a:=U0.RawComponents[i1]-U2.RawComponents[i1]; b:=-(U0.RawComponents[i0]-U2.RawComponents[i0]); c:=(-(a*U2.RawComponents[i0]))-(b*U2.RawComponents[i1]); d2:=((a*V0.RawComponents[i0])+(b*V0.RawComponents[i1]))+c; result:=((d0*d1)>0.0) and ((d0*d2)>0.0); end; function EDGE_AGAINST_TRI_EDGES(const v0,v1,u0,u1,u2:TpvVector3;const i0,i1:TpvInt32):boolean; var Ax,Ay:TpvScalar; begin Ax:=v1.RawComponents[i0]-v0.RawComponents[i0]; Ay:=v1.RawComponents[i1]-v0.RawComponents[i1]; result:=EDGE_EDGE_TEST(V0,U0,U1,Ax,Ay,i0,i1) or // test edge U0,U1 against V0,V1 EDGE_EDGE_TEST(V0,U1,U2,Ax,Ay,i0,i1) or // test edge U1,U2 against V0,V1 EDGE_EDGE_TEST(V0,U2,U0,Ax,Ay,i0,i1); // test edge U2,U1 against V0,V1 end; function coplanar_tri_tri(const n,v0,v1,v2,u0,u1,u2:TpvVector3):boolean; var i0,i1:TpvInt32; a:TpvVector3; begin a.x:=abs(n.x); a.y:=abs(n.y); a.z:=abs(n.z); if a.x>a.y then begin if a.x>a.z then begin i0:=1; i1:=2; end else begin i0:=0; i1:=1; end; end else begin if a.y<a.z then begin i0:=0; i1:=1; end else begin i0:=0; i1:=2; end; end; // test all edges of triangle 1 against the edges of triangle 2 result:=EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2,i0,i1) or EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2,i0,i1) or EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2,i0,i1) or POINT_IN_TRI(V0,U0,U1,U2,i0,i1) or // finally, test if tri1 is totally contained in tri2 or vice versa POINT_IN_TRI(U0,V0,V1,V2,i0,i1); end; function COMPUTE_INTERVALS(const N1:TpvVector3;const VV0,VV1,VV2,D0,D1,D2,D0D1,D0D2:TpvScalar;var isect0,isect1:TpvScalar):boolean; begin result:=false; if D0D1>0.0 then begin // here we know that D0D2<=0.0 // that is D0, D1 are on the same side, D2 on the other or on the plane ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); end else if D0D2>0.0 then begin // here we know that d0d1<=0.0 ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); end else if ((D1*D2)>0.0) or (D0<>0.0) then begin // here we know that d0d1<=0.0 or that D0<>0.0 ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1); end else if D1<>0.0 then begin ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); end else if D2<>0.0 then begin ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); end else begin // triangles are coplanar result:=coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2); end; end; var index:TpvInt32; d1,d2,du0,du1,du2,dv0,dv1,dv2,du0du1,du0du2,dv0dv1,dv0dv2,vp0,vp1,vp2,up0,up1,up2,b,c,m:TpvScalar; isect1,isect2:array[0..1] of TpvScalar; e1,e2,n1,n2,d:TpvVector3; begin result:=false; // compute plane equation of triangle(V0,V1,V2) e1:=v1-v0; e2:=v2-v0; n1:=e1.Cross(e2); d1:=-n1.Dot(v0); // put U0,U1,U2 into plane equation 1 to compute signed distances to the plane du0:=n1.Dot(u0)+d1; du1:=n1.Dot(u1)+d1; du2:=n1.Dot(u2)+d1; // coplanarity robustness check if abs(du0)<EPSILON then begin du0:=0.0; end; if abs(du1)<EPSILON then begin du1:=0.0; end; if abs(du2)<EPSILON then begin du2:=0.0; end; du0du1:=du0*du1; du0du2:=du0*du2; // same sign on all of them + not equal 0 ? if (du0du1>0.0) and (du0du2>0.0) then begin // no intersection occurs exit; end; // compute plane of triangle (U0,U1,U2) e1:=u1-u0; e2:=u2-u0; n2:=e1.Cross(e2); d2:=-n2.Dot(u0); // put V0,V1,V2 into plane equation 2 dv0:=n2.Dot(v0)+d2; dv1:=n2.Dot(v1)+d2; dv2:=n2.Dot(v2)+d2; // coplanarity robustness check if abs(dv0)<EPSILON then begin dv0:=0.0; end; if abs(dv1)<EPSILON then begin dv1:=0.0; end; if abs(dv2)<EPSILON then begin dv2:=0.0; end; dv0dv1:=dv0*dv1; dv0dv2:=dv0*dv2; // same sign on all of them + not equal 0 ? if (dv0dv1>0.0) and (dv0dv2>0.0) then begin // no intersection occurs exit; end; // compute direction of intersection line d:=n1.Cross(n2); // compute and index to the largest component of D m:=abs(d.x); index:=0; b:=abs(d.y); c:=abs(d.z); if m<b then begin m:=b; index:=1; end; if m<c then begin //m:=c; index:=2; end; // this is the simplified projection onto L vp0:=v0.RawComponents[index]; vp1:=v1.RawComponents[index]; vp2:=v2.RawComponents[index]; up0:=u0.RawComponents[index]; up1:=u1.RawComponents[index]; up2:=u2.RawComponents[index]; // compute interval for triangle 1 result:=COMPUTE_INTERVALS(N1,vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,isect1[0],isect1[1]); if result then begin exit; end; // compute interval for triangle 2 result:=COMPUTE_INTERVALS(N1,up0,up1,up2,du0,du1,du2,du0du1,du0du2,isect2[0],isect2[1]); if result then begin exit; end; SORT(isect1[0],isect1[1]); SORT(isect2[0],isect2[1]); result:=not ((isect1[1]<isect2[0]) or (isect2[1]<isect1[0])); end; function UnclampedClosestPointToLine(const LineStartPoint,LineEndPoint,Point:TpvVector3;const ClosestPointOnLine:PpvVector3=nil;const Time:PpvScalar=nil):TpvScalar; var LineSegmentPointsDifference,ClosestPoint:TpvVector3; LineSegmentLengthSquared,PointOnLineSegmentTime:TpvScalar; begin LineSegmentPointsDifference:=LineEndPoint-LineStartPoint; LineSegmentLengthSquared:=LineSegmentPointsDifference.SquaredLength; if LineSegmentLengthSquared<EPSILON then begin PointOnLineSegmentTime:=0.0; ClosestPoint:=LineStartPoint; end else begin PointOnLineSegmentTime:=(Point-LineStartPoint).Dot(LineSegmentPointsDifference)/LineSegmentLengthSquared; ClosestPoint:=LineStartPoint+(LineSegmentPointsDifference*PointOnLineSegmentTime); end; if assigned(ClosestPointOnLine) then begin ClosestPointOnLine^:=ClosestPoint; end; if assigned(Time) then begin Time^:=PointOnLineSegmentTime; end; result:=Point.DistanceTo(ClosestPoint); end; function ClosestPointToLine(const LineStartPoint,LineEndPoint,Point:TpvVector3;const ClosestPointOnLine:PpvVector3=nil;const Time:PpvScalar=nil):TpvScalar; var LineSegmentPointsDifference,ClosestPoint:TpvVector3; LineSegmentLengthSquared,PointOnLineSegmentTime:TpvScalar; begin LineSegmentPointsDifference:=LineEndPoint-LineStartPoint; LineSegmentLengthSquared:=LineSegmentPointsDifference.SquaredLength; if LineSegmentLengthSquared<EPSILON then begin PointOnLineSegmentTime:=0.0; ClosestPoint:=LineStartPoint; end else begin PointOnLineSegmentTime:=(Point-LineStartPoint).Dot(LineSegmentPointsDifference)/LineSegmentLengthSquared; if PointOnLineSegmentTime<=0.0 then begin PointOnLineSegmentTime:=0.0; ClosestPoint:=LineStartPoint; end else if PointOnLineSegmentTime>=1.0 then begin PointOnLineSegmentTime:=1.0; ClosestPoint:=LineEndPoint; end else begin ClosestPoint:=LineStartPoint+(LineSegmentPointsDifference*PointOnLineSegmentTime); end; end; if assigned(ClosestPointOnLine) then begin ClosestPointOnLine^:=ClosestPoint; end; if assigned(Time) then begin Time^:=PointOnLineSegmentTime; end; result:=Point.DistanceTo(ClosestPoint); end; function ClosestPointToAABB(const AABB:TpvAABB;const Point:TpvVector3;const ClosestPointOnAABB:PpvVector3=nil):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var ClosestPoint:TpvVector3; begin ClosestPoint.x:=Min(Max(Point.x,AABB.Min.x),AABB.Max.x); ClosestPoint.y:=Min(Max(Point.y,AABB.Min.y),AABB.Max.y); ClosestPoint.z:=Min(Max(Point.z,AABB.Min.z),AABB.Max.z); if assigned(ClosestPointOnAABB) then begin ClosestPointOnAABB^:=ClosestPoint; end; result:=ClosestPoint.DistanceTo(Point); end; function ClosestPointToOBB(const OBB:TpvOBB;const Point:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var DistanceVector:TpvVector3; begin DistanceVector:=Point-OBB.Center; ClosestPoint:=OBB.Center+ (OBB.Axis[0]*Min(Max(DistanceVector.Dot(OBB.Axis[0]),-OBB.HalfExtents.RawComponents[0]),OBB.HalfExtents.RawComponents[0]))+ (OBB.Axis[1]*Min(Max(DistanceVector.Dot(OBB.Axis[1]),-OBB.HalfExtents.RawComponents[1]),OBB.HalfExtents.RawComponents[1]))+ (OBB.Axis[2]*Min(Max(DistanceVector.Dot(OBB.Axis[2]),-OBB.HalfExtents.RawComponents[2]),OBB.HalfExtents.RawComponents[2])); result:=ClosestPoint.DistanceTo(Point); end; function ClosestPointToSphere(const Sphere:TpvSphere;const Point:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin result:=Max(0.0,Sphere.Center.DistanceTo(Point)-Sphere.Radius); ClosestPoint:=Point+((Sphere.Center-Point).Normalize*result); end; function ClosestPointToCapsule(const Capsule:TpvCapsule;const Point:TpvVector3;out ClosestPoint:TpvVector3;const Time:PpvScalar=nil):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var LineSegmentPointsDifference,LineClosestPoint:TpvVector3; LineSegmentLengthSquared,PointOnLineSegmentTime:TpvScalar; begin LineSegmentPointsDifference:=Capsule.LineEndPoint-Capsule.LineStartPoint; LineSegmentLengthSquared:=LineSegmentPointsDifference.SquaredLength; if LineSegmentLengthSquared<EPSILON then begin PointOnLineSegmentTime:=0.0; LineClosestPoint:=Capsule.LineStartPoint; end else begin PointOnLineSegmentTime:=(Point-Capsule.LineStartPoint).Dot(LineSegmentPointsDifference)/LineSegmentLengthSquared; if PointOnLineSegmentTime<=0.0 then begin PointOnLineSegmentTime:=0.0; LineClosestPoint:=Capsule.LineStartPoint; end else if PointOnLineSegmentTime>=1.0 then begin PointOnLineSegmentTime:=1.0; LineClosestPoint:=Capsule.LineEndPoint; end else begin LineClosestPoint:=Capsule.LineStartPoint+(LineSegmentPointsDifference*PointOnLineSegmentTime); end; end; LineSegmentPointsDifference:=LineClosestPoint-Point; result:=Max(0.0,LineSegmentPointsDifference.Length-Capsule.Radius); ClosestPoint:=Point+(LineSegmentPointsDifference.Normalize*result); if assigned(Time) then begin Time^:=PointOnLineSegmentTime; end; end; function ClosestPointToTriangle(const a,b,c,p:TpvVector3;out ClosestPoint:TpvVector3):TpvScalar; var ab,ac,bc,pa,pb,pc,ap,bp,cp,n:TpvVector3; snom,sdenom,tnom,tdenom,unom,udenom,vc,vb,va,u,v,w:TpvScalar; begin ab.x:=b.x-a.x; ab.y:=b.y-a.y; ab.z:=b.z-a.z; ac.x:=c.x-a.x; ac.y:=c.y-a.y; ac.z:=c.z-a.z; bc.x:=c.x-b.x; bc.y:=c.y-b.y; bc.z:=c.z-b.z; pa.x:=p.x-a.x; pa.y:=p.y-a.y; pa.z:=p.z-a.z; pb.x:=p.x-b.x; pb.y:=p.y-b.y; pb.z:=p.z-b.z; pc.x:=p.x-c.x; pc.y:=p.y-c.y; pc.z:=p.z-c.z; // Determine the parametric position s for the projection of P onto AB (i.e. Pí = A+s*AB, where // s = snom/(snom+sdenom), and then parametric position t for P projected onto AC snom:=(ab.x*pa.x)+(ab.y*pa.y)+(ab.z*pa.z); sdenom:=(pb.x*(a.x-b.x))+(pb.y*(a.y-b.y))+(pb.z*(a.z-b.z)); tnom:=(ac.x*pa.x)+(ac.y*pa.y)+(ac.z*pa.z); tdenom:=(pc.x*(a.x-c.x))+(pc.y*(a.y-c.y))+(pc.z*(a.z-c.z)); if (snom<=0.0) and (tnom<=0.0) then begin // Vertex voronoi region hit early out ClosestPoint:=a; result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; // Parametric position u for P projected onto BC unom:=(bc.x*pb.x)+(bc.y*pb.y)+(bc.z*pb.z); udenom:=(pc.x*(b.x-c.x))+(pc.y*(b.y-c.y))+(pc.z*(b.z-c.z)); if (sdenom<=0.0) and (unom<=0.0) then begin // Vertex voronoi region hit early out ClosestPoint:=b; result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; if (tdenom<=0.0) and (udenom<=0.0) then begin // Vertex voronoi region hit early out ClosestPoint:=c; result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; // Determine if P is outside (or on) edge AB by finding the area formed by vectors PA, PB and // the triangle normal. A scalar triple product is used. P is outside (or on) AB if the triple // scalar product [N PA PB] <= 0 n.x:=(ab.y*ac.z)-(ab.z*ac.y); n.y:=(ab.z*ac.x)-(ab.x*ac.z); n.z:=(ab.x*ac.y)-(ab.y*ac.x); ap.x:=a.x-p.x; ap.y:=a.y-p.y; ap.z:=a.z-p.z; bp.x:=b.x-p.x; bp.y:=b.y-p.y; bp.z:=b.z-p.z; vc:=(n.x*((ap.y*bp.z)-(ap.z*bp.y)))+(n.y*((ap.z*bp.x)-(ap.x*bp.z)))+(n.z*((ap.x*bp.y)-(ap.y*bp.x))); // If P is outside of AB (signed area <= 0) and within voronoi feature region, then return // projection of P onto AB if (vc<=0.0) and (snom>=0.0) and (sdenom>=0.0) then begin u:=snom/(snom+sdenom); ClosestPoint.x:=a.x+(ab.x*u); ClosestPoint.y:=a.y+(ab.y*u); ClosestPoint.z:=a.z+(ab.z*u); result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; // Repeat the same test for P onto BC cp.x:=c.x-p.x; cp.y:=c.y-p.y; cp.z:=c.z-p.z; va:=(n.x*((bp.y*cp.z)-(bp.z*cp.y)))+(n.y*((bp.z*cp.x)-(bp.x*cp.z)))+(n.z*((bp.x*cp.y)-(bp.y*cp.x))); if (va<=0.0) and (unom>=0.0) and (udenom>=0.0) then begin v:=unom/(unom+udenom); ClosestPoint.x:=b.x+(bc.x*v); ClosestPoint.y:=b.y+(bc.y*v); ClosestPoint.z:=b.z+(bc.z*v); result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; // Repeat the same test for P onto CA vb:=(n.x*((cp.y*ap.z)-(cp.z*ap.y)))+(n.y*((cp.z*ap.x)-(cp.x*ap.z)))+(n.z*((cp.x*ap.y)-(cp.y*ap.x))); if (vb<=0.0) and (tnom>=0.0) and (tdenom>=0.0) then begin w:=tnom/(tnom+tdenom); ClosestPoint.x:=a.x+(ac.x*w); ClosestPoint.y:=a.y+(ac.y*w); ClosestPoint.z:=a.z+(ac.z*w); result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); exit; end; // P must project onto inside face. Find closest point using the barycentric coordinates w:=1.0/(va+vb+vc); u:=va*w; v:=vb*w; w:=(1.0-u)-v; ClosestPoint.x:=(a.x*u)+(b.x*v)+(c.x*w); ClosestPoint.y:=(a.y*u)+(b.y*v)+(c.y*w); ClosestPoint.z:=(a.z*u)+(b.z*v)+(c.z*w); result:=sqrt(sqr(ClosestPoint.x-p.x)+sqr(ClosestPoint.y-p.y)+sqr(ClosestPoint.z-p.z)); end; function SquaredDistanceFromPointToAABB(const AABB:TpvAABB;const Point:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} var ClosestPoint:TpvVector3; begin ClosestPoint.x:=Min(Max(Point.x,AABB.Min.x),AABB.Max.x); ClosestPoint.y:=Min(Max(Point.y,AABB.Min.y),AABB.Max.y); ClosestPoint.z:=Min(Max(Point.z,AABB.Min.z),AABB.Max.z); result:=(ClosestPoint-Point).SquaredLength; end; function SquaredDistanceFromPointToTriangle(const p,a,b,c:TpvVector3):TpvScalar; var ab,ac,bc,pa,pb,pc,ap,bp,cp,n:TpvVector3; snom,sdenom,tnom,tdenom,unom,udenom,vc,vb,va,u,v,w:TpvScalar; begin ab.x:=b.x-a.x; ab.y:=b.y-a.y; ab.z:=b.z-a.z; ac.x:=c.x-a.x; ac.y:=c.y-a.y; ac.z:=c.z-a.z; bc.x:=c.x-b.x; bc.y:=c.y-b.y; bc.z:=c.z-b.z; pa.x:=p.x-a.x; pa.y:=p.y-a.y; pa.z:=p.z-a.z; pb.x:=p.x-b.x; pb.y:=p.y-b.y; pb.z:=p.z-b.z; pc.x:=p.x-c.x; pc.y:=p.y-c.y; pc.z:=p.z-c.z; // Determine the parametric position s for the projection of P onto AB (i.e. PPU2 = A+s*AB, where // s = snom/(snom+sdenom), and then parametric position t for P projected onto AC snom:=(ab.x*pa.x)+(ab.y*pa.y)+(ab.z*pa.z); sdenom:=(pb.x*(a.x-b.x))+(pb.y*(a.y-b.y))+(pb.z*(a.z-b.z)); tnom:=(ac.x*pa.x)+(ac.y*pa.y)+(ac.z*pa.z); tdenom:=(pc.x*(a.x-c.x))+(pc.y*(a.y-c.y))+(pc.z*(a.z-c.z)); if (snom<=0.0) and (tnom<=0.0) then begin // Vertex voronoi region hit early out result:=sqr(a.x-p.x)+sqr(a.y-p.y)+sqr(a.z-p.z); exit; end; // Parametric position u for P projected onto BC unom:=(bc.x*pb.x)+(bc.y*pb.y)+(bc.z*pb.z); udenom:=(pc.x*(b.x-c.x))+(pc.y*(b.y-c.y))+(pc.z*(b.z-c.z)); if (sdenom<=0.0) and (unom<=0.0) then begin // Vertex voronoi region hit early out result:=sqr(b.x-p.x)+sqr(b.y-p.y)+sqr(b.z-p.z); exit; end; if (tdenom<=0.0) and (udenom<=0.0) then begin // Vertex voronoi region hit early out result:=sqr(c.x-p.x)+sqr(c.y-p.y)+sqr(c.z-p.z); exit; end; // Determine if P is outside (or on) edge AB by finding the area formed by vectors PA, PB and // the triangle normal. A scalar triple product is used. P is outside (or on) AB if the triple // scalar product [N PA PB] <= 0 n.x:=(ab.y*ac.z)-(ab.z*ac.y); n.y:=(ab.z*ac.x)-(ab.x*ac.z); n.z:=(ab.x*ac.y)-(ab.y*ac.x); ap.x:=a.x-p.x; ap.y:=a.y-p.y; ap.z:=a.z-p.z; bp.x:=b.x-p.x; bp.y:=b.y-p.y; bp.z:=b.z-p.z; vc:=(n.x*((ap.y*bp.z)-(ap.z*bp.y)))+(n.y*((ap.z*bp.x)-(ap.x*bp.z)))+(n.z*((ap.x*bp.y)-(ap.y*bp.x))); // If P is outside of AB (signed area <= 0) and within voronoi feature region, then return // projection of P onto AB if (vc<=0.0) and (snom>=0.0) and (sdenom>=0.0) then begin u:=snom/(snom+sdenom); result:=sqr((a.x+(ab.x*u))-p.x)+sqr((a.y+(ab.y*u))-p.y)+sqr((a.z+(ab.z*u))-p.z); exit; end; // Repeat the same test for P onto BC cp.x:=c.x-p.x; cp.y:=c.y-p.y; cp.z:=c.z-p.z; va:=(n.x*((bp.y*cp.z)-(bp.z*cp.y)))+(n.y*((bp.z*cp.x)-(bp.x*cp.z)))+(n.z*((bp.x*cp.y)-(bp.y*cp.x))); if (va<=0.0) and (unom>=0.0) and (udenom>=0.0) then begin v:=unom/(unom+udenom); result:=sqr((b.x+(bc.x*v))-p.x)+sqr((b.y+(bc.y*v))-p.y)+sqr((b.z+(bc.z*v))-p.z); exit; end; // Repeat the same test for P onto CA vb:=(n.x*((cp.y*ap.z)-(cp.z*ap.y)))+(n.y*((cp.z*ap.x)-(cp.x*ap.z)))+(n.z*((cp.x*ap.y)-(cp.y*ap.x))); if (vb<=0.0) and (tnom>=0.0) and (tdenom>=0.0) then begin w:=tnom/(tnom+tdenom); result:=sqr((a.x+(ac.x*w))-p.x)+sqr((a.y+(ac.y*w))-p.y)+sqr((a.z+(ac.z*w))-p.z); exit; end; // P must project onto inside face. Find closest point using the barycentric coordinates w:=1.0/(va+vb+vc); u:=va*w; v:=vb*w; w:=(1.0-u)-v; result:=sqr(((a.x*u)+(b.x*v)+(c.x*w))-p.x)+sqr(((a.y*u)+(b.y*v)+(c.y*w))-p.y)+sqr(((a.z*u)+(b.z*v)+(c.z*w))-p.z); end; function IsParallel(const a,b:TpvVector3;const Tolerance:TpvScalar=1e-5):boolean; {$ifdef CAN_INLINE}inline;{$endif} var t:TpvVector3; begin t:=a-(b*(a.Length/b.Length)); result:=(abs(t.x)<Tolerance) and (abs(t.y)<Tolerance) and (abs(t.z)<Tolerance); end; function Vector3ToAnglesLDX(v:TpvVector3):TpvVector3; var Yaw,Pitch:TpvScalar; begin if (v.x=0.0) and (v.y=0.0) then begin Yaw:=0.0; if v.z>0.0 then begin Pitch:=HalfPI; end else begin Pitch:=PI*1.5; end; end else begin if v.x<>0.0 then begin Yaw:=arctan2(v.y,v.x); end else if v.y>0.0 then begin Yaw:=HalfPI; end else begin Yaw:=PI; end; if Yaw<0.0 then begin Yaw:=Yaw+TwoPI; end; Pitch:=ArcTan2(v.z,sqrt(sqr(v.x)+sqr(v.y))); if Pitch<0.0 then begin Pitch:=Pitch+TwoPI; end; end; result.Pitch:=-Pitch; result.Yaw:=Yaw; result.Roll:=0.0; end; procedure AnglesToVector3LDX(const Angles:TpvVector3;var ForwardVector,RightVector,UpVector:TpvVector3); var cp,sp,cy,sy,cr,sr:TpvScalar; begin cp:=cos(Angles.Pitch); sp:=sin(Angles.Pitch); cy:=cos(Angles.Yaw); sy:=sin(Angles.Yaw); cr:=cos(Angles.Roll); sr:=sin(Angles.Roll); ForwardVector:=TpvVector3.Create(cp*cy,cp*sy,-sp).Normalize; RightVector:=TpvVector3.Create(((-(sr*sp*cy))-(cr*(-sy))),((-(sr*sp*sy))-(cr*cy)),-(sr*cp)).Normalize; UpVector:=TpvVector3.Create((cr*sp*cy)+((-sr)*(-sy)),(cr*sp*sy)+((-sr)*cy),cr*cp).Normalize; end; function UnsignedAngle(const v0,v1:TpvVector3):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin //result:=ArcCos(v0.Normalize.Dot(v1))); result:=ArcTan2(v0.Cross(v1).Length,v0.Dot(v1)); if IsNaN(result) or IsInfinite(result) or (abs(result)<1e-12) then begin result:=0.0; end else begin result:=ModuloPos(result,TwoPI); end; end; function AngleDegClamp(a:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin a:=ModuloPos(ModuloPos(a+180.0,360.0)+360.0,360.0)-180.0; while a<-180.0 do begin a:=a+360.0; end; while a>180.0 do begin a:=a-360.0; end; result:=a; end; function AngleDegDiff(a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin result:=AngleDegClamp(AngleDegClamp(b)-AngleDegClamp(a)); end; function AngleClamp(a:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin a:=ModuloPos(ModuloPos(a+PI,TwoPI)+TwoPI,TwoPI)-PI; while a<(-OnePI) do begin a:=a+TwoPI; end; while a>OnePI do begin a:=a-TwoPI; end; result:=a; end; function AngleDiff(a,b:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin result:=AngleClamp(AngleClamp(b)-AngleClamp(a)); end; function AngleLerp(a,b,x:TpvScalar):TpvScalar; {$ifdef CAN_INLINE}inline;{$endif} begin {if (b-a)>PI then begin b:=b-TwoPI; end; if (b-a)<(-PI) then begin b:=b+TwoPI; end; result:=a+((b-a)*x);} result:=a+(AngleDiff(a,b)*x); end; function InertiaTensorTransform(const Inertia,Transform:TpvMatrix3x3):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} begin result:=(Transform*Inertia)*Transform.Transpose; end; function InertiaTensorParallelAxisTheorem(const Center:TpvVector3;const Mass:TpvScalar):TpvMatrix3x3; {$ifdef CAN_INLINE}inline;{$endif} var CenterDotCenter:TpvScalar; begin CenterDotCenter:=sqr(Center.x)+sqr(Center.y)+sqr(Center.z); result[0,0]:=((TpvMatrix3x3.Identity[0,0]*CenterDotCenter)-(Center.x*Center.x))*Mass; result[0,1]:=((TpvMatrix3x3.Identity[0,1]*CenterDotCenter)-(Center.y*Center.x))*Mass; result[0,2]:=((TpvMatrix3x3.Identity[0,2]*CenterDotCenter)-(Center.z*Center.x))*Mass; result[1,0]:=((TpvMatrix3x3.Identity[1,0]*CenterDotCenter)-(Center.x*Center.y))*Mass; result[1,1]:=((TpvMatrix3x3.Identity[1,1]*CenterDotCenter)-(Center.y*Center.y))*Mass; result[1,2]:=((TpvMatrix3x3.Identity[1,2]*CenterDotCenter)-(Center.z*Center.y))*Mass; result[2,0]:=((TpvMatrix3x3.Identity[2,0]*CenterDotCenter)-(Center.x*Center.z))*Mass; result[2,1]:=((TpvMatrix3x3.Identity[2,1]*CenterDotCenter)-(Center.y*Center.z))*Mass; result[2,2]:=((TpvMatrix3x3.Identity[2,2]*CenterDotCenter)-(Center.z*Center.z))*Mass; end; procedure OrthoNormalize(var Tangent,Bitangent,Normal:TpvVector3); begin Normal:=Normal.Normalize; Tangent:=(Tangent-(Normal*Tangent.Dot(Normal))).Normalize; Bitangent:=Normal.Cross(Tangent).Normalize; Bitangent:=Bitangent-(Normal*Bitangent.Dot(Normal)); Bitangent:=(Bitangent-(Tangent*Bitangent.Dot(Tangent))).Normalize; Tangent:=Bitangent.Cross(Normal).Normalize; Normal:=Tangent.Cross(Bitangent).Normalize; end; procedure RobustOrthoNormalize(var Tangent,Bitangent,Normal:TpvVector3;const Tolerance:TpvScalar=1e-3); var Bisector,Axis:TpvVector3; begin begin if Normal.Length<Tolerance then begin // Degenerate case, compute new normal Normal:=Tangent.Cross(Bitangent); if Normal.Length<Tolerance then begin Tangent:=TpvVector3.XAxis; Bitangent:=TpvVector3.YAxis; Normal:=TpvVector3.ZAxis; exit; end; end; Normal:=Normal.Normalize; end; begin // Project tangent and bitangent onto the normal orthogonal plane Tangent:=Tangent-(Normal*Tangent.Dot(Normal)); Bitangent:=Bitangent-(Normal*Bitangent.Dot(Normal)); end; begin // Check for several degenerate cases if Tangent.Length<Tolerance then begin if Bitangent.Length<Tolerance then begin Tangent:=Normal.Normalize; if (Tangent.x<=Tangent.y) and (Tangent.x<=Tangent.z) then begin Tangent:=TpvVector3.XAxis; end else if (Tangent.y<=Tangent.x) and (Tangent.y<=Tangent.z) then begin Tangent:=TpvVector3.YAxis; end else begin Tangent:=TpvVector3.ZAxis; end; Tangent:=Tangent-(Normal*Tangent.Dot(Normal)); Bitangent:=Normal.Cross(Tangent).Normalize; end else begin Tangent:=Bitangent.Cross(Normal).Normalize; end; end else begin Tangent:=Tangent.Normalize; if Bitangent.Length<Tolerance then begin Bitangent:=Normal.Cross(Tangent).Normalize; end else begin Bitangent:=Bitangent.Normalize; Bisector:=Tangent+Bitangent; if Bisector.Length<Tolerance then begin Bisector:=Tangent; end else begin Bisector:=Bisector.Normalize; end; Axis:=Bisector.Cross(Normal).Normalize; if Axis.Dot(Tangent)>0.0 then begin Tangent:=(Bisector+Axis).Normalize; Bitangent:=(Bisector-Axis).Normalize; end else begin Tangent:=(Bisector-Axis).Normalize; Bitangent:=(Bisector+Axis).Normalize; end; end; end; end; Bitangent:=Normal.Cross(Tangent).Normalize; Tangent:=Bitangent.Cross(Normal).Normalize; Normal:=Tangent.Cross(Bitangent).Normalize; end; function MaxOverlaps(const Min1,Max1,Min2,Max2:TpvScalar;var LowerLim,UpperLim:TpvScalar):boolean; begin if (Max1<Min2) or (Max2<Min1) then begin result:=false; end else begin if (Min2<=Min1) and (Min1<=Max2) then begin if (Min1<=Max2) and (Max2<=Max1) then begin LowerLim:=Min1; UpperLim:=Max1; end else if (Max1-Min2)<(Max2-Min1) then begin LowerLim:=Min2; UpperLim:=Max1; end else begin LowerLim:=Min1; UpperLim:=Max2; end; end else begin if (Min1<=Max2) and (Max2<=Max1) then begin LowerLim:=Min2; UpperLim:=Max1; end else if (Max2-Min1)<(Max1-Min2) then begin LowerLim:=Min1; UpperLim:=Max2; end else begin LowerLim:=Min2; UpperLim:=Max1; end; end; result:=true; end; end; function GetHaltonSequence(const aIndex,aPrimeBase:TpvUInt32):TpvDouble; var f,OneOverPrimeBase:TpvDouble; Current,CurrentDiv:TpvInt32; begin result:=0.0; OneOverPrimeBase:=1.0/aPrimeBase; f:=OneOverPrimeBase; Current:=aIndex; while Current>0 do begin CurrentDiv:=Current div aPrimeBase; result:=result+(f*(Current-(CurrentDiv*aPrimeBase))); Current:=CurrentDiv; f:=f*OneOverPrimeBase; end; end; function ConvertRGB32FToRGB9E5(r,g,b:TpvFloat):TpvUInt32; const RGB9E5_EXPONENT_BITS=5; RGB9E5_MANTISSA_BITS=9; RGB9E5_EXP_BIAS=15; RGB9E5_MAX_VALID_BIASED_EXP=31; MAX_RGB9E5_EXP=RGB9E5_MAX_VALID_BIASED_EXP-RGB9E5_EXP_BIAS; RGB9E5_MANTISSA_VALUES=1 shl RGB9E5_MANTISSA_BITS; MAX_RGB9E5_MANTISSA=RGB9E5_MANTISSA_VALUES-1; MAX_RGB9E5=((MAX_RGB9E5_MANTISSA+0.0)/RGB9E5_MANTISSA_VALUES)*(1 shl MAX_RGB9E5_EXP); EPSILON_RGB9E5=(1.0/RGB9E5_MANTISSA_VALUES)/(1 shl RGB9E5_EXP_BIAS); var Exponent,MaxMantissa,ri,gi,bi:TpvInt32; MaxComponent,Denominator:TpvFloat; CastedMaxComponent:TpvUInt32 absolute MaxComponent; begin if r>0.0 then begin if r>MAX_RGB9E5 then begin r:=MAX_RGB9E5; end; end else begin r:=0.0; end; if g>0.0 then begin if g>MAX_RGB9E5 then begin g:=MAX_RGB9E5; end; end else begin g:=0.0; end; if b>0.0 then begin if b>MAX_RGB9E5 then begin b:=MAX_RGB9E5; end; end else begin b:=0.0; end; if r<g then begin if g<b then begin MaxComponent:=b; end else begin MaxComponent:=g; end; end else begin if r<b then begin MaxComponent:=b; end else begin MaxComponent:=r; end; end; Exponent:=(TpvInt32(CastedMaxComponent and $7f800000) shr 23)-127; if Exponent<((-RGB9E5_EXP_BIAS)-1) then begin Exponent:=((-RGB9E5_EXP_BIAS)-1); end; inc(Exponent,RGB9E5_EXP_BIAS+1); if Exponent<0 then begin Exponent:=0; end else if Exponent>RGB9E5_MAX_VALID_BIASED_EXP then begin Exponent:=RGB9E5_MAX_VALID_BIASED_EXP; end; Denominator:=power(2.0,Exponent-(RGB9E5_EXP_BIAS+RGB9E5_MANTISSA_BITS)); MaxMantissa:=trunc(floor((MaxComponent/Denominator)+0.5)); if MaxMantissa=(MAX_RGB9E5_MANTISSA+1) then begin Denominator:=Denominator*2.0; inc(Exponent); Assert(Exponent<=RGB9E5_MAX_VALID_BIASED_EXP); end else begin Assert(Exponent<=MAX_RGB9E5_MANTISSA); end; ri:=trunc(floor((r/Denominator))+0.5); gi:=trunc(floor((g/Denominator))+0.5); bi:=trunc(floor((b/Denominator))+0.5); if ri<0 then begin ri:=0; end else if ri>MAX_RGB9E5_MANTISSA then begin ri:=MAX_RGB9E5_MANTISSA; end; if gi<0 then begin gi:=0; end else if gi>MAX_RGB9E5_MANTISSA then begin gi:=MAX_RGB9E5_MANTISSA; end; if bi<0 then begin bi:=0; end else if bi>MAX_RGB9E5_MANTISSA then begin bi:=MAX_RGB9E5_MANTISSA; end; result:=TpvUInt32(ri) or (TpvUInt32(gi) shl 9) or (TpvUInt32(bi) shl 18) or (TpvUInt32(Exponent and 31) shl 27); end; function PackFP32FloatToM6E5Float(const pValue:TpvFloat):TpvUInt32; const Float32MantissaBits=23; Float32ExponentBits=8; Float32Bits=32; Float32ExponentBias=127; Float6E5MantissaBits=6; Float6E5MantissaMask=(1 shl Float6E5MantissaBits)-1; Float6E5ExponentBits=5; Float6E5Bits=11; Float6E5ExponentBias=15; var CastedValue:TpvUInt32 absolute pValue; Exponent,Mantissa:TpvUInt32; begin // Extract the exponent and the mantissa from the 32-bit floating point value Exponent:=(CastedValue and $7f800000) shr Float32MantissaBits; Mantissa:=(CastedValue shr (Float32MantissaBits-Float6E5MantissaBits)) and Float6E5MantissaMask; // Round mantissa if (CastedValue and (1 shl ((Float32MantissaBits-Float6E5MantissaBits)-1)))<>0 then begin inc(Mantissa); if (Mantissa and (1 shl Float6E5MantissaBits))<>0 then begin Mantissa:=0; inc(Exponent); end; end; if Exponent<=(Float32ExponentBias-Float6E5ExponentBias) then begin // Denormal if Exponent<((Float32ExponentBias-Float6E5ExponentBias)-Float6E5MantissaBits) then begin result:=0; end else begin result:=(Mantissa or (1 shl Float6E5MantissaBits)) shr (((Float32ExponentBias-Float6E5ExponentBias)+1)-Exponent); end; end else if Exponent>(Float32ExponentBias+Float6E5ExponentBias) then begin // |x| > 2^15, overflow, an existing INF, or NaN if Exponent=((1 shl Float32ExponentBits)-1) then begin if Mantissa<>0 then begin // Return allows -NaN to return as NaN even if there is no sign bit. result:=((1 shl (Float6E5ExponentBits+Float6E5MantissaBits))-1) or ((CastedValue shr (Float32Bits-Float6E5Bits)) and (1 shl (Float32MantissaBits+Float32ExponentBits))); exit; end else begin result:=((1 shl Float6E5ExponentBits)-1) shl Float6E5MantissaBits; end; end else begin result:=((((1 shl Float6E5ExponentBits)-1) shl Float6E5MantissaBits)-(1 shl Float6E5MantissaBits)) or Float6E5MantissaMask; end; end else begin result:=((Exponent-(Float32ExponentBias-Float6E5ExponentBias)) shl Float6E5MantissaBits) or Mantissa; end; if (CastedValue and (1 shl (Float32MantissaBits+Float32ExponentBits)))<>0 then begin // Clamp negative value result:=0; end; end; function PackFP32FloatToM5E5Float(const pValue:TpvFloat):TpvUInt32; const Float32MantissaBits=23; Float32ExponentBits=8; Float32Bits=32; Float32ExponentBias=127; Float5E5MantissaBits=5; Float5E5MantissaMask=(1 shl Float5E5MantissaBits)-1; Float5E5ExponentBits=5; Float5E5Bits=10; Float5E5ExponentBias=15; var CastedValue:TpvUInt32 absolute pValue; Exponent,Mantissa:TpvUInt32; begin // Extract the exponent and the mantissa from the 32-bit floating point value Exponent:=(CastedValue and $7f800000) shr Float32MantissaBits; Mantissa:=(CastedValue shr (Float32MantissaBits-Float5E5MantissaBits)) and Float5E5MantissaMask; // Round mantissa if (CastedValue and (1 shl ((Float32MantissaBits-Float5E5MantissaBits)-1)))<>0 then begin inc(Mantissa); if (Mantissa and (1 shl Float5E5MantissaBits))<>0 then begin Mantissa:=0; inc(Exponent); end; end; if Exponent<=(Float32ExponentBias-Float5E5ExponentBias) then begin // Denormal if Exponent<((Float32ExponentBias-Float5E5ExponentBias)-Float5E5MantissaBits) then begin result:=0; end else begin result:=(Mantissa or (1 shl Float5E5MantissaBits)) shr (((Float32ExponentBias-Float5E5ExponentBias)+1)-Exponent); end; end else if Exponent>(Float32ExponentBias+Float5E5ExponentBias) then begin // |x| > 2^15, overflow, an existing INF, or NaN if Exponent=((1 shl Float32ExponentBits)-1) then begin if Mantissa<>0 then begin // Return allows -NaN to return as NaN even if there is no sign bit. result:=((1 shl (Float5E5ExponentBits+Float5E5MantissaBits))-1) or ((CastedValue shr (Float32Bits-Float5E5Bits)) and (1 shl (Float32MantissaBits+Float32ExponentBits))); exit; end else begin result:=((1 shl Float5E5ExponentBits)-1) shl Float5E5MantissaBits; end; end else begin result:=((((1 shl Float5E5ExponentBits)-1) shl Float5E5MantissaBits)-(1 shl Float5E5MantissaBits)) or Float5E5MantissaMask; end; end else begin result:=((Exponent-(Float32ExponentBias-Float5E5ExponentBias)) shl Float5E5MantissaBits) or Mantissa; end; if (CastedValue and (1 shl (Float32MantissaBits+Float32ExponentBits)))<>0 then begin // Clamp negative value result:=0; end; end; function Float32ToFloat11(const pValue:TpvFloat):TpvUInt32; const EXPONENT_BIAS=15; EXPONENT_BITS=$1f; EXPONENT_SHIFT=6; MANTISSA_BITS=$3f; MANTISSA_SHIFT=23-EXPONENT_SHIFT; MAX_EXPONENT=EXPONENT_BITS shl EXPONENT_SHIFT; var CastedValue:TpvUInt32 absolute pValue; Sign:TpvUInt32; Exponent,Mantissa:TpvInt32; begin Sign:=CastedValue shr 31; Exponent:=TpvInt32(TpvUInt32((CastedValue and $7f800000) shr 23))-127; Mantissa:=CastedValue and $007fffff; if Exponent=128 then begin // Infinity or NaN (* From the GL_EXT_packed_float spec: * "Additionally: negative infinity is converted to zero; positive * infinity is converted to positive infinity; and both positive and * negative NaN are converted to positive NaN." *) if Mantissa<>0 then begin result:=MAX_EXPONENT or 1; // NaN end else begin if Sign<>0 then begin result:=0; // 0.0 end else begin result:=MAX_EXPONENT; // Infinity end; end; end else if Sign<>0 then begin result:=0; end else if pValue>65024.0 then begin (* From the GL_EXT_packed_float spec: * "Likewise, finite positive values greater than 65024 (the maximum * finite representable unsigned 11-bit floating-point value) are * converted to 65024." *) result:=(30 shl EXPONENT_SHIFT) or 63; end else if Exponent>-15 then begin result:=((Exponent+EXPONENT_BIAS) shl EXPONENT_SHIFT) or (Mantissa shr MANTISSA_SHIFT); end else begin result:=0; end; end; function Float32ToFloat10(const pValue:TpvFloat):TpvUInt32; const EXPONENT_BIAS=15; EXPONENT_BITS=$1f; EXPONENT_SHIFT=5; MANTISSA_BITS=$1f; MANTISSA_SHIFT=23-EXPONENT_SHIFT; MAX_EXPONENT=EXPONENT_BITS shl EXPONENT_SHIFT; var CastedValue:TpvUInt32 absolute pValue; Sign:TpvUInt32; Exponent,Mantissa:TpvInt32; begin Sign:=CastedValue shr 31; Exponent:=TpvInt32(TpvUInt32((CastedValue and $7f800000) shr 23))-127; Mantissa:=CastedValue and $007fffff; if Exponent=128 then begin // Infinity or NaN (* From the GL_EXT_packed_float spec: * "Additionally: negative infinity is converted to zero; positive * infinity is converted to positive infinity; and both positive and * negative NaN are converted to positive NaN." *) if Mantissa<>0 then begin result:=MAX_EXPONENT or 1; // NaN end else begin if Sign<>0 then begin result:=0; // 0.0 end else begin result:=MAX_EXPONENT; // Infinity end; end; end else if Sign<>0 then begin result:=0; end else if pValue>64512.0 then begin (* From the GL_EXT_packed_float spec: * "Likewise, finite positive values greater than 64512 (the maximum * finite representable unsigned 11-bit floating-point value) are * converted to 64512." *) result:=(30 shl EXPONENT_SHIFT) or 31; end else if Exponent>-15 then begin result:=((Exponent+EXPONENT_BIAS) shl EXPONENT_SHIFT) or (Mantissa shr MANTISSA_SHIFT); end else begin result:=0; end; end; function ConvertRGB32FToR11FG11FB10F(const r,g,b:TpvFloat):TpvUInt32; {$ifdef CAN_INLINE}inline;{$endif} begin //result:=(PackFP32FloatToM6E5Float(r) and $7ff) or ((PackFP32FloatToM6E5Float(g) and $7ff) shl 11) or ((PackFP32FloatToM5E5Float(b) and $3ff) shl 22); result:=(Float32ToFloat11(r) and $7ff) or ((Float32ToFloat11(g) and $7ff) shl 11) or ((Float32ToFloat10(b) and $3ff) shl 22); end; function PackTangentSpace(const aTangent,aBitangent,aNormal:TpvVector3):TpvPackedTangentSpace; var q:TpvQuaternion; begin q:=TpvMatrix3x3.Create(aTangent,aBitangent,aNormal).ToQTangent; result.x:=Min(Max((round(q.x*127)+128),0),255); result.y:=Min(Max((round(q.y*127)+128),0),255); result.z:=Min(Max((round(q.z*127)+128),0),255); result.w:=Min(Max((round(q.w*127)+128),0),255); end; { begin result.x:=Min(Max((round((ArcSin(aNormal.z)/PI)*127)+128),0),255); result.y:=Min(Max((round((ArcTan2(aNormal.y,aNormal.x)/PI)*127)+128),0),255); result.z:=Min(Max((round((ArcSin(aTangent.z)/PI)*127)+128),0),255); result.w:=Min(Max((round((ArcTan2(aTangent.y,aTangent.x)/PI)*127)+128),0),255); end;//} procedure UnpackTangentSpace(const aPackedTangentSpace:TpvPackedTangentSpace;out aTangent,aBitangent,aNormal:TpvVector3); var q:TpvQuaternion; m:TpvMatrix3x3; begin q.x:=(aPackedTangentSpace.x-128)/127; q.y:=(aPackedTangentSpace.y-128)/127; q.z:=(aPackedTangentSpace.z-128)/127; q.w:=(aPackedTangentSpace.w-128)/127; m:=TpvMatrix3x3.CreateFromQTangent(q); aTangent.x:=m[0,0]; aTangent.y:=m[0,1]; aTangent.z:=m[0,2]; aBitangent.x:=m[1,0]; aBitangent.y:=m[1,1]; aBitangent.z:=m[1,2]; aNormal.x:=m[2,0]; aNormal.y:=m[2,1]; aNormal.z:=m[2,2]; end; {var Latitude,Longitude:single; begin Latitude:=((aPackedTangentSpace.x-128)/127)*PI; Longitude:=((aPackedTangentSpace.y-128)/127)*PI; aNormal.x:=cos(Latitude)*cos(Longitude); aNormal.y:=cos(Latitude)*sin(Longitude); aNormal.z:=sin(Latitude); Latitude:=((aPackedTangentSpace.z-128)/127)*PI; Longitude:=((aPackedTangentSpace.w-128)/127)*PI; aTangent.x:=cos(Latitude)*cos(Longitude); aTangent.y:=cos(Latitude)*sin(Longitude); aTangent.z:=sin(Latitude); aBitangent:=Vector3Norm(Vector3Cross(aNormal,aTangent)); end;//} function ConvertLinearToSRGB(const aColor:TpvVector3):TpvVector3; const InverseGamma=1.0/2.4; var ChannelIndex:TpvInt32; begin for ChannelIndex:=0 to 2 do begin if aColor[ChannelIndex]<0.0031308 then begin result[ChannelIndex]:=aColor[ChannelIndex]*12.92; end else if aColor[ChannelIndex]<1.0 then begin result[ChannelIndex]:=(Power(aColor[ChannelIndex],InverseGamma)*1.055)-0.055; end else begin result[ChannelIndex]:=1.0; end; end; end; function ConvertLinearToSRGB(const aColor:TpvVector4):TpvVector4; const InverseGamma=1.0/2.4; var ChannelIndex:TpvInt32; begin for ChannelIndex:=0 to 2 do begin if aColor[ChannelIndex]<0.0031308 then begin result[ChannelIndex]:=aColor[ChannelIndex]*12.92; end else if aColor[ChannelIndex]<1.0 then begin result[ChannelIndex]:=(Power(aColor[ChannelIndex],InverseGamma)*1.055)-0.055; end else begin result[ChannelIndex]:=1.0; end; end; result.a:=aColor.a; end; function ConvertSRGBToLinear(const aColor:TpvVector3):TpvVector3; const Inverse12d92=1.0/12.92; var ChannelIndex:TpvInt32; begin for ChannelIndex:=0 to 2 do begin if aColor[ChannelIndex]<0.04045 then begin result[ChannelIndex]:=aColor[ChannelIndex]*Inverse12d92; end else if aColor[ChannelIndex]<1.0 then begin result[ChannelIndex]:=Power((aColor[ChannelIndex]+0.055)/1.055,2.4); end else begin result[ChannelIndex]:=1.0; end; end; end; function ConvertSRGBToLinear(const aColor:TpvVector4):TpvVector4; const Inverse12d92=1.0/12.92; var ChannelIndex:TpvInt32; begin for ChannelIndex:=0 to 2 do begin if aColor[ChannelIndex]<0.04045 then begin result[ChannelIndex]:=aColor[ChannelIndex]*Inverse12d92; end else if aColor[ChannelIndex]<1.0 then begin result[ChannelIndex]:=Power((aColor[ChannelIndex]+0.055)/1.055,2.4); end else begin result[ChannelIndex]:=1.0; end; end; result.a:=aColor.a; end; function ConvertHSVToRGB(const aHSV:TpvVector3):TpvVector3; var Angle,Sector,FracSector,h,s,v,p,q,t:TpvScalar; IntSector:TpvInt32; begin s:=aHSV.y; if SameValue(s,0.0) then begin result:=aHSV.zzz; end else begin h:=aHSV.x; Angle:=frac(h)*360.0; Sector:=Angle/60.0; IntSector:=trunc(Sector); FracSector:=frac(Sector); v:=aHSV.z; p:=v*(1.0-s); q:=v*(1.0-(s*FracSector)); t:=v*(1.0-(s*(1.0-FracSector))); case IntSector of 0:begin result:=TpvVector3.InlineableCreate(v,t,p); end; 1:begin result:=TpvVector3.InlineableCreate(q,v,p); end; 2:begin result:=TpvVector3.InlineableCreate(p,v,t); end; 3:begin result:=TpvVector3.InlineableCreate(p,q,v); end; 4:begin result:=TpvVector3.InlineableCreate(t,p,v); end; else begin result:=TpvVector3.InlineableCreate(v,p,q); end; end; end; end; function ConvertRGBToHSV(const aRGB:TpvVector3):TpvVector3; var MinValue,MaxValue,Delta,h,s,v:TpvScalar; begin MinValue:=Min(aRGB.x,Min(aRGB.y,aRGB.z)); MaxValue:=Max(aRGB.x,Max(aRGB.y,aRGB.z)); v:=MaxValue; Delta:=MaxValue-MinValue; if Delta<1e-5 then begin result:=TpvVector3.InlineableCreate(0.0,0.0,v); end else if MaxValue>0.0 then begin s:=Delta/MaxValue; if SameValue(aRGB.x,MaxValue) then begin h:=(aRGB.y-aRGB.z)/Delta; end else if SameValue(aRGB.y,MaxValue) then begin h:=2.0+((aRGB.z-aRGB.x)/Delta); end else begin h:=4.0+((aRGB.x-aRGB.y)/Delta); end; h:=(h*60.0); if h<0.0 then begin h:=h+360.0; end else if h>360.0 then begin h:=h-360.0; end; h:=h/360.0; result:=TpvVector3.InlineableCreate(h,s,v); end else begin result:=TpvVector3.InlineableCreate(-1.0,0.0,v); end; end; constructor TpvVector2Property.Create(const aVector:PpvVector2); begin inherited Create; fVector:=aVector; fOnChange:=nil; end; destructor TpvVector2Property.Destroy; begin inherited Destroy; end; function TpvVector2Property.GetX:TpvScalar; begin result:=fVector^.x; end; function TpvVector2Property.GetY:TpvScalar; begin result:=fVector^.y; end; function TpvVector2Property.GetVector:TpvVector2; begin result:=fVector^; end; procedure TpvVector2Property.SetX(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.x<>aNewValue) then begin fVector^.x:=aNewValue; fOnChange(self); end else begin fVector^.x:=aNewValue; end; end; procedure TpvVector2Property.SetY(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.y<>aNewValue) then begin fVector^.y:=aNewValue; fOnChange(self); end else begin fVector^.y:=aNewValue; end; end; procedure TpvVector2Property.SetVector(const aNewVector:TpvVector2); begin if assigned(fOnChange) and ((fVector^.x<>aNewVector.x) or (fVector^.y<>aNewVector.y)) then begin fVector^:=aNewVector; fOnChange(self); end else begin fVector^:=aNewVector; end; end; constructor TpvVector3Property.Create(const aVector:PpvVector3); begin inherited Create; fVector:=aVector; fOnChange:=nil; end; destructor TpvVector3Property.Destroy; begin inherited Destroy; end; function TpvVector3Property.GetX:TpvScalar; begin result:=fVector^.x; end; function TpvVector3Property.GetY:TpvScalar; begin result:=fVector^.y; end; function TpvVector3Property.GetZ:TpvScalar; begin result:=fVector^.z; end; function TpvVector3Property.GetVector:TpvVector3; begin result:=fVector^; end; procedure TpvVector3Property.SetX(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.x<>aNewValue) then begin fVector^.x:=aNewValue; fOnChange(self); end else begin fVector^.x:=aNewValue; end; end; procedure TpvVector3Property.SetY(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.y<>aNewValue) then begin fVector^.y:=aNewValue; fOnChange(self); end else begin fVector^.y:=aNewValue; end; end; procedure TpvVector3Property.SetZ(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.z<>aNewValue) then begin fVector^.z:=aNewValue; fOnChange(self); end else begin fVector^.z:=aNewValue; end; end; procedure TpvVector3Property.SetVector(const aNewVector:TpvVector3); begin if assigned(fOnChange) and ((fVector^.x<>aNewVector.x) or (fVector^.y<>aNewVector.y) or (fVector^.z<>aNewVector.z)) then begin fVector^:=aNewVector; fOnChange(self); end else begin fVector^:=aNewVector; end; end; constructor TpvVector4Property.Create(const aVector:PpvVector4); begin inherited Create; fVector:=aVector; fOnChange:=nil; end; destructor TpvVector4Property.Destroy; begin inherited Destroy; end; function TpvVector4Property.GetX:TpvScalar; begin result:=fVector^.x; end; function TpvVector4Property.GetY:TpvScalar; begin result:=fVector^.y; end; function TpvVector4Property.GetZ:TpvScalar; begin result:=fVector^.z; end; function TpvVector4Property.GetW:TpvScalar; begin result:=fVector^.w; end; function TpvVector4Property.GetVector:TpvVector4; begin result:=fVector^; end; procedure TpvVector4Property.SetX(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.x<>aNewValue) then begin fVector^.x:=aNewValue; fOnChange(self); end else begin fVector^.x:=aNewValue; end; end; procedure TpvVector4Property.SetY(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.y<>aNewValue) then begin fVector^.y:=aNewValue; fOnChange(self); end else begin fVector^.y:=aNewValue; end; end; procedure TpvVector4Property.SetZ(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.z<>aNewValue) then begin fVector^.z:=aNewValue; fOnChange(self); end else begin fVector^.z:=aNewValue; end; end; procedure TpvVector4Property.SetW(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.w<>aNewValue) then begin fVector^.w:=aNewValue; fOnChange(self); end else begin fVector^.w:=aNewValue; end; end; procedure TpvVector4Property.SetVector(const aNewVector:TpvVector4); begin if assigned(fOnChange) and ((fVector^.x<>aNewVector.x) or (fVector^.y<>aNewVector.y) or (fVector^.z<>aNewVector.z) or (fVector^.w<>aNewVector.w)) then begin fVector^:=aNewVector; fOnChange(self); end else begin fVector^:=aNewVector; end; end; constructor TpvQuaternionProperty.Create(const AQuaternion:PpvQuaternion); begin inherited Create; fQuaternion:=AQuaternion; fOnChange:=nil; end; destructor TpvQuaternionProperty.Destroy; begin inherited Destroy; end; function TpvQuaternionProperty.GetX:TpvScalar; begin result:=fQuaternion^.x; end; function TpvQuaternionProperty.GetY:TpvScalar; begin result:=fQuaternion^.y; end; function TpvQuaternionProperty.GetZ:TpvScalar; begin result:=fQuaternion^.z; end; function TpvQuaternionProperty.GetW:TpvScalar; begin result:=fQuaternion^.w; end; function TpvQuaternionProperty.GetQuaternion:TpvQuaternion; begin result:=fQuaternion^; end; procedure TpvQuaternionProperty.SetX(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.x<>aNewValue) then begin fQuaternion^.x:=aNewValue; fOnChange(self); end else begin fQuaternion^.x:=aNewValue; end; end; procedure TpvQuaternionProperty.SetY(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.y<>aNewValue) then begin fQuaternion^.y:=aNewValue; fOnChange(self); end else begin fQuaternion^.y:=aNewValue; end; end; procedure TpvQuaternionProperty.SetZ(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.z<>aNewValue) then begin fQuaternion^.z:=aNewValue; fOnChange(self); end else begin fQuaternion^.z:=aNewValue; end; end; procedure TpvQuaternionProperty.SetW(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.w<>aNewValue) then begin fQuaternion^.w:=aNewValue; fOnChange(self); end else begin fQuaternion^.w:=aNewValue; end; end; procedure TpvQuaternionProperty.SetQuaternion(const aNewQuaternion:TpvQuaternion); begin if assigned(fOnChange) and ((fQuaternion^.x<>aNewQuaternion.x) or (fQuaternion^.y<>aNewQuaternion.y) or (fQuaternion^.z<>aNewQuaternion.z) or (fQuaternion^.w<>aNewQuaternion.w)) then begin fQuaternion^:=aNewQuaternion; fOnChange(self); end else begin fQuaternion^:=aNewQuaternion; end; end; constructor TpvAngleProperty.Create(const aRadianAngle:PpvScalar); begin inherited Create; fRadianAngle:=aRadianAngle; fOnChange:=nil; end; destructor TpvAngleProperty.Destroy; begin inherited Destroy; end; function TpvAngleProperty.GetAngle:TpvScalar; begin result:=fRadianAngle^*RAD2DEG; end; function TpvAngleProperty.GetRadianAngle:TpvScalar; begin result:=fRadianAngle^; end; procedure TpvAngleProperty.SetAngle(const aNewValue:TpvScalar); begin SetRadianAngle(aNewValue*DEG2RAD); end; procedure TpvAngleProperty.SetRadianAngle(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fRadianAngle^<>aNewValue) then begin fRadianAngle^:=aNewValue; fOnChange(self); end else begin fRadianAngle^:=aNewValue; end; end; constructor TpvRotation3DProperty.Create(const AQuaternion:PpvQuaternion); begin inherited Create; fQuaternion:=AQuaternion; fOnChange:=nil; end; destructor TpvRotation3DProperty.Destroy; begin inherited Destroy; end; function TpvRotation3DProperty.GetX:TpvScalar; begin result:=fQuaternion^.x; end; function TpvRotation3DProperty.GetY:TpvScalar; begin result:=fQuaternion^.y; end; function TpvRotation3DProperty.GetZ:TpvScalar; begin result:=fQuaternion^.z; end; function TpvRotation3DProperty.GetW:TpvScalar; begin result:=fQuaternion^.w; end; function TpvRotation3DProperty.GetPitch:TpvScalar; begin result:=fQuaternion^.Normalize.ToEuler.Pitch*RAD2DEG; end; function TpvRotation3DProperty.GetYaw:TpvScalar; begin result:=fQuaternion^.Normalize.ToEuler.Yaw*RAD2DEG; end; function TpvRotation3DProperty.GetRoll:TpvScalar; begin result:=fQuaternion^.Normalize.ToEuler.Roll*RAD2DEG; end; function TpvRotation3DProperty.GetQuaternion:TpvQuaternion; begin result:=fQuaternion^; end; procedure TpvRotation3DProperty.SetX(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.x<>aNewValue) then begin fQuaternion^.x:=aNewValue; fOnChange(self); end else begin fQuaternion^.x:=aNewValue; end; end; procedure TpvRotation3DProperty.SetY(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.y<>aNewValue) then begin fQuaternion^.y:=aNewValue; fOnChange(self); end else begin fQuaternion^.y:=aNewValue; end; end; procedure TpvRotation3DProperty.SetZ(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.z<>aNewValue) then begin fQuaternion^.z:=aNewValue; fOnChange(self); end else begin fQuaternion^.z:=aNewValue; end; end; procedure TpvRotation3DProperty.SetW(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fQuaternion^.w<>aNewValue) then begin fQuaternion^.w:=aNewValue; fOnChange(self); end else begin fQuaternion^.w:=aNewValue; end; end; procedure TpvRotation3DProperty.SetPitch(const aNewValue:TpvScalar); var Angles:TpvVector3; begin Angles:=fQuaternion^.Normalize.ToEuler; Angles.Pitch:=aNewValue*DEG2RAD; SetQuaternion(TpvQuaternion.CreateFromEuler(Angles)); end; procedure TpvRotation3DProperty.SetYaw(const aNewValue:TpvScalar); var Angles:TpvVector3; begin Angles:=fQuaternion^.Normalize.ToEuler; Angles.Yaw:=aNewValue*DEG2RAD; SetQuaternion(TpvQuaternion.CreateFromEuler(Angles)); end; procedure TpvRotation3DProperty.SetRoll(const aNewValue:TpvScalar); var Angles:TpvVector3; begin Angles:=fQuaternion^.Normalize.ToEuler; Angles.Roll:=aNewValue*DEG2RAD; SetQuaternion(TpvQuaternion.CreateFromEuler(Angles)); end; procedure TpvRotation3DProperty.SetQuaternion(const aNewQuaternion:TpvQuaternion); begin if assigned(fOnChange) and ((fQuaternion^.x<>aNewQuaternion.x) or (fQuaternion^.y<>aNewQuaternion.y) or (fQuaternion^.z<>aNewQuaternion.z) or (fQuaternion^.w<>aNewQuaternion.w)) then begin fQuaternion^:=aNewQuaternion; fOnChange(self); end else begin fQuaternion^:=aNewQuaternion; end; end; constructor TpvColorRGBProperty.Create(const aVector:PpvVector3); begin inherited Create; fVector:=aVector; fOnChange:=nil; end; destructor TpvColorRGBProperty.Destroy; begin inherited Destroy; end; function TpvColorRGBProperty.GetR:TpvScalar; begin result:=fVector^.r; end; function TpvColorRGBProperty.GetG:TpvScalar; begin result:=fVector^.g; end; function TpvColorRGBProperty.GetB:TpvScalar; begin result:=fVector^.b; end; function TpvColorRGBProperty.GetVector:TpvVector3; begin result:=fVector^; end; procedure TpvColorRGBProperty.SetR(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.r<>aNewValue) then begin fVector^.r:=aNewValue; fOnChange(self); end else begin fVector^.r:=aNewValue; end; end; procedure TpvColorRGBProperty.SetG(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.g<>aNewValue) then begin fVector^.g:=aNewValue; fOnChange(self); end else begin fVector^.g:=aNewValue; end; end; procedure TpvColorRGBProperty.SetB(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.b<>aNewValue) then begin fVector^.b:=aNewValue; fOnChange(self); end else begin fVector^.b:=aNewValue; end; end; procedure TpvColorRGBProperty.SetVector(const aNewVector:TpvVector3); begin if assigned(fOnChange) and ((fVector^.r<>aNewVector.r) or (fVector^.g<>aNewVector.g) or (fVector^.b<>aNewVector.b)) then begin fVector^:=aNewVector; fOnChange(self); end else begin fVector^:=aNewVector; end; end; constructor TpvColorRGBAProperty.Create(const aVector:PpvVector4); begin inherited Create; fVector:=aVector; fOnChange:=nil; end; destructor TpvColorRGBAProperty.Destroy; begin inherited Destroy; end; function TpvColorRGBAProperty.GetR:TpvScalar; begin result:=fVector^.r; end; function TpvColorRGBAProperty.GetG:TpvScalar; begin result:=fVector^.g; end; function TpvColorRGBAProperty.GetB:TpvScalar; begin result:=fVector^.b; end; function TpvColorRGBAProperty.GetA:TpvScalar; begin result:=fVector^.a; end; function TpvColorRGBAProperty.GetVector:TpvVector4; begin result:=fVector^; end; procedure TpvColorRGBAProperty.SetR(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.r<>aNewValue) then begin fVector^.r:=aNewValue; fOnChange(self); end else begin fVector^.r:=aNewValue; end; end; procedure TpvColorRGBAProperty.SetG(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.g<>aNewValue) then begin fVector^.g:=aNewValue; fOnChange(self); end else begin fVector^.g:=aNewValue; end; end; procedure TpvColorRGBAProperty.SetB(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.b<>aNewValue) then begin fVector^.b:=aNewValue; fOnChange(self); end else begin fVector^.b:=aNewValue; end; end; procedure TpvColorRGBAProperty.SetA(const aNewValue:TpvScalar); begin if assigned(fOnChange) and (fVector^.a<>aNewValue) then begin fVector^.a:=aNewValue; fOnChange(self); end else begin fVector^.a:=aNewValue; end; end; procedure TpvColorRGBAProperty.SetVector(const aNewVector:TpvVector4); begin if assigned(fOnChange) and ((fVector^.r<>aNewVector.r) or (fVector^.g<>aNewVector.g) or (fVector^.b<>aNewVector.b) or (fVector^.a<>aNewVector.a)) then begin fVector^:=aNewVector; fOnChange(self); end else begin fVector^:=aNewVector; end; end; function SolveQuadratic(const a,b,c:TpvDouble;out r0,r1:TpvDouble):TpvSizeInt; var d:TpvDouble; begin if IsZero(a) or (abs(b)>(abs(a)*1e+12)) then begin if IsZero(b) then begin if IsZero(c) then begin result:=-1; end else begin result:=0; end; end else begin r0:=(-c)/b; result:=1; end; end else begin d:=sqr(b)+((4.0*a)*c); if IsZero(d) then begin r0:=(-b)/(2.0*a); result:=1; end else if d>0.0 then begin d:=sqrt(d); r0:=((-b)+d)/(2.0*a); r1:=((-b)-d)/(2.0*a); result:=2; end else begin result:=0; end; end; end; function SolveCubic(const a,b,c,d:TpvDouble;out r0,r1,r2:TpvDouble):TpvSizeInt; const ONE_OVER_3=1.0/3.0; ONE_OVER_9=1.0/9.0; ONE_OVER_54=1.0/9.0; var a0,a1,a2,o,q,r,d_,u,Theta,t:TpvDouble; begin if IsZero(a) then begin result:=SolveQuadratic(b,c,d,r0,r1); end else begin result:=0; a2:=b/a; a1:=c/a; a0:=d/a; q:=(a1*ONE_OVER_3)-(sqr(a2)*ONE_OVER_9); r:=((27.0*a0)+(a2*((2.0*sqr(a2))-(9.0*a1))))*ONE_OVER_54; d_:=(q*sqr(q))+sqr(r); o:=(-ONE_OVER_3)*a2; if IsZero(d_) then begin if IsZero(r) then begin r0:=0.0; result:=1; end else begin u:=Power(-r,ONE_OVER_3); r0:=(2.0*u)+o; r1:=-u; result:=2; end; end else if d>0 then begin d_:=sqrt(d_); r0:=(Power(d_-r,ONE_OVER_3)-Power(d_+r,ONE_OVER_3))+o; result:=1; end else begin Theta:=ArcCos((-r)/sqrt(-(sqr(q)*q)))*ONE_OVER_3; t:=2*sqrt(-q); r0:=(t*cos(Theta))+o; r1:=((-t)*cos(Theta+(PI*ONE_OVER_3)))+o; r2:=((-t)*cos(Theta-(PI*ONE_OVER_3)))+o; result:=3; end; end; end; function SolveQuartic(const a,b,c,d,e:TpvDouble;out r0,r1,r2,r3:TpvDouble):TpvSizeInt; var Index,OtherIndex,CubSols:TpvSizeInt; a_,b_,c_,d_,y,rs,tmp,ds,es:TpvDouble; SolValid:array[0..3] of boolean; Results:array[0..3] of TpvDouble; CubicSols:array[0..2] of TpvDouble; begin if IsZero(a) then begin result:=SolveCubic(b,c,d,e,r0,r1,r2); end else begin SolValid[0]:=false; SolValid[1]:=false; SolValid[2]:=false; SolValid[3]:=false; a_:=b/a; b_:=c/a; c_:=d/a; d_:=e/a; CubSols:=SolveCubic(1.0, -b, (a_*c_)-(4.0*d_), (((-sqr(a_))*d_)+((4.0*b_)*d_))-sqr(c_), CubicSols[0], CubicSols[1], CubicSols[2]); if CubSols>0 then begin result:=0; y:=CubicSols[0]; rs:=((sqr(a_)*0.25)-b_)+y; if IsZero(rs) then begin tmp:=sqr(y)-(4.0*d_); if tmp<0 then begin exit; end; ds:=(((3.0*sqr(a_))*0.25)-(2*b))+(2.0*tmp); es:=(((3.0*sqr(a_))*0.25)-(2*b))-(2.0*tmp); if ds>=0.0 then begin ds:=sqrt(ds); SolValid[0]:=true; SolValid[1]:=true; inc(result,2); Results[0]:=((-0.25)*a)-(ds*0.5); Results[1]:=((-0.25)*a)+(ds*0.5); end; if es>=0.0 then begin es:=sqrt(es); SolValid[2]:=true; SolValid[3]:=true; inc(result,2); Results[2]:=((-0.25)*a)-(es*0.5); Results[3]:=((-0.25)*a)+(es*0.5); end; end else if rs>0.0 then begin rs:=sqrt(rs); ds:=(((0.75*sqr(a_))-rs)-(2.0*b_))+((((4.0*(a_*b_))-(8.0*c_))-(sqr(a_)*a_))/(4.0*rs)); es:=(((0.75*sqr(a_))-rs)-(2.0*b_))-((((4.0*(a_*b_))-(8.0*c_))-(sqr(a_)*a_))/(4.0*rs)); if ds>=0.0 then begin ds:=sqrt(ds); SolValid[0]:=true; SolValid[1]:=true; inc(result,2); Results[0]:=(((-0.25)*a)+(rs*0.5))-(ds*0.5); Results[1]:=(((-0.25)*a)+(rs*0.5))+(ds*0.5); end; if es>=0.0 then begin es:=sqrt(es); SolValid[2]:=true; SolValid[3]:=true; inc(result,2); Results[2]:=(((-0.25)*a)-(rs*0.5))-(es*0.5); Results[3]:=(((-0.25)*a)-(rs*0.5))+(es*0.5); end; OtherIndex:=0; for Index:=0 to result-1 do begin while (OtherIndex<4) and not SolValid[OtherIndex] do begin inc(OtherIndex); end; Results[Index]:=Results[OtherIndex]; inc(OtherIndex); end; r0:=Results[0]; r1:=Results[1]; r2:=Results[2]; r3:=Results[3]; end else begin result:=0; end; end else begin result:=0; end; end; end; function GetRootsDerivative(const aCoefs:array of TpvDouble):TpvDoubleDynamicArray; var Index:TpvSizeInt; begin result:=nil; SetLength(result,length(aCoefs)-1); for Index:=0 to length(aCoefs)-2 do begin result[Index]:=aCoefs[Index+1]*(Index+1); end; end; function PolyEval(const aCoefs:array of TpvDouble;const aValue:TpvDouble):TpvDouble; var Index:TpvSizeInt; begin result:=0.0; for Index:=0 to length(aCoefs)-1 do begin result:=(result*aValue)+aCoefs[Index]; end; end; function GetRootBisection(const aCoefs:array of TpvDouble;aMin,aMax:TpvDouble;out aResult:TpvDouble):Boolean; const TOLERANCE=1e-6; ACCURACY=6; var MinValue,MaxValue,Value,t0,t1:TpvDouble; Iterations,Index:TpvSizeInt; begin MinValue:=PolyEval(aCoefs,aMin); MaxValue:=PolyEval(aCoefs,aMax); if abs(MinValue)<TOLERANCE then begin aResult:=MinValue; result:=true; end else if abs(MaxValue)<TOLERANCE then begin aResult:=MaxValue; result:=true; end else if (MinValue*MaxValue)<=0.0 then begin t0:=ln(aMax-aMin); t1:=ln(10.0)*ACCURACY; Iterations:=Trunc(Ceil((t0+t1)/ln(2))); for Index:=0 to Iterations-1 do begin aResult:=(aMin+aMax)*0.5; Value:=PolyEval(aCoefs,aResult); if abs(Value)<TOLERANCE then begin result:=true; exit; end; if (Value*MinValue)<0.0 then begin aMax:=aResult; MaxValue:=Value; end else begin aMin:=aResult; MinValue:=Value; end; end; result:=false; end else begin result:=false; end; end; function SolveRootsInInterval(const aCoefs:array of TpvDouble;const aMin,aMax:TpvDouble):TpvDoubleDynamicArray; var Derivative,DerivativeRoots:TpvDoubleDynamicArray; Count,Index:TpvSizeInt; Root:TpvDouble; begin result:=nil; case length(aCoefs) of 0:begin end; 1..2:begin if GetRootBisection(aCoefs,aMin,aMax,Root) then begin SetLength(result,1); result[0]:=Root; end; end; else begin Count:=0; try SetLength(result,length(aCoefs)+2); Derivative:=GetRootsDerivative(aCoefs); DerivativeRoots:=SolveRootsInInterval(Derivative,aMin,aMax); if length(DerivativeRoots)>0 then begin if GetRootBisection(aCoefs,aMin,DerivativeRoots[0],Root) then begin result[Count]:=Root; inc(Count); end; for Index:=0 to length(DerivativeRoots)-2 do begin if GetRootBisection(aCoefs,DerivativeRoots[Index],DerivativeRoots[Index+1],Root) then begin result[Count]:=Root; inc(Count); end; end; if GetRootBisection(aCoefs,DerivativeRoots[length(DerivativeRoots)-1],aMax,Root) then begin result[Count]:=Root; inc(Count); end; end else begin if GetRootBisection(aCoefs,aMin,aMax,Root) then begin result[Count]:=Root; inc(Count); end; end; finally SetLength(result,Count); end; end; end; end; constructor TpvPolynomial.Create(const aCoefs:array of TpvDouble); begin SetLength(Coefs,length(aCoefs)); if length(aCoefs)>0 then begin Move(aCoefs[0],Coefs[0],length(aCoefs)*SizeOf(TpvDouble)); end; end; function TpvPolynomial.GetDegree:TpvSizeInt; begin result:=length(Coefs)-1; end; function TpvPolynomial.Eval(const aValue:TpvDouble):TpvDouble; var Index:TpvSizeInt; begin result:=0.0; for Index:=0 to length(Coefs)-1 do begin result:=(result*aValue)+Coefs[Index]; end; end; procedure TpvPolynomial.SimplifyEquals(const aThreshold:TpvDouble=1e-12); var Index,NewLength:TpvSizeInt; begin NewLength:=length(Coefs); for Index:=length(Coefs)-1 downto 0 do begin if Coefs[Index]<=aThreshold then begin NewLength:=Index; end else begin break; end; end; if length(Coefs)<>NewLength then begin SetLength(Coefs,NewLength); end; end; function TpvPolynomial.GetDerivative:TpvPolynomial; var Index:TpvSizeInt; begin result.Coefs:=nil; SetLength(result.Coefs,length(Coefs)-1); for Index:=1 to length(Coefs)-1 do begin result.Coefs[Index-1]:=Coefs[Index]*Index; end; end; function TpvPolynomial.GetLinearRoots:TpvDoubleDynamicArray; begin result:=nil; if not IsZero(Coefs[1]) then begin SetLength(result,1); result[0]:=-(Coefs[0]/Coefs[1]); end; end; function TpvPolynomial.GetQuadraticRoots:TpvDoubleDynamicArray; var a,b,c,d:TpvDouble; begin result:=nil; if GetDegree=2 then begin a:=Coefs[2]; b:=Coefs[1]; c:=Coefs[0]; d:=sqr(b)-(4.0*c); if IsZero(d) then begin SetLength(result,1); result[0]:=(-0.5)*b; end else if d>0.0 then begin d:=sqrt(d); SetLength(result,2); result[0]:=((-b)+d)*0.5; result[1]:=((-b)-d)*0.5; end; end; end; function TpvPolynomial.GetCubicRoots:TpvDoubleDynamicArray; var c3,c2,c1,c0,a,b,Offset,d,hb,t,r,Distance,Angle,Cosinus,Sinus,Sqrt3:TpvDouble; begin result:=nil; if GetDegree=3 then begin c3:=Coefs[3]; c2:=Coefs[2]/c3; c1:=Coefs[1]/c3; c0:=Coefs[0]/c3; a:=((3.0*c1)-sqr(c2))/3.0; b:=((((2.0*sqr(c2))*c2)-((9.0*c1)*c2))+(27.0*c0))/27.0; Offset:=c2/3.0; d:=(sqr(b)*0.25)+((sqr(a)*a)/27.0); hb:=b*0.5; if IsZero(abs(d)) then begin if hb>=0.0 then begin t:=-Power(hb,1.0/3.0); end else begin t:=Power(-hb,1.0/3.0); end; SetLength(result,2); result[0]:=(2.0*t)-Offset; result[1]:=(-t)-Offset; end else if d>0.0 then begin d:=sqrt(d); t:=(-hb)+d; if t>=0.0 then begin r:=Power(t,1.0/3.0); end else begin r:=Power(-t,1.0/3.0); end; t:=(-hb)-d; if t>=0.0 then begin r:=r+Power(t,1.0/3.0); end else begin r:=r-Power(-t,1.0/3.0); end; SetLength(result,1); result[0]:=r-Offset; end else if d<0.0 then begin Distance:=sqrt((-a)/3.0); Angle:=ArcTan2(sqrt(-d),-hb)/3.0; Cosinus:=cos(Angle); Sinus:=sin(Angle); Sqrt3:=sqrt(3.0); SetLength(result,3); result[0]:=((2.0*Distance)*Cosinus)-Offset; result[1]:=((-Distance)*(Cosinus+(Sqrt3*Sinus)))-Offset; result[2]:=((-Distance)*(Cosinus-(Sqrt3*Sinus)))-Offset; end; end; end; function TpvPolynomial.GetQuarticRoots:TpvDoubleDynamicArray; var c4,c3,c2,c1,c0,y,d,f,t2,t1,Plus,Minus:TpvDouble; ResolveRoots:TpvDoubleDynamicArray; begin result:=nil; if GetDegree=4 then begin c4:=Coefs[4]; c3:=Coefs[3]/c4; c2:=Coefs[2]/c4; c1:=Coefs[1]/c4; c0:=Coefs[0]/c4; ResolveRoots:=(TpvPolynomial.Create([1.0,-c2,(c3*c1)-(4.0*c0),((((-c3)*c3)*c0)+((4.0*c2)*c0))-sqr(c1)])).GetCubicRoots; y:=ResolveRoots[0]; d:=((sqr(c3)*0.25)-c2)+y; if IsZero(abs(d)) then begin t2:=sqr(y)-(4.0*c0); if (t2>=0.0) or IsZero(t2) then begin if t2<0.0 then begin t2:=0.0; end; t2:=2.0*sqrt(t2); t1:=((3.0*c3)*c3)-(2.0*c2); d:=t1+t2; if (d>0.0) and not IsZero(d) then begin d:=sqrt(d); SetLength(result,2); result[0]:=(c3*(-0.25))+(d*0.5); result[1]:=(c3*(-0.25))-(d*0.5); end; d:=t1-t2; if (d>0.0) and not IsZero(d) then begin d:=sqrt(d); SetLength(result,2); result[0]:=(c3*(-0.25))+(d*0.5); result[1]:=(c3*(-0.25))-(d*0.5); end; end; end else if d>0.0 then begin d:=sqrt(d); t1:=((((3.0*c3)*c3)*0.25)-sqr(d))-(2.0*c2); t2:=((((4.0*c3)*c2)-(8.0*c1))-((c3*c3)*c3))/(4.0*d); Plus:=t1+t2; Minus:=t1-t2; if not IsZero(Plus) then begin f:=sqrt(Plus); if not IsZero(Minus) then begin SetLength(result,4); result[0]:=(c3*(-0.25))+((d+f)*0.5); result[1]:=(c3*(-0.25))+((d-f)*0.5); f:=sqrt(Minus); result[2]:=(c3*(-0.25))+((f-d)*0.5); result[3]:=(c3*(-0.25))-((f+d)*0.5); end else begin SetLength(result,2); result[0]:=(c3*(-0.25))+((d+f)*0.5); result[1]:=(c3*(-0.25))+((d-f)*0.5); end; end else if not IsZero(Minus) then begin f:=sqrt(Minus); SetLength(result,2); result[0]:=(c3*(-0.25))+((f-d)*0.5); result[1]:=(c3*(-0.25))-((f+d)*0.5); end; end else begin // No roots end; end; end; function TpvPolynomial.GetRoots:TpvDoubleDynamicArray; begin SimplifyEquals; case GetDegree of 0:begin result:=nil; end; 1:begin result:=GetLinearRoots; end; 2:begin result:=GetQuadraticRoots; end; 3:begin result:=GetCubicRoots; end; 4:begin result:=GetQuarticRoots; end; else begin result:=nil; end; end; end; function TpvPolynomial.Bisection(aMin,aMax:TpvDouble;out aResult:TpvDouble):Boolean; const TOLERANCE=1e-6; ACCURACY=6; var MinValue,MaxValue,Value,t0,t1:TpvDouble; Iterations,Index:TpvSizeInt; begin MinValue:=Eval(aMin); MaxValue:=Eval(aMax); if abs(MinValue)<TOLERANCE then begin aResult:=MinValue; result:=true; end else if abs(MaxValue)<TOLERANCE then begin aResult:=MaxValue; result:=true; end else if (MinValue*MaxValue)<=0.0 then begin t0:=ln(aMax-aMin); t1:=ln(10.0)*ACCURACY; Iterations:=Trunc(Ceil((t0+t1)/ln(2))); for Index:=0 to Iterations-1 do begin aResult:=(aMin+aMax)*0.5; Value:=Eval(aResult); if abs(Value)<TOLERANCE then begin result:=true; exit; end; if (Value*MinValue)<0.0 then begin aMax:=aResult; MaxValue:=Value; end else begin aMin:=aResult; MinValue:=Value; end; end; result:=true; end else begin result:=false; end; end; function TpvPolynomial.GetRootsInInterval(const aMin,aMax:TpvDouble):TpvDoubleDynamicArray; var Derivative:TpvPolynomial; DerivativeRoots:TpvDoubleDynamicArray; Count,Index:TpvSizeInt; Root:TpvDouble; begin result:=nil; case length(Coefs) of 0:begin end; 1..2:begin if Bisection(aMin,aMax,Root) then begin SetLength(result,1); result[0]:=Root; end; end; else begin Count:=0; try SetLength(result,length(Coefs)+2); Derivative:=GetDerivative; DerivativeRoots:=Derivative.GetRootsInInterval(aMin,aMax); if length(DerivativeRoots)>0 then begin if Bisection(aMin,DerivativeRoots[0],Root) then begin result[Count]:=Root; inc(Count); end; for Index:=0 to length(DerivativeRoots)-2 do begin if Bisection(DerivativeRoots[Index],DerivativeRoots[Index+1],Root) then begin result[Count]:=Root; inc(Count); end; end; if Bisection(DerivativeRoots[length(DerivativeRoots)-1],aMax,Root) then begin result[Count]:=Root; inc(Count); end; end else begin if Bisection(aMin,aMax,Root) then begin result[Count]:=Root; inc(Count); end; end; finally SetLength(result,Count); end; end; end; end; // 32-bit normal encoding from Journal of Computer Graphics Techniques Vol. 3, No. 2, 2014 function EncodeNormalAsUInt32(const aNormal:TpvVector3):TpvUInt32; var Projected0,Projected1:TpvUInt32; InversedL1Norm,Encoded0,Encoded1:TpvScalar; begin InversedL1Norm:=1.0/(abs(aNormal.x)+abs(aNormal.y)+abs(aNormal.z)); if aNormal.z<0.0 then begin Encoded0:=1.0-abs(aNormal.y*InversedL1Norm)*SignNonZero(aNormal.x); Encoded1:=1.0-abs(aNormal.x*InversedL1Norm)*SignNonZero(aNormal.y); end else begin Encoded0:=aNormal.x*InversedL1Norm; Encoded1:=aNormal.y*InversedL1Norm; end; Projected0:=((CastFloatToUInt32(Encoded0) and TpvUInt32($80000000)) shr 16) or ((CastFloatToUInt32((abs(Encoded0)+2.0)*0.5) and TpvUInt32($7fffff)) shr 8); Projected1:=((CastFloatToUInt32(Encoded1) and TpvUInt32($80000000)) shr 16) or ((CastFloatToUInt32((abs(Encoded1)+2.0)*0.5) and TpvUInt32($7fffff)) shr 8); if (Projected0 and $7fff)=0 then begin Projected0:=0; end; if (Projected1 and $7fff)=0 then begin Projected1:=0; end; result:=(Projected1 shl 16) or Projected0; end; function DecodeNormalFromUInt32(const aNormal:TpvUInt32):TpvVector3; var Projected0,Projected1:TpvUInt32; t:TpvScalar; begin Projected0:=aNormal and TpvUInt32($ffff); Projected1:=aNormal shr 16; result.x:=CastUInt32ToFloat(CastFloatToUInt32((CastUInt32ToFloat(TpvUInt32($3f800000) or ((Projected0 and TpvUInt32($7fff)) shl 8))*2.0)-2.0) or ((Projected0 and TpvUInt32($8000)) shl 16)); result.y:=CastUInt32ToFloat(CastFloatToUInt32((CastUInt32ToFloat(TpvUInt32($3f800000) or ((Projected1 and TpvUInt32($7fff)) shl 8))*2.0)-2.0) or ((Projected1 and TpvUInt32($8000)) shl 16)); result.z:=1.0-(abs(result.x)+abs(result.y)); if result.z<0.0 then begin t:=result.x; result.x:=(1.0-abs(result.y))*SignNonZero(t); result.y:=(1.0-abs(t))*SignNonZero(result.y); end; result:=result.Normalize; end; initialization end.
unit TextEditor.LeftMargin.LineState; interface uses System.Classes; type TTextEditorLeftMarginLineState = class(TPersistent) strict private FOnChange: TNotifyEvent; FVisible: Boolean; FWidth: Integer; procedure DoChange; procedure SetOnChange(const AValue: TNotifyEvent); procedure SetVisible(const AValue: Boolean); procedure SetWidth(const AValue: Integer); public constructor Create; procedure Assign(ASource: TPersistent); override; procedure ChangeScale(const AMultiplier, ADivider: Integer); property OnChange: TNotifyEvent read FOnChange write SetOnChange; published property Visible: Boolean read FVisible write SetVisible default True; property Width: Integer read FWidth write SetWidth default 2; end; implementation uses Winapi.Windows; constructor TTextEditorLeftMarginLineState.Create; begin inherited; FVisible := True; FWidth := 2; end; procedure TTextEditorLeftMarginLineState.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorLeftMarginLineState) then with ASource as TTextEditorLeftMarginLineState do begin Self.FVisible := FVisible; Self.FWidth := FWidth; Self.DoChange; end else inherited Assign(ASource); end; procedure TTextEditorLeftMarginLineState.ChangeScale(const AMultiplier, ADivider: Integer); var LNumerator: Integer; begin LNumerator := (AMultiplier div ADivider) * ADivider; FWidth := MulDiv(FWidth, LNumerator, ADivider); end; procedure TTextEditorLeftMarginLineState.SetOnChange(const AValue: TNotifyEvent); begin FOnChange := AValue; end; procedure TTextEditorLeftMarginLineState.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TTextEditorLeftMarginLineState.SetVisible(const AValue: Boolean); begin if FVisible <> AValue then begin FVisible := AValue; DoChange end; end; procedure TTextEditorLeftMarginLineState.SetWidth(const AValue: Integer); begin if FWidth <> AValue then begin FWidth := AValue; DoChange end; end; end.
PROGRAM Equation2(INPUT, OUTPUT); TYPE Koef = RECORD A, B, C: REAL END; Roots = RECORD X1, X2: REAL; Q: REAL END; VAR K: Koef; R: Roots; D: REAL; FUNCTION ReadKoefs(VAR F: TEXT; VAR Ko: Koef): BOOLEAN; BEGIN READ(F, Ko.A, Ko.B, Ko.C); IF Ko.A = 0 THEN ReadKoefs := FALSE ELSE ReadKoefs := TRUE END; PROCEDURE Discriminant(VAR Di: REAL; Ko: Koef); BEGIN Di := (Ko.B * Ko.B) - (4 * Ko.A * Ko.C); END; FUNCTION RootsEquation(VAR Ro: Roots; Di: REAL): INTEGER; BEGIN IF Di > 0 THEN BEGIN RootsEquation := 2; Ro.Q := 2 END ELSE IF Di = 0 THEN BEGIN RootsEquation := 1; Ro.Q := 1 END ELSE BEGIN RootsEquation := 0; Ro.Q := 0 END END; PROCEDURE FindingRoots(VAR Ro: Roots; Ko: Koef); BEGIN IF (Ro.Q = 2) OR (Ro.Q = 1) THEN BEGIN Ro.X1 := (-Ko.B + SQRT(D))/(2 * Ko.A); Ro.X2 := Ro.X1; IF Ro.Q = 2 THEN Ro.X2 := (-Ko.B - SQRT(D))/(2 * Ko.A); WRITELN('1 Root & 2 Root = ', Ro.X1:4:2, ' & ', Ro.X2:4:2) END ELSE IF Ro.Q = 0 THEN WRITELN('NO ROOTS.') END; BEGIN {Equation2} IF ReadKoefs(INPUT, K) THEN BEGIN Discriminant(D, K); WRITELN('Equation Roots = ', RootsEquation(R, D)); FindingRoots(R, K); WRITELN END ELSE WRITELN('Equation is not square') END. {Equation2}
unit fCompra; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, fBasicoCrudMasterDetail, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack, dxSkinscxPCPainter, dxBarBuiltInMenu, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxButtonEdit, System.Actions, Vcl.ActnList, cxSplitter, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxGroupBox, cxRadioGroup, Vcl.StdCtrls, cxDropDownEdit, cxImageComboBox, cxTextEdit, cxMaskEdit, cxCalendar, Vcl.ExtCtrls, cxPC, dmuEstoque, dmuLookup, uTypes, System.DateUtils, uClientDataSet, uControleAcesso, System.TypInfo, cxMemo, cxDBEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCurrencyEdit, uMensagem, cxCalc, uExceptions, fEntrada, fLote_Muda, fConta_Pagar, dmuPrincipal, System.RegularExpressions, fLote_Semente, Vcl.ExtDlgs, fItem, fFornecedor, Vcl.Menus; type TCompra = class(TModelo) private FIdPessoaComprou: Integer; FData: TDateTime; FIdSolicitacao: Integer; procedure SetData(const Value: TDateTime); procedure SetIdPessoaComprou(const Value: Integer); procedure SetIdSolicitacao(const Value: Integer); public property Data: TDateTime read FData write SetData; property IdPessoaComprou: Integer read FIdPessoaComprou write SetIdPessoaComprou; property IdSolicitacao: Integer read FIdSolicitacao write SetIdSolicitacao; end; TfrmCompra = class(TfrmBasicoCrudMasterDetail) viewRegistrosID: TcxGridDBColumn; viewRegistrosID_FORNECEDOR: TcxGridDBColumn; viewRegistrosID_PESSOA_COMPROU: TcxGridDBColumn; viewRegistrosDATA: TcxGridDBColumn; viewRegistrosSTATUS_ENTREGA: TcxGridDBColumn; viewRegistrosVALOR_FRETE: TcxGridDBColumn; viewRegistrosCODIGO_RASTREIO: TcxGridDBColumn; viewRegistrosFORNECEDOR: TcxGridDBColumn; viewRegistrosPESSOA_COMPROU: TcxGridDBColumn; viewRegistrosVALOR_TOTAL: TcxGridDBColumn; viewRegistrosDetailID: TcxGridDBColumn; viewRegistrosDetailID_ITEM: TcxGridDBColumn; viewRegistrosDetailID_ESPECIE: TcxGridDBColumn; viewRegistrosDetailQTDE: TcxGridDBColumn; viewRegistrosDetailVALOR_UNITARIO: TcxGridDBColumn; viewRegistrosDetailITEM: TcxGridDBColumn; viewRegistrosDetailESPECIE: TcxGridDBColumn; lbl1: TLabel; cbComprador: TcxDBLookupComboBox; lbl2: TLabel; EditDataCompra: TcxDBDateEdit; lbStatusEntrega: TLabel; cbStatusEntrega: TcxDBImageComboBox; lbl4: TLabel; EditDescricao: TcxDBMemo; lbl5: TLabel; cbFornecedor: TcxDBLookupComboBox; Label3: TLabel; EditValorFrete: TcxDBCurrencyEdit; btnProdutoEntregue: TButton; Ac_Produto_Entregue: TAction; Label4: TLabel; cbItem: TcxDBLookupComboBox; Label5: TLabel; cbEspecie: TcxDBLookupComboBox; Label7: TLabel; EditQtde: TcxDBCalcEdit; lbUnidade: TLabel; lbl6: TLabel; EditValorUnitario: TcxDBCurrencyEdit; cbPesquisaPessoa: TcxLookupComboBox; cbItemPesquisa: TcxLookupComboBox; cbPesquisaFornecedor: TcxLookupComboBox; EditCodigoRastreio: TcxDBTextEdit; Label6: TLabel; btnGerarContaPagar: TButton; Ac_Gerar_Conta_Pagar: TAction; btnAdicionarItem: TButton; Ac_Adicionar_Item: TAction; btnAdicionarFornecedor: TButton; Ac_Adicionar_Fornecedor: TAction; viewRegistrosDetailCALC_VALOR_TOTAL: TcxGridDBColumn; viewRegistrosGEROU_CONTA_PAGAR: TcxGridDBColumn; cbPesquisaEspecie: TcxLookupComboBox; procedure FormCreate(Sender: TObject); procedure Ac_Produto_EntregueUpdate(Sender: TObject); procedure Ac_Produto_EntregueExecute(Sender: TObject); procedure viewRegistrosSTATUS_ENTREGACustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure cbItemPropertiesEditValueChanged(Sender: TObject); procedure Ac_Gerar_Conta_PagarExecute(Sender: TObject); procedure Ac_Adicionar_ItemExecute(Sender: TObject); procedure Ac_Adicionar_FornecedorExecute(Sender: TObject); procedure cbItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cbFornecedorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Ac_Gerar_Conta_PagarUpdate(Sender: TObject); procedure viewRegistrosGEROU_CONTA_PAGARCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); private dmEstoque: TdmEstoque; dmLookup: TdmLookup; procedure ppvRealizarEntradas; procedure ppvGerarEntrada(); procedure ppvGerarEntradaSemente; procedure ppvGerarEntradaMuda; procedure ppvGerarContaPagar; procedure ppvExcluirLotesMuda(ipIds: TArray<Integer>); procedure ppvExcluirLotesSemente(ipIds: TArray<Integer>); procedure ppvExcluirItensEntrada(ipIds: TArray<Integer>); procedure ppvAdicionarItem; procedure ppvCarregarItens; procedure ppvAdicionarFornecedor; procedure ppvCarregarFornecedores; procedure ppvConfigurarComponentes(ipIncluindo: Boolean); protected function fprGetPermissao: string; override; procedure pprCarregarParametrosPesquisa(ipCds: TRFClientDataSet); override; function fprConfigurarControlesPesquisa: TWinControl; override; procedure pprValidarPesquisa; override; procedure pprExecutarSalvar; override; procedure pprBeforeSalvarDetail; override; procedure pprBeforeExcluirDetail(ipId: Integer); override; procedure pprBeforeExcluir(ipId: Integer; ipAcao: TAcaoTela); override; procedure pprCarregarDadosModelo; override; procedure pprCarregarDadosModeloDetail; override; procedure pprBeforeIncluir; override; procedure pprBeforeAlterar; override; public procedure ppuIncluir; override; public const coPesquisaItem = 6; coPesquisaComprador = 5; coPesquisaCodigoRastreio = 7; coPesquisaFornecedor = 8; coPesquisaEspecie = 9; { Public declarations } end; var frmCompra: TfrmCompra; implementation {$R *.dfm} procedure TfrmCompra.Ac_Adicionar_FornecedorExecute(Sender: TObject); begin inherited; ppvAdicionarFornecedor; end; procedure TfrmCompra.Ac_Adicionar_ItemExecute(Sender: TObject); begin inherited; ppvAdicionarItem; end; procedure TfrmCompra.Ac_Gerar_Conta_PagarExecute(Sender: TObject); begin inherited; ppvGerarContaPagar; end; procedure TfrmCompra.Ac_Gerar_Conta_PagarUpdate(Sender: TObject); begin inherited; TAction(Sender).Enabled := fprHabilitarAlterar and (dmEstoque.cdsCompraGEROU_CONTA_PAGAR.AsInteger = 0); end; procedure TfrmCompra.ppvGerarContaPagar; var vaContaGerada,vaAutoApply: Boolean; vaPergunta: string; vaFrmContaPagar: TfrmContaPagar; vaContaPagar: TContaPagar; begin vaContaGerada := dmPrincipal.FuncoesEstoque.fpuVerificarContaPagarJaGerada(dmEstoque.cdsCompraID.AsInteger); if vaContaGerada then vaPergunta := 'Já existe uma conta a pagar para esta compra. Tem certeza que deseja gerar outra?' else vaPergunta := 'Deseja gerar uma conta a pagar para esta compra?'; if TMensagem.fpuPerguntar(vaPergunta, ppSimNao) = rpSim then begin vaFrmContaPagar := TfrmContaPagar.Create(nil); try vaContaPagar := TContaPagar.Create; vaContaPagar.IdFornecedor := dmEstoque.cdsCompraID_FORNECEDOR.AsInteger; vaContaPagar.IdCompra := dmEstoque.cdsCompraID.AsInteger; vaContaPagar.ValorTotal := dmEstoque.cdsCompraVALOR_TOTAL.AsFloat; vaContaPagar.IdResponsavel := dmEstoque.cdsCompraID_PESSOA_COMPROU.AsInteger; vaFrmContaPagar.ppuConfigurarModoExecucao(meSomenteCadastro, vaContaPagar); vaFrmContaPagar.ShowModal; if vaFrmContaPagar.IdEscolhido <> 0 then begin TMensagem.ppuShowMessage('Conta a Pagar gerada com sucesso.'); vaAutoApply := dmEstoque.cdsCompra.RFApplyAutomatico; dmEstoque.cdsCompra.RFApplyAutomatico := false; try dmEstoque.cdsCompra.Edit; dmEstoque.cdsCompraGEROU_CONTA_PAGAR.AsInteger := 1; dmEstoque.cdsCompra.Post; dmEstoque.cdsCompra.MergeChangeLog; finally dmEstoque.cdsCompra.RFApplyAutomatico := vaAutoApply; end; end; finally vaFrmContaPagar.Free; end; end; end; procedure TfrmCompra.Ac_Produto_EntregueExecute(Sender: TObject); begin inherited; ppvRealizarEntradas; dmEstoque.cdsCompra.Edit; dmEstoque.cdsCompraSTATUS_ENTREGA.AsInteger := Ord(sepEntregue); dmEstoque.cdsCompra.Post; end; procedure TfrmCompra.ppvRealizarEntradas(); begin if dmEstoque.cdsCompra_Item.RecordCount > 0 then begin if TMensagem.fpuPerguntar('Deseja realizar a entrada do produtos comprados?', ppSimNao) = rpSim then begin // Tipo Outros if dmEstoque.cdsCompra_Item.Locate(dmEstoque.cdsCompra_ItemTIPO_ITEM.FieldName, Ord(tiOutro), []) then ppvGerarEntrada(); // Semente if dmEstoque.cdsCompra_Item.Locate(dmEstoque.cdsCompra_ItemTIPO_ITEM.FieldName, Ord(tiSemente), []) then ppvGerarEntradaSemente(); // Muda if dmEstoque.cdsCompra_Item.Locate(dmEstoque.cdsCompra_ItemTIPO_ITEM.FieldName, Ord(tiMuda), []) then ppvGerarEntradaMuda(); TMensagem.ppuShowMessage('Entradas realizadas com sucesso.'); end; end; end; procedure TfrmCompra.Ac_Produto_EntregueUpdate(Sender: TObject); begin inherited; TAction(Sender).Enabled := fprHabilitarAlterar and (dmEstoque.cdsCompraSTATUS_ENTREGA.AsInteger <> Ord(sepEntregue)); end; procedure TfrmCompra.cbFornecedorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F2 then ppvAdicionarFornecedor; end; procedure TfrmCompra.cbItemKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F2 then ppvAdicionarItem; end; procedure TfrmCompra.ppvCarregarItens(); begin dmLookup.cdslkItem.ppuDataRequest([TParametros.coTodos], ['NAO_IMPORTA'], TOperadores.coAnd, True); end; procedure TfrmCompra.ppvCarregarFornecedores; begin dmLookup.cdslkFornecedor.ppuDataRequest([TParametros.coTodos], ['NAO_IMPORTA'], TOperadores.coAnd, True); end; procedure TfrmCompra.ppvAdicionarFornecedor; var vaFrmFornecedor: TfrmFornecedor; begin vaFrmFornecedor := TfrmFornecedor.Create(nil); try vaFrmFornecedor.ppuConfigurarModoExecucao(meSomenteCadastro); vaFrmFornecedor.ShowModal; if vaFrmFornecedor.IdEscolhido <> 0 then begin ppvCarregarFornecedores; if dmLookup.cdslkFornecedor.Locate(TBancoDados.coId, vaFrmFornecedor.IdEscolhido, []) then begin cbFornecedor.EditValue := vaFrmFornecedor.IdEscolhido; cbFornecedor.PostEditValue; end; end; finally vaFrmFornecedor.Free; end; end; procedure TfrmCompra.ppvAdicionarItem; var vaFrmItem: TfrmItem; begin vaFrmItem := TfrmItem.Create(nil); try vaFrmItem.ppuConfigurarModoExecucao(meSomenteCadastro); vaFrmItem.ShowModal; if vaFrmItem.IdEscolhido <> 0 then begin ppvCarregarItens; if dmLookup.cdslkItem.Locate(TBancoDados.coId, vaFrmItem.IdEscolhido, []) then begin cbItem.EditValue := vaFrmItem.IdEscolhido; cbItem.PostEditValue; end; end; finally vaFrmItem.Free; end; end; procedure TfrmCompra.cbItemPropertiesEditValueChanged(Sender: TObject); begin inherited; cbItem.PostEditValue; lbUnidade.Caption := dmLookup.cdslkItemUNIDADE.AsString; cbEspecie.Enabled := dmLookup.cdslkItemTIPO.AsInteger in ([Ord(tiSemente), Ord(tiMuda)]); end; procedure TfrmCompra.FormCreate(Sender: TObject); begin dmLookup := TdmLookup.Create(Self); dmLookup.Name := ''; dmEstoque := TdmEstoque.Create(Self); dmEstoque.Name := ''; inherited; PesquisaPadrao := Ord(tppData); EditDataInicialPesquisa.Date := IncDay(Now, -7);; EditDataFinalPesquisa.Date := IncDay(Now, 7); dmLookup.ppuCarregarPessoas(0, [trpFuncionario, trpEstagiario, trpVoluntario, trpMembroDiretoria]); ppvCarregarItens; dmLookup.cdslkEspecie.ppuDataRequest([TParametros.coTodos], ['NAO_IMPORTA'], TOperadores.coAnd, True); ppvCarregarFornecedores; end; function TfrmCompra.fprConfigurarControlesPesquisa: TWinControl; begin Result := inherited; cbPesquisaPessoa.Visible := (cbPesquisarPor.EditValue = coPesquisaComprador); cbItemPesquisa.Visible := cbPesquisarPor.EditValue = coPesquisaItem; cbPesquisaFornecedor.Visible := cbPesquisarPor.EditValue = coPesquisaFornecedor; cbPesquisaEspecie.Visible := cbPesquisarPor.EditValue = coPesquisaEspecie; EditPesquisa.Visible := EditPesquisa.Visible and (not(cbPesquisaEspecie.Visible or cbItemPesquisa.Visible or cbPesquisaPessoa.Visible or cbPesquisaFornecedor.Visible)); if cbPesquisaPessoa.Visible then Result := cbPesquisaPessoa else if cbItemPesquisa.Visible then Result := cbItemPesquisa else if cbPesquisaFornecedor.Visible then Result := cbPesquisaFornecedor else if cbPesquisaEspecie.Visible then Result := cbPesquisaEspecie; end; function TfrmCompra.fprGetPermissao: string; begin Result := GetEnumName(TypeInfo(TPermissaoEstoque), Ord(estCompra)); end; procedure TfrmCompra.pprBeforeAlterar; begin inherited; ppvConfigurarComponentes(false); end; procedure TfrmCompra.ppvConfigurarComponentes(ipIncluindo: Boolean); begin lbStatusEntrega.Visible := not ipIncluindo; cbStatusEntrega.Visible := lbStatusEntrega.Visible; end; procedure TfrmCompra.pprBeforeExcluir(ipId: Integer; ipAcao: TAcaoTela); var vaIdsExcluir: String; vaIdsString: TArray<String>; vaIds: TArray<Integer>; I: Integer; begin inherited; vaIdsExcluir := dmPrincipal.FuncoesViveiro.fpuBuscarLotesMudas(ipId); if vaIdsExcluir <> '' then begin if TMensagem.fpuPerguntar('Existem lotes de mudas vinculados a esta compra. Deseja excluí-los também?', ppSimNao) = rpSim then begin vaIdsString := TRegex.Split(vaIdsExcluir, coDelimitadorPadrao); SetLength(vaIds, length(vaIdsString)); for I := 0 to High(vaIdsString) do vaIds[I] := vaIdsString[I].ToInteger; ppvExcluirLotesMuda(vaIds); end; end; vaIdsExcluir := dmPrincipal.FuncoesViveiro.fpuBuscarLotesSementes(ipId); if vaIdsExcluir <> '' then begin if TMensagem.fpuPerguntar('Existem lotes de sementes vinculados a esta compra. Deseja excluí-los também?', ppSimNao) = rpSim then begin vaIdsString := TRegex.Split(vaIdsExcluir, coDelimitadorPadrao); SetLength(vaIds, length(vaIdsString)); for I := 0 to High(vaIdsString) do vaIds[I] := vaIdsString[I].ToInteger; ppvExcluirLotesSemente(vaIds); end; end; vaIdsExcluir := dmPrincipal.FuncoesEstoque.fpuBuscarItensEntrada(ipId); if vaIdsExcluir <> '' then begin if TMensagem.fpuPerguntar('Existem itens de entradas vinculados a esta compra. Deseja excluí-los também?', ppSimNao) = rpSim then begin vaIdsString := TRegex.Split(vaIdsExcluir, coDelimitadorPadrao); SetLength(vaIds, length(vaIdsString)); for I := 0 to High(vaIdsString) do vaIds[I] := vaIdsString[I].ToInteger; ppvExcluirItensEntrada(vaIds); end; end; end; procedure TfrmCompra.ppvExcluirItensEntrada(ipIds: TArray<Integer>); var vaFrmEntrada: TfrmEntrada; begin vaFrmEntrada := TfrmEntrada.Create(nil); try vaFrmEntrada.ModoSilencioso := True; vaFrmEntrada.ppuConfigurarPesquisa(TfrmEntrada.coPesquisaCompra, dmEstoque.cdsCompraID.AsString); vaFrmEntrada.ppuPesquisar; vaFrmEntrada.fpuExcluirDetail(ipIds); finally vaFrmEntrada.Free; end; end; procedure TfrmCompra.ppvExcluirLotesSemente(ipIds: TArray<Integer>); var vaFrmLoteSemente: TfrmLoteSemente; vaIds: TStringList; I: Integer; begin vaFrmLoteSemente := TfrmLoteSemente.Create(nil); try vaFrmLoteSemente.ModoSilencioso := True; if length(ipIds) > 1 then begin vaIds := TStringList.Create; try vaIds.StrictDelimiter := True; vaIds.Delimiter := coDelimitadorPadrao; for I := 0 to High(ipIds) do vaIds.Add(ipIds[I].ToString()); vaFrmLoteSemente.ppuConfigurarPesquisa(Ord(tppId), vaIds.DelimitedText); finally vaIds.Free; end; end else vaFrmLoteSemente.ppuConfigurarPesquisa(Ord(tppId), ipIds[0].ToString); vaFrmLoteSemente.ppuPesquisar; vaFrmLoteSemente.fpuExcluir(ipIds); finally vaFrmLoteSemente.Free; end; end; procedure TfrmCompra.ppvExcluirLotesMuda(ipIds: TArray<Integer>); var vaFrmLoteMuda: TfrmLoteMuda; vaIds: TStringList; I: Integer; begin vaFrmLoteMuda := TfrmLoteMuda.Create(nil); try vaFrmLoteMuda.ModoSilencioso := True; if length(ipIds) > 1 then begin vaIds := TStringList.Create; try vaIds.StrictDelimiter := True; vaIds.Delimiter := coDelimitadorPadrao; for I := 0 to High(ipIds) do vaIds.Add(ipIds[I].ToString()); vaFrmLoteMuda.ppuConfigurarPesquisa(Ord(tppId), vaIds.DelimitedText); finally vaIds.Free; end; end else vaFrmLoteMuda.ppuConfigurarPesquisa(Ord(tppId), ipIds[0].ToString); vaFrmLoteMuda.ppuPesquisar; vaFrmLoteMuda.fpuExcluir(ipIds); finally vaFrmLoteMuda.Free; end; end; procedure TfrmCompra.pprBeforeExcluirDetail(ipId: Integer); var vaIdExcluir: Integer; begin inherited; if dmEstoque.cdsCompra_ItemTIPO_ITEM.AsInteger = Ord(tiMuda) then begin vaIdExcluir := dmPrincipal.FuncoesViveiro.fpuBuscarLoteMuda(ipId); if vaIdExcluir <> 0 then begin if not ModoSilencioso then begin if TMensagem.fpuPerguntar('Existe um lote de mudas vinculado a esta compra. Deseja excluí-lo também?', ppSimNao) = rpSim then ppvExcluirLotesMuda([vaIdExcluir]); end; end; end else if dmEstoque.cdsCompra_ItemTIPO_ITEM.AsInteger = Ord(tiSemente) then begin vaIdExcluir := dmPrincipal.FuncoesViveiro.fpuBuscarLoteSemente(ipId); if vaIdExcluir <> 0 then begin if not ModoSilencioso then begin if TMensagem.fpuPerguntar('Existe um lote de semente vinculado a esta compra. Deseja excluí-lo também?', ppSimNao) = rpSim then ppvExcluirLotesSemente([vaIdExcluir]); end; end; end else begin vaIdExcluir := dmPrincipal.FuncoesEstoque.fpuBuscarItemEntrada(ipId); if vaIdExcluir <> 0 then begin if not ModoSilencioso then begin if TMensagem.fpuPerguntar('Existe um item de uma entrada vinculado a esta compra. Deseja excluí-lo também?', ppSimNao) = rpSim then ppvExcluirItensEntrada([vaIdExcluir]); end; end; end; end; procedure TfrmCompra.pprBeforeIncluir; begin inherited; // nao vamos deixar alterar o valor padrao durante a insercao ppvConfigurarComponentes(True); end; procedure TfrmCompra.pprBeforeSalvarDetail; begin inherited; // vamos garantir que somente itens do tipo smente e muda vao estar vinculados a uma especie if dmLookup.cdslkItemTIPO.AsInteger = Ord(tiOutro) then dmEstoque.cdsCompra_ItemID_ESPECIE.Clear; end; procedure TfrmCompra.pprCarregarDadosModelo; var vaCompra: TCompra; begin inherited; if (ModoExecucao in [meSomenteCadastro, meSomenteEdicao]) and Assigned(Modelo) and (Modelo is TCompra) then begin vaCompra := TCompra(Modelo); EditDataCompra.EditValue := vaCompra.Data; EditDataCompra.PostEditValue; cbComprador.EditValue := vaCompra.IdPessoaComprou; cbComprador.PostEditValue; if vaCompra.IdSolicitacao <> 0 then dmEstoque.cdsCompraID_SOLICITACAO_COMPRA.AsInteger := vaCompra.IdSolicitacao; end; end; procedure TfrmCompra.pprCarregarDadosModeloDetail; var vaItem: TItem; begin inherited; if (ModoExecucao in [meSomenteCadastro, meSomenteEdicao]) and Assigned(Modelo) and (Modelo is TItem) then begin vaItem := TItem(Modelo); cbItem.EditValue := vaItem.Id; cbItem.PostEditValue; if vaItem.IdEspecie <> 0 then begin cbEspecie.EditValue := vaItem.IdEspecie; cbEspecie.PostEditValue; end; EditQtde.EditValue := vaItem.Qtde; EditQtde.PostEditValue; end; end; procedure TfrmCompra.pprCarregarParametrosPesquisa(ipCds: TRFClientDataSet); begin inherited; if cbPesquisarPor.EditValue = coPesquisaItem then ipCds.ppuAddParametro(TParametros.coItem, cbItemPesquisa.EditValue) else if cbPesquisarPor.EditValue = coPesquisaComprador then ipCds.ppuAddParametro(TParametros.coComprador, cbPesquisaPessoa.EditValue) else if cbPesquisarPor.EditValue = coPesquisaFornecedor then ipCds.ppuAddParametro(TParametros.coFornecedor, cbPesquisaFornecedor.EditValue) else if cbPesquisarPor.EditValue = coPesquisaCodigoRastreio then ipCds.ppuAddParametro(TParametros.coCodigoRastreio, EditPesquisa.Text) else if cbPesquisarPor.EditValue = coPesquisaEspecie then ipCds.ppuAddParametro(TParametros.coEspecie, cbPesquisaEspecie.EditValue) end; procedure TfrmCompra.pprExecutarSalvar; var vaRealizarEntradas: Boolean; begin vaRealizarEntradas := false; if not VarIsNull(dmEstoque.cdsCompraSTATUS_ENTREGA.NewValue) then begin if dmEstoque.cdsCompraSTATUS_ENTREGA.NewValue = Ord(sepEntregue) then begin if (not VarIsNull(dmEstoque.cdsCompraSTATUS_ENTREGA.OldValue)) and (dmEstoque.cdsCompraSTATUS_ENTREGA.NewValue <> dmEstoque.cdsCompraSTATUS_ENTREGA.OldValue) then vaRealizarEntradas := True end; end; inherited; if vaRealizarEntradas then ppvRealizarEntradas; end; procedure TfrmCompra.pprValidarPesquisa; begin inherited; if cbPesquisaPessoa.Visible and (VarIsNull(cbPesquisaPessoa.EditValue)) then begin if cbPesquisarPor.EditValue = coPesquisaComprador then raise TControlException.Create('Informe o comprador.', cbPesquisaPessoa); end; if cbItemPesquisa.Visible and (VarIsNull(cbItemPesquisa.EditValue)) then raise Exception.Create('Informe o item a ser pesquisado.'); if cbPesquisaFornecedor.Visible and (VarIsNull(cbPesquisaFornecedor.EditValue)) then raise Exception.Create('Informe o fornecedor a ser pesquisado.'); end; procedure TfrmCompra.ppuIncluir; begin inherited; if dmEstoque.cdsCompraSTATUS_ENTREGA.isNull then dmEstoque.cdsCompraSTATUS_ENTREGA.AsInteger := Ord(sepACaminho); if dmEstoque.cdsCompraDATA.isNull then dmEstoque.cdsCompraDATA.AsDateTime := Now; end; procedure TfrmCompra.ppvGerarEntrada(); var vaFrmEntrada: TfrmEntrada; vaEntrada: TEntrada; vaItem: TItem; begin // realizando a entrada vaFrmEntrada := TfrmEntrada.Create(nil); try vaEntrada := TEntrada.Create; // vai ser destruido pelo frmEntrada vaEntrada.Data := dmEstoque.cdsCompraDATA.AsDateTime; vaFrmEntrada.ppuConfigurarModoExecucao(meSomenteCadastro, vaEntrada); vaFrmEntrada.ppuIncluir; vaFrmEntrada.ppuSalvar; dmEstoque.cdsCompra_Item.First; while not dmEstoque.cdsCompra_Item.Eof do begin if dmEstoque.cdsCompra_ItemTIPO_ITEM.AsInteger = Ord(tiOutro) then begin vaItem := TItem.Create; // vai ser destruido pelo vafrmEntrada vaItem.Id := dmEstoque.cdsCompra_ItemID_ITEM.AsInteger; vaItem.Qtde := dmEstoque.cdsCompra_ItemQTDE.AsFloat; vaItem.IdItemCompraVenda := dmEstoque.cdsCompra_ItemID.AsInteger; vaFrmEntrada.Modelo := vaItem; vaFrmEntrada.ppuIncluirDetail; vaFrmEntrada.ppuSalvarDetail; end; dmEstoque.cdsCompra_Item.Next; end; finally vaFrmEntrada.Free; end; end; procedure TfrmCompra.ppvGerarEntradaSemente(); var vaFrmLoteSemente: TfrmLoteSemente; vaLoteSemente: TLoteSemente; begin // realizando a entrada de sementes vaFrmLoteSemente := TfrmLoteSemente.Create(nil); try dmEstoque.cdsCompra_Item.First; while not dmEstoque.cdsCompra_Item.Eof do begin if dmEstoque.cdsCompra_ItemTIPO_ITEM.AsInteger = Ord(tiSemente) then begin vaLoteSemente := TLoteSemente.Create; // vai ser destruido pelo vaFrmLoteSemente vaLoteSemente.Data := dmEstoque.cdsCompraDATA.AsDateTime; vaLoteSemente.IdItemCompra := dmEstoque.cdsCompra_ItemID.AsInteger; vaLoteSemente.IdEspecie := dmEstoque.cdsCompra_ItemID_ESPECIE.AsInteger; vaLoteSemente.Nome := 'Lote (Comprado)'; vaLoteSemente.Qtde := dmEstoque.cdsCompra_ItemQTDE.AsFloat; vaLoteSemente.IdPessoaColetouComprou := dmEstoque.cdsCompraID_PESSOA_COMPROU.AsInteger; vaFrmLoteSemente.ppuConfigurarModoExecucao(meSomenteCadastro, vaLoteSemente); vaFrmLoteSemente.ppuIncluir; vaFrmLoteSemente.ppuSalvar; end; dmEstoque.cdsCompra_Item.Next; end; finally vaFrmLoteSemente.Free; end; end; procedure TfrmCompra.ppvGerarEntradaMuda(); var vaFrmLoteMuda: TfrmLoteMuda; vaLoteMuda: TLoteMuda; begin // realizando a entrada de muda vaFrmLoteMuda := TfrmLoteMuda.Create(nil); try dmEstoque.cdsCompra_Item.First; while not dmEstoque.cdsCompra_Item.Eof do begin if dmEstoque.cdsCompra_ItemTIPO_ITEM.AsInteger = Ord(tiMuda) then begin vaLoteMuda := TLoteMuda.Create; vaLoteMuda.Data := dmEstoque.cdsCompraDATA.AsDateTime; vaLoteMuda.IdItemCompra := dmEstoque.cdsCompra_ItemID.AsInteger; vaLoteMuda.IdEspecie := dmEstoque.cdsCompra_ItemID_ESPECIE.AsInteger; vaLoteMuda.Nome := 'Lote (Comprado)'; vaLoteMuda.Qtde := dmEstoque.cdsCompra_ItemQTDE.AsFloat; vaLoteMuda.Status := smProntaPlantio; vaFrmLoteMuda.ppuConfigurarModoExecucao(meSomenteCadastro, vaLoteMuda); vaFrmLoteMuda.ppuIncluir; vaFrmLoteMuda.ppuSalvar; end; dmEstoque.cdsCompra_Item.Next; end; finally vaFrmLoteMuda.Free; end; end; procedure TfrmCompra.viewRegistrosGEROU_CONTA_PAGARCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin inherited; if AViewInfo.Value = 0 then begin ACanvas.Font.Color := clWhite; if AViewInfo.GridRecord.Selected then ACanvas.Brush.Color := clMaroon else ACanvas.Brush.Color := clRed; end else begin ACanvas.Font.Color := clWhite; ACanvas.Brush.Color := clGreen; end; end; procedure TfrmCompra.viewRegistrosSTATUS_ENTREGACustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin inherited; // if AViewInfo.GridRecord.Values[viewRegistrosDetailSTATUS.Index] = 1 then // begin // ACanvas.Font.Color := clWhite; // if AViewInfo.GridRecord.Selected then // ACanvas.Brush.Color := $00274F00 // else // ACanvas.Brush.Color := clGreen; // end // else if AViewInfo.GridRecord.Values[viewRegistrosDetailVENCIMENTO.Index] < Today then // begin // ACanvas.Font.Color := clWhite; // if AViewInfo.GridRecord.Selected then // ACanvas.Brush.Color := clMaroon // else // ACanvas.Brush.Color := clRed; // end; end; { TCompra } procedure TCompra.SetData( const Value: TDateTime); begin FData := Value; end; procedure TCompra.SetIdPessoaComprou( const Value: Integer); begin FIdPessoaComprou := Value; end; procedure TCompra.SetIdSolicitacao( const Value: Integer); begin FIdSolicitacao := Value; end; end.
unit RRManagerStratumEditForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, CommonComplexCombo, StdCtrls, ExtCtrls, Buttons, ActnList, ImgList, ClientDicts, BaseDicts {$IFDEF VER150} , Variants {$ENDIF} ; type TfrmEditStratum = class(TDictEditForm) gbxContainment: TGroupBox; pnlButtons: TPanel; lbxContainedStratons: TListBox; sbtnRight: TSpeedButton; sbtnLeft: TSpeedButton; sbtnFullLeft: TSpeedButton; btnOK: TButton; btnCancel: TButton; actnEditStratum: TActionList; MoveRight: TAction; MoveLeft: TAction; MoveAllLeft: TAction; pnlLeft: TPanel; lbxAllStratons: TListBox; edtSearch: TEdit; Label2: TLabel; imgList: TImageList; Panel1: TPanel; Label1: TLabel; edtStratumName: TEdit; cmplxHorizon: TfrmComplexCombo; actnOK: TAction; procedure FormCreate(Sender: TObject); procedure MoveRightExecute(Sender: TObject); procedure MoveRightUpdate(Sender: TObject); procedure MoveLeftExecute(Sender: TObject); procedure MoveLeftUpdate(Sender: TObject); procedure MoveAllLeftExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtSearchChange(Sender: TObject); procedure cmplxHorizonbtnShowAdditionalClick(Sender: TObject); procedure actnOKUpdate(Sender: TObject); private { Private declarations } protected procedure SetDict(const Value: TDict); override; public { Public declarations } procedure ClearControls; override; procedure SaveValues; override; procedure AdditionalSave; override; end; var frmEditStratum: TfrmEditStratum; implementation uses Facade; {$R *.DFM} { TStratumEditForm } procedure TfrmEditStratum.SetDict(const Value: TDict); begin FDict := Value; ClearControls; end; procedure TfrmEditStratum.FormCreate(Sender: TObject); begin cmplxHorizon.Caption := 'Горизонт'; cmplxHorizon.FullLoad := true; cmplxHorizon.DictName := 'TBL_STRATUM'; (TMainFacade.GetInstance as TMainFacade).AllDicts.MakeList(lbxAllStratons.Items, (TMainFacade.GetInstance as TMainFacade).AllDicts.DictContentByName('TBL_STRATIGRAPHY_NAME_DICT')); lbxAllStratons.Sorted := true; Width := 700; Height := 500; end; procedure TfrmEditStratum.MoveRightExecute(Sender: TObject); begin with lbxAllStratons do begin lbxContainedStratons.ItemIndex := lbxContainedStratons.Items.IndexOfObject(Items.Objects[ItemIndex]); if lbxContainedStratons.ItemIndex = -1 then lbxContainedStratons.ItemIndex := lbxContainedStratons.Items.AddObject(Items[ItemIndex], Items.Objects[ItemIndex]); lbxContainedStratons.Sorted := true; end; end; procedure TfrmEditStratum.MoveRightUpdate(Sender: TObject); begin MoveRight.Enabled := lbxAllStratons.ItemIndex > -1; end; procedure TfrmEditStratum.MoveLeftExecute(Sender: TObject); begin lbxContainedStratons.Items.Delete(lbxContainedStratons.ItemIndex); end; procedure TfrmEditStratum.MoveLeftUpdate(Sender: TObject); begin MoveLeft.Enabled := lbxContainedStratons.ItemIndex > -1; end; procedure TfrmEditStratum.MoveAllLeftExecute(Sender: TObject); begin lbxContainedStratons.Clear; end; procedure TfrmEditStratum.FormShow(Sender: TObject); var v: variant; iHorizonID: integer; begin iHorizonID := Dict.Columns[2].Value; if iHorizonID > 0 then cmplxHorizon.AddItem(iHorizonID, cmplxHorizon.cmbxName.Items[cmplxHorizon.cmbxName.Items.IndexOfObject(TObject(iHorizonID))]); edtStratumName.Text := Dict.Columns[1].Value; // загружаем зависимые v := Dict.Reference('TBL_STRATUM_STRATON', 'STRATON_ID'); if not varIsEmpty(v) then (TMainFacade.GetInstance as TMainFacade).AllDicts.MakeList(lbxContainedStratons.Items, (TMainFacade.GetInstance as TMainFacade).AllDicts.DictContentByName('TBL_STRATIGRAPHY_NAME_DICT'), v, 0); end; procedure TfrmEditStratum.ClearControls; begin cmplxHorizon.Clear; edtStratumName.Clear; lbxContainedStratons.Clear; end; procedure TfrmEditStratum.edtSearchChange(Sender: TObject); var i: integer; begin for i := 0 to lbxAllStratons.Items.Count - 1 do if pos(edtSearch.Text, lbxAllStratons.Items[i]) > 0 then begin lbxAllStratons.ItemIndex := i; break; end; end; procedure TfrmEditStratum.cmplxHorizonbtnShowAdditionalClick( Sender: TObject); begin cmplxHorizon.btnShowAdditionalClick(Sender); end; procedure TfrmEditStratum.AdditionalSave; begin inherited; FDict.SetRefer(lbxContainedStratons.Items); end; procedure TfrmEditStratum.SaveValues; begin inherited; FDict.Columns[1].Value := edtStratumName.Text; FDict.Columns[2].Value := cmplxHorizon.SelectedElementID; end; procedure TfrmEditStratum.actnOKUpdate(Sender: TObject); begin actnOK.Enabled := cmplxHorizon.SelectedElementID > 0 end; end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.DataView.Base; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ComCtrls, Vcl.ExtCtrls, Data.DB, DataGrabber.Interfaces; type TBaseDataView = class(TForm, IDataView) dscMain : TDataSource; procedure FormClose(Sender: TObject; var Action: TCloseAction); private FManager : IConnectionViewManager; FToolBar : TToolBar; FToolBarPanel : TPanel; FResultSet : IResultSet; protected {$REGION 'property access methods'} function GetName: string; virtual; function GetGridType: string; virtual; function GetSettings: IDataViewSettings; function GetData: IData; function GetRecordCount: Integer; virtual; function GetPopupMenu: TPopupMenu; reintroduce; virtual; procedure SetPopupMenu(const Value: TPopupMenu); virtual; function GetDataSet: TDataSet; virtual; function GetResultSet: IResultSet; {$ENDREGION} procedure DataAfterExecute(Sender: TObject); virtual; procedure SettingsChanged(Sender: TObject); virtual; procedure AssignParent(AParent: TWinControl); virtual; procedure UpdateView; virtual; procedure HideSelectedColumns; virtual; function IsActiveDataView: Boolean; virtual; procedure Inspect; virtual; procedure AutoSizeColumns; virtual; procedure Copy; virtual; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; function ResultsToWikiTable( AIncludeHeader: Boolean = False ): string; virtual; function ResultsToTextTable( AIncludeHeader: Boolean = False ): string; virtual; function SelectionToCommaText( AQuoteItems: Boolean = True ): string; virtual; function SelectionToDelimitedTable( ADelimiter : string = #9; AIncludeHeader : Boolean = True ): string; virtual; function SelectionToTextTable( AIncludeHeader: Boolean = False ): string; virtual; function SelectionToWikiTable( AIncludeHeader: Boolean = False ): string; virtual; function SelectionToFields( AQuoteItems: Boolean = True ): string; virtual; procedure ApplyGridSettings; virtual; procedure UpdateActions; override; public constructor Create( AOwner : TComponent; AManager : IConnectionViewManager; AResultSet : IResultSet ); reintroduce; virtual; procedure AfterConstruction; override; procedure BeforeDestruction; override; property Name: string read GetName; property GridType: string read GetGridType; property DataSet: TDataSet read GetDataSet; property Data: IData read GetData; property RecordCount: Integer read GetRecordCount; property Settings: IDataViewSettings read GetSettings; property PopupMenu: TPopupMenu read GetPopupMenu write SetPopupMenu; end; implementation {$R *.dfm} uses Spring, DataGrabber.Utils, DataGrabber.Factories; {$REGION 'construction and destruction'} constructor TBaseDataView.Create(AOwner: TComponent; AManager: IConnectionViewManager; AResultSet: IResultSet); begin inherited Create(AOwner); Guard.CheckNotNull(AManager, 'AManager'); Guard.CheckNotNull(AResultSet, 'AResultSet'); FResultSet := AResultSet; FManager := AManager; dscMain.DataSet := AResultSet.DataSet; end; procedure TBaseDataView.AfterConstruction; begin inherited AfterConstruction; FToolBarPanel := TPanel.Create(Self); FToolBarPanel.Parent := Self; FToolBarPanel.BevelOuter := bvNone; FToolBarPanel.Color := clWhite; FToolBarPanel.Align := alRight; FToolBarPanel.Visible := False; FToolbar := TDataGrabberFactories.CreateDataViewToolbar( Self, FToolBarPanel, FManager ); FToolbar.Align := alRight; FToolbar.Visible := True; FToolbar.AutoSize := True; FToolBarPanel.AutoSize := True; Data.OnAfterExecute.Add(DataAfterExecute); Settings.OnChanged.Add(SettingsChanged); end; procedure TBaseDataView.BeforeDestruction; begin Settings.OnChanged.Remove(SettingsChanged); Data.OnAfterExecute.Remove(DataAfterExecute); FResultSet := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TBaseDataView.GetData: IData; begin if Assigned(FResultSet) then Result := FResultSet.Data else Result := nil; end; function TBaseDataView.GetDataSet: TDataSet; begin if Assigned(FResultSet) then Result := FResultSet.DataSet else Result := nil; end; function TBaseDataView.GetGridType: string; begin Result := ''; end; function TBaseDataView.GetName: string; begin Result := inherited Name; end; function TBaseDataView.GetPopupMenu: TPopupMenu; begin Result := inherited PopupMenu; end; procedure TBaseDataView.SetPopupMenu(const Value: TPopupMenu); begin inherited PopupMenu := Value; end; function TBaseDataView.GetRecordCount: Integer; begin Result := DataSet.RecordCount; end; function TBaseDataView.GetResultSet: IResultSet; begin Result := FResultSet; end; function TBaseDataView.GetSettings: IDataViewSettings; begin Result := FManager.Settings as IDataViewSettings; end; {$ENDREGION} {$REGION 'event handlers'} procedure TBaseDataView.DataAfterExecute(Sender: TObject); begin if Assigned(Data) then UpdateView; end; procedure TBaseDataView.SettingsChanged(Sender: TObject); begin ApplyGridSettings; end; procedure TBaseDataView.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; {$ENDREGION} {$REGION 'protected methods'} procedure TBaseDataView.ApplyGridSettings; begin // end; procedure TBaseDataView.AssignParent(AParent: TWinControl); begin Parent := AParent; BorderStyle := bsNone; Align := alClient; Visible := True; end; procedure TBaseDataView.AutoSizeColumns; begin // end; procedure TBaseDataView.BeginUpdate; begin // end; procedure TBaseDataView.EndUpdate; begin // end; procedure TBaseDataView.Copy; begin // end; procedure TBaseDataView.HideSelectedColumns; begin // end; procedure TBaseDataView.Inspect; begin // end; function TBaseDataView.IsActiveDataView: Boolean; begin Result := ContainsFocus(Self); end; function TBaseDataView.ResultsToTextTable(AIncludeHeader: Boolean): string; begin Result := ''; end; function TBaseDataView.ResultsToWikiTable(AIncludeHeader: Boolean): string; begin Result := ''; end; function TBaseDataView.SelectionToCommaText(AQuoteItems: Boolean): string; begin Result := ''; end; function TBaseDataView.SelectionToDelimitedTable(ADelimiter: string; AIncludeHeader: Boolean): string; begin Result := ''; end; function TBaseDataView.SelectionToFields(AQuoteItems: Boolean): string; begin Result := ''; end; function TBaseDataView.SelectionToTextTable(AIncludeHeader: Boolean): string; begin Result := ''; end; function TBaseDataView.SelectionToWikiTable(AIncludeHeader: Boolean): string; begin Result := ''; end; procedure TBaseDataView.UpdateActions; begin inherited UpdateActions; FToolBarPanel.Visible := IsActiveDataView; end; procedure TBaseDataView.UpdateView; begin UpdateActions; end; {$ENDREGION} end.
unit aOPCTCPSource_V32; interface uses Classes, SysUtils, IdComponent, DC.StrUtils, aOPCSource, aOPCTCPSource_V30, uDCObjects, uUserMessage, aCustomOPCSource, aCustomOPCTCPSource; const cPV32_BlockSize = 64*1024; type TaOPCTCPSource_V32 = class(TaOPCTCPSource_V30) public constructor Create(aOwner: TComponent); override; procedure WriteFileStream(aStream: TStream); function GetProjects(aMask: string = ''): string; function GetProjectGroups(aParentID: Integer = 0): string; function GetProjectVersions(aProjectID: integer; aLastVerCount: Integer; aDate1, aDate2: TDateTime): string; function GetProjectVersionInfo(aProjectID, aVersionID: integer): string; function GetProjectVersionFileName(aProjectID, aVersionID: Integer): string; procedure GetProjectVersionFile( aProjectID, aVersionID: Integer; aStream: TStream; aComment: string; aProgressNotify: TOPCProgressNotify = nil); function AddProject(aLabel, aOwner, aDescription, DevEnviroment, Plant, Process, Equipment: string; GroupID: Integer): Integer; function UpdateProject(aID: Integer; aLabel, aOwner, aDescription, DevEnviroment, Plant, Process, Equipment: string; GroupID: Integer): Integer; function DelProject(aID: Integer): Integer; function AddProjectGroup(aLabel, aDescription: string; aParentID: Integer): Integer; function UpdateProjectGroup(aID: Integer; aLabel, aDescription: string; aParentID: Integer): Integer; function DelProjectGroup(aID: Integer): Integer; function AddProjectVersionInfo(aProjectID: Integer; aLabel, aComment, aDescription, aAuthor: string): Integer; procedure AddProjectVersionFile( aProjectID, aVersionID: Integer; aStream: TStream; aProgressNotify: TOPCProgressNotify = nil); function AddProjectVersion(aProjectID: Integer; aLabel, aComment, aDescription, aAuthor: string; aStream: TStream; aProgressNotify: TOPCProgressNotify = nil): Integer; procedure LockProject(aProjectID, aHours: Integer; aReason: string); procedure UnlockProject(aProjectID: Integer); procedure DownloadPMCSetup(aStream: TStream; aProgressNotify: TOPCProgressNotify = nil); //function GetUserProjectPermission(aProjectID: Integer): string; //function GetProjectPermission(aProjectID: Integer): string; //procedure SetProjectPermission(aProjectID: Integer; aUserPermitions: string); function GetOperationLog(aLastCount: Integer; aDate1, aDate2: TDateTime): string; end; implementation uses Math, uDCStrResource; { TaOPCTCPSource_V32 } function TaOPCTCPSource_V32.AddProject(aLabel, aOwner, aDescription, DevEnviroment, Plant, Process, Equipment: string; GroupID: Integer): Integer; begin LockConnection; try DoConnect; DoCommandFmt('AddProject ' + 'Encoded=1;' + 'Label=%s;' + 'Owner=%s;' + 'Description=%s;' + 'DevEnviroment=%s;' + 'Plant=%s;' + 'Process=%s;' + 'Equipment=%s;' + 'GroupID=%s', [EncodeStr(aLabel), EncodeStr(aOwner), EncodeStr(aDescription), EncodeStr(DevEnviroment), EncodeStr(Plant), EncodeStr(Process), EncodeStr(Equipment), EncodeStr(IntToStr(GroupID))]); Result := StrToInt(ReadLn); finally UnLockConnection; end; end; function TaOPCTCPSource_V32.AddProjectGroup(aLabel, aDescription: string; aParentID: Integer): Integer; begin LockConnection; try DoConnect; DoCommandFmt('AddProjectGroup ' + 'Encoded=1;' + 'Label=%s;' + 'Description=%s;' + 'ParentID=%s', [EncodeStr(aLabel), EncodeStr(aDescription), EncodeStr(IntToStr(aParentID))]); Result := StrToInt(ReadLn); finally UnLockConnection; end; end; function TaOPCTCPSource_V32.AddProjectVersion(aProjectID: Integer; aLabel, aComment, aDescription, aAuthor: string; aStream: TStream; aProgressNotify: TOPCProgressNotify): Integer; var aSize: Integer; aBlockSize: Integer; aCanceled: Boolean; oldOnWork: TWorkEvent; begin Assert(Assigned(aStream), uDCStrResource.dcResS_StreamNotCreated); LockConnection; try aSize := aStream.Size; DoConnect; DoCommandFmt('AddProjectVersion ' + 'ProjectID=%d;' + 'StreamSize=%d;' + 'Encoded=1;' + 'Label=%s;' + 'Description=%s;' + 'Comment=%s;' + 'Author=%s', [aProjectID, aSize, EncodeStr(aLabel), EncodeStr(aDescription), EncodeStr(aComment), EncodeStr(aAuthor)]); aCanceled := False; aStream.Position := 0; // попытка 1 // WriteFileStream(aStream); // попытка 2 { OpenWriteBuffer; try WriteStream(aStream, False, False, aStream.Size); finally CloseWriteBuffer; end; } aBlockSize := Min(cPV32_BlockSize, aStream.Size); //aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); OpenWriteBuffer; try while aStream.Position < aSize do begin WriteStream(aStream, False, False, aBlockSize); if Assigned(aProgressNotify) then begin aProgressNotify(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); end; finally CloseWriteBuffer; end; if not aCanceled then begin CheckCommandResult; Result := StrToInt(ReadLn); end; finally UnLockConnection; end; if aCanceled then begin DoDisconnect; raise EOPCTCPOperationCanceledException.Create(uDCStrResource.dcResS_OperationCanceledByUser); end; end; procedure TaOPCTCPSource_V32.AddProjectVersionFile(aProjectID, aVersionID: Integer; aStream: TStream; aProgressNotify: TOPCProgressNotify); var aSize: Integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), dcResS_StreamNotCreated); LockConnection; try aSize := aStream.Size; DoConnect; DoCommandFmt('AddProjectVersionFile %d;%d;%d', [aProjectID, aVersionID, aSize]); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin WriteStream(aStream, False, False, aBlockSize); if Assigned(aProgressNotify) then begin aProgressNotify(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); end; finally UnLockConnection; end; if aCanceled then begin Disconnect; raise EOPCTCPOperationCanceledException.Create(dcResS_OperationCanceledByUser); end; end; function TaOPCTCPSource_V32.AddProjectVersionInfo(aProjectID: Integer; aLabel, aComment, aDescription, aAuthor: string): Integer; begin LockConnection; try DoConnect; DoCommandFmt('AddProjectVersionInfo ' + 'ProjectID=%d;' + 'Label=%s;' + 'Description=%s;' + 'Comment=%s;' + 'Author=%s', [aProjectID, aLabel, aDescription, aComment, aAuthor]); Result := StrToInt(ReadLn); finally UnLockConnection; end; end; constructor TaOPCTCPSource_V32.Create(aOwner: TComponent); begin inherited; ProtocolVersion := 32; { TODO -oAlex -cCompression : Проблемы со сжатием при передаче файлов } CompressionLevel := 0; end; function TaOPCTCPSource_V32.DelProject(aID: Integer): Integer; begin LockAndDoCommandFmt('DelProject %d', [aID]); end; function TaOPCTCPSource_V32.DelProjectGroup(aID: Integer): Integer; begin LockAndDoCommandFmt('DelProjectGroup %d', [aID]); end; procedure TaOPCTCPSource_V32.DownloadPMCSetup(aStream: TStream; aProgressNotify: TOPCProgressNotify); var aSize: Integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), dcResS_StreamNotCreated); LockConnection; try DoConnect; DoCommand('DownloadPMC'); aSize := StrToInt(ReadLn); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin ReadStream(aStream, aBlockSize); if Assigned(aProgressNotify) then begin aProgressNotify(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); end; finally UnLockConnection; end; if aCanceled then begin Disconnect; Reconnect; raise EOPCTCPOperationCanceledException.Create(dcResS_OperationCanceledByUser); end; end; function TaOPCTCPSource_V32.GetOperationLog(aLastCount: Integer; aDate1, aDate2: TDateTime): string; begin Result := LockAndGetStringsCommand( Format('GetOperationLog LastCount=%d;Encoded=1;Date1=%s;Date2=%s', [aLastCount, FloatToStr(aDate1, OpcFS), FloatToStr(aDate2, OpcFS)])); end; function TaOPCTCPSource_V32.GetProjectGroups(aParentID: Integer): string; begin Result := LockAndGetStringsCommand(Format('GetProjectGroups %d', [aParentID])); end; //function TaOPCTCPSource_V32.GetProjectPermission(aProjectID: Integer): string; //begin // Result := LockAndGetStringsCommand(Format('GetProjectPermission %d;1', [aProjectID])); //end; function TaOPCTCPSource_V32.GetProjects(aMask: string): string; begin Result := LockAndGetStringsCommand(Format('GetProjects %s;1', [EncodeStr(aMask)])); end; procedure TaOPCTCPSource_V32.GetProjectVersionFile(aProjectID, aVersionID: Integer; aStream: TStream; aComment: string; aProgressNotify: TOPCProgressNotify); var aSize: Integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), dcResS_StreamNotCreated); LockConnection; try DoConnect; DoCommandFmt('GetProjectVersionFile %d;%d;%s', [aProjectID, aVersionID, EncodeStr(aComment)]); aSize := StrToInt(ReadLn); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin ReadStream(aStream, aBlockSize); if Assigned(aProgressNotify) then begin aProgressNotify(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV32_BlockSize, aSize - aStream.Position); end; finally UnLockConnection; end; if aCanceled then begin Disconnect; raise EOPCTCPOperationCanceledException.Create(dcResS_OperationCanceledByUser); end; end; function TaOPCTCPSource_V32.GetProjectVersionFileName(aProjectID, aVersionID: Integer): string; begin Result := LockDoCommandReadLnFmt('GetProjectVersionFileName %d;%d', [aProjectID, aVersionID]); end; function TaOPCTCPSource_V32.GetProjectVersionInfo(aProjectID, aVersionID: integer): string; begin Result := LockAndGetStringsCommand( Format('GetProjectVersionInfo %d;%d', [aProjectID, aVersionID])) end; function TaOPCTCPSource_V32.GetProjectVersions(aProjectID, aLastVerCount: Integer; aDate1, aDate2: TDateTime): string; begin // получить список версий проекта по ID // if aLastVerCount <> 0 then Result := LockAndGetStringsCommand( Format('GetProjectVersions %d;%d;1;%s;%s', [aProjectID, aLastVerCount, FloatToStr(aDate1, OpcFS), FloatToStr(aDate2, OpcFS)])) // else // Result := LockAndGetStringsCommand( // Format('GetProjectVersions %d;0;1', [aProjectID])) end; //function TaOPCTCPSource_V32.GetUserProjectPermission(aProjectID: Integer): string; //begin // LockConnection; // try // DoConnect; // DoCommandFmt('GetUserProjectPermission %d', [aProjectID]); // // Result := ReadLn; // finally // UnLockConnection; // end; // //end; procedure TaOPCTCPSource_V32.LockProject(aProjectID, aHours: Integer; aReason: string); begin LockAndDoCommandFmt('LockProject %d;%d;%s;1', [aProjectID, aHours, StrToHex(aReason)]); end; //procedure TaOPCTCPSource_V32.SetProjectPermission(aProjectID: Integer; aUserPermitions: string); //begin // LockAndDoCommandFmt('SetProjectPermission %d;%s;1', [aProjectID, EncodeStr(aUserPermitions)]); //end; procedure TaOPCTCPSource_V32.UnlockProject(aProjectID: Integer); begin LockAndDoCommandFmt('UnlockProject %d', [aProjectID]); end; function TaOPCTCPSource_V32.UpdateProject(aID: Integer; aLabel, aOwner, aDescription, DevEnviroment, Plant, Process, Equipment: string; GroupID: Integer): Integer; begin LockConnection; try DoConnect; DoCommandFmt('UpdateProject ' + 'Encoded=1;' + 'ID=%d;' + 'Label=%s;' + 'Owner=%s;' + 'Description=%s;' + 'DevEnviroment=%s;' + 'Plant=%s;' + 'Process=%s;' + 'Equipment=%s;' + 'GroupID=%s', [aID, EncodeStr(aLabel), EncodeStr(aOwner), EncodeStr(aDescription), EncodeStr(DevEnviroment), EncodeStr(Plant), EncodeStr(Process), EncodeStr(Equipment), EncodeStr(IntToStr(GroupID))]); Result := StrToInt(ReadLn); finally UnLockConnection; end; end; function TaOPCTCPSource_V32.UpdateProjectGroup(aID: Integer; aLabel, aDescription: string; aParentID: Integer): Integer; begin LockConnection; try DoConnect; DoCommandFmt('UpdateProjectGroup ' + 'Encoded=1;' + 'ID=%s;' + 'Label=%s;' + 'Description=%s;' + 'ParentID=%s', [EncodeStr(IntToStr(aID)), EncodeStr(aLabel), EncodeStr(aDescription), EncodeStr(IntToStr(aParentID))]); Result := StrToInt(ReadLn); finally UnLockConnection; end; end; procedure TaOPCTCPSource_V32.WriteFileStream(aStream: TStream); const cBufSize = 1024 * 1024; var aSize: Int64; aSendSize: Int64; begin aSize := aStream.Size; aStream.Position := 0; Connection.IOHandler.Write(aSize); repeat aSendSize := Min(aSize, cBufSize); Connection.IOHandler.Write(aStream, aSendSize, True); aSize := aSize - aSendSize; CheckCommandResult; until aSize <= 0; end; end.
unit angPasteHistorie; {$mode objfpc}{$H+} interface uses Classes, SysUtils,strutils; type TAngClipboardHistorie = class public sClipboard : string; end; type { TAngClipboardHistorieList } TAngClipboardHistorieList = class(TStringlist) public procedure AddToHistorie(s : string); function AngClipboardHistorie(i:integer):TAngClipboardHistorie; constructor create; end; implementation { TAngClipboardHistorieList } procedure TAngClipboardHistorieList.AddToHistorie(s: string); var gefunden : boolean; i : integer; AngClipboardHistorie1 : TAngClipboardHistorie; s2 : string; begin gefunden := false; for i := 0 to self.count -1 do begin if self.AngClipboardHistorie(i).sClipboard = s then begin gefunden := true; self.Exchange(i,0); break; end; end; if not gefunden then begin AngClipboardHistorie1 := TAngClipboardHistorie.create; AngClipboardHistorie1.sClipboard:= s; s2 := copy(s,1,100); s2 := ansireplacestr(s2,#13,''); s2 := ansireplacestr(s2,#10,''); self.InsertObject (0,s2,AngClipboardHistorie1); end; for i := self.count -1 downto 20 do self.Delete(i); end; function TAngClipboardHistorieList.AngClipboardHistorie(i: integer ): TAngClipboardHistorie; begin result := TAngClipboardHistorie(self.Objects[i]); end; constructor TAngClipboardHistorieList.create; begin self.OwnsObjects:= true; end; end.
unit FieldLogReportDM; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.IBLiteDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, System.Types; type TdmFieldLogger = class(TDataModule) conn: TFDConnection; qProjects: TFDQuery; qLogEntries: TFDQuery; dsProjects: TDataSource; qProjectsPROJ_ID: TIntegerField; qProjectsPROJ_TITLE: TWideStringField; qProjectsPROJ_DESC: TWideMemoField; qLogEntriesLOG_ID: TIntegerField; qLogEntriesPROJ_ID: TIntegerField; qLogEntriesPICTURE: TBlobField; qLogEntriesLONGITUDE: TSingleField; qLogEntriesLATITUDE: TSingleField; qLogEntriesTIMEDATESTAMP: TSQLTimeStampField; qLogEntriesOR_X: TSingleField; qLogEntriesOR_Y: TSingleField; qLogEntriesOR_Z: TSingleField; qLogEntriesOR_DISTANCE: TSingleField; qLogEntriesHEADING_X: TSingleField; qLogEntriesHEADING_Y: TSingleField; qLogEntriesHEADING_Z: TSingleField; qLogEntriesV_X: TSingleField; qLogEntriesV_Y: TSingleField; qLogEntriesV_Z: TSingleField; qLogEntriesANGLE_X: TSingleField; qLogEntriesANGLE_Y: TSingleField; qLogEntriesANGLE_Z: TSingleField; qLogEntriesMOTION: TSingleField; qLogEntriesSPEED: TSingleField; qLogEntriesNOTE: TWideMemoField; procedure DataModuleCreate(Sender: TObject); procedure qLogEntriesAfterInsert(DataSet: TDataSet); private { Private declarations } public { Public declarations } procedure LoadRandomImage; end; var dmFieldLogger: TdmFieldLogger; function ResizeJpegField(const field: TBlobField; const maxWidth: integer): TByteDynArray; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses IOUtils, FMX.Graphics; function ResizeJpegField(const field: TBlobField; const maxWidth: integer): TByteDynArray; var blob: TStream; jpeg: TBitmap; begin Assert(Assigned(field)); blob := nil; jpeg := nil; try blob := field.DataSet.CreateBlobStream(field, TBlobStreamMode.bmRead); jpeg := TBitmap.Create; jpeg.LoadFromStream(blob); blob.DisposeOf; if jpeg.Width > maxWidth then jpeg.Resize(maxWidth, Trunc(jpeg.Height / jpeg.Width * maxWidth)); blob := TMemoryStream.Create; jpeg.SaveToStream(blob); blob.Position := 0; SetLength(result, blob.Size); blob.Read(result[0], blob.Size); finally jpeg.DisposeOf; blob.DisposeOf; end; end; procedure TdmFieldLogger.LoadRandomImage; var imgs: TArray<System.string>; jpeg: TBitmap; idx: Integer; begin imgs := TDirectory.GetFiles('C:\Users\Jim\Documents\GitHub\FieldLogger-FMXTraining\ReportingDemo\RandomImages'); idx := Random(Length(imgs)); jpeg := TBitmap.CreateFromFile(imgs[idx]); try // resize the images to 512 on the largest size if jpeg.Height > jpeg.Width then jpeg.Resize(Trunc(jpeg.Width / jpeg.Height * 512), 512) else jpeg.Resize(512, Trunc(jpeg.Height / jpeg.Width * 512)); dmFieldLogger.qLogEntriesPicture.Assign(jpeg); finally jpeg.DisposeOf; end; end; procedure TdmFieldLogger.DataModuleCreate(Sender: TObject); begin {$ifdef ANDROID} conn.Params.Clear; conn.Params.DriverID := 'IBLite'; conn.Params.Database := TPath.Combine(TPath.GetDocumentsPath, 'EMBEDDEDIBLITE.IB'); {$ENDIF} conn.Params.UserName := 'sysdba'; conn.Params.Password := 'masterkey'; conn.Params.Values['CharacterSet'] := 'UTF8'; qProjects.Open(); qLogEntries.Open(); end; procedure TdmFieldLogger.qLogEntriesAfterInsert(DataSet: TDataSet); begin qLogEntriesLOG_ID.Value := Random(MaxInt); qLogEntriesTIMEDATESTAMP.AsDateTime := Now + (random(31) * (0.5-random)); qLogEntriesLONGITUDE.Value := Random + (179 - Random(360)); qLogEntriesLATITUDE.Value := Random + (89 - Random(180)); qLogEntriesOR_X.Value := Random - Random(2); qLogEntriesOR_Y.Value := Random - Random(2); qLogEntriesOR_Z.Value := Random - Random(2); qLogEntriesOR_DISTANCE.Value := Random; qLogEntriesHEADING_X.Value := 720 * Random - 360; qLogEntriesHEADING_Y.Value := 720 * Random - 360; qLogEntriesHEADING_Z.Value := 720 * Random - 360; qLogEntriesV_X.Value := 10 * Random; qLogEntriesV_Y.Value := 10 * Random; qLogEntriesV_Z.Value := 10 * Random; qLogEntriesANGLE_X.Value := 360 * Random; qLogEntriesANGLE_Y.Value := 360 * Random; qLogEntriesANGLE_Z.Value := 360 * Random; qLogEntriesMOTION.Value := 1000 * Random; qLogEntriesSPEED.Value := 100 * Random; LoadRandomImage; end; end.
unit sodbutils; {$mode objfpc}{$H+} interface uses Classes, SysUtils,SuperObject,DB; function Dataset2SO(DS:TDataset;AllRecords:Boolean=True):ISuperObject; procedure SO2Dataset(SO:ISuperObject;DS:TDataset;ExcludedFields:Array of String); implementation uses StrUtils,character,superdate,soutils; function StrIsOneOf(const S: string; const List: array of string): Boolean; var i:integer; begin Result := False; for i:=low(List) to High(List) do if List[i] = S then begin Result:=True; Exit; end; end; function Dataset2SO(DS: TDataset;AllRecords:Boolean=True): ISuperObject; var rec: ISuperObject; procedure Fillrec(rec:ISuperObject); var i:integer; begin for i:=0 to DS.Fields.Count-1 do begin if DS.Fields[i].IsNull then rec.N[DS.Fields[i].fieldname] := Nil else case DS.Fields[i].DataType of ftString : rec.S[DS.Fields[i].fieldname] := UTF8Decode(DS.Fields[i].AsString); ftInteger : rec.I[DS.Fields[i].fieldname] := DS.Fields[i].AsInteger; ftFloat : rec.D[DS.Fields[i].fieldname] := DS.Fields[i].AsFloat; ftBoolean : rec.B[DS.Fields[i].fieldname] := DS.Fields[i].AsBoolean; ftDateTime : rec.D[DS.Fields[i].fieldname] := DS.Fields[i].AsDateTime; else rec.S[DS.Fields[i].fieldname] := UTF8Decode(DS.Fields[i].AsString); end; end; end; begin if AllRecords then begin if not DS.Active then DS.Open; DS.First; Result := TSuperObject.Create(stArray); While not DS.EOF do begin rec := TSuperObject.Create(stObject); Result.AsArray.Add(rec); Fillrec(Rec); DS.Next; end; end else begin if not DS.Active then DS.Open; Result := TSuperObject.Create; Fillrec(Result); end; end; procedure SO2Dataset(SO: ISuperObject; DS: TDataset;ExcludedFields:Array of String); var arec : ISuperObject; procedure Fillrec(rec:ISuperObject); var i:integer; dt : TDateTime; begin for i:=0 to DS.Fields.Count-1 do begin if StrIsOneOf(DS.Fields[i].fieldname,ExcludedFields) then Continue; if rec.AsObject.Exists(DS.Fields[i].fieldname) then begin if ObjectIsNull(rec.N[DS.Fields[i].fieldname]) then DS.Fields[i].Clear else case DS.Fields[i].DataType of ftString : DS.Fields[i].AsString := UTF8Encode(rec.S[DS.Fields[i].fieldname]); ftInteger : DS.Fields[i].AsInteger := rec.I[DS.Fields[i].fieldname]; ftFloat : DS.Fields[i].AsFloat := rec.D[DS.Fields[i].fieldname]; ftBoolean : DS.Fields[i].AsBoolean := rec.B[DS.Fields[i].fieldname]; ftDateTime : DS.Fields[i].AsDateTime := rec.D[DS.Fields[i].fieldname]; else DS.Fields[i].AsString := UTF8Encode(rec.S[DS.Fields[i].fieldname]); end end end; end; begin // If SO is an array, we fill the dataset with all records if SO.DataType = stArray then begin for arec in SO do begin DS.Append; Fillrec(ARec); DS.Post; end; end else begin // If SO is a single object, we fill the dataset with one record if not (DS.State in dsEditModes) then DS.Append; Fillrec(SO); DS.Post; end; end; end.
unit LimitUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Mask, ToolEdit, CurrEdit; type TLimitForm = class(TForm) BitBtnSave: TBitBtn; BitBtnCancel: TBitBtn; Label2: TLabel; CurrencyEditInsurLimit: TCurrencyEdit; MemoInsurLimitName: TEdit; procedure BitBtnCancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure BitBtnSaveClick(Sender: TObject); procedure MemoInsurLimitNameEnter(Sender: TObject); private { Private declarations } public { Public declarations } InsurLimitNum:Integer; end; var LimitForm: TLimitForm; implementation uses DataUnit, InsNewMedUnit; {$R *.DFM} procedure TLimitForm.BitBtnCancelClick(Sender: TObject); begin Close; end; procedure TLimitForm.FormActivate(Sender: TObject); begin with DataModuleHM.AsaStoredProcShowInsurLimit do begin ParamByName('@InsurLimitNum').Value:=InsurLimitNum; Open; MemoInsurLimitName.Text:=DataModuleHM.AsaStoredProcShowInsurLimitInsurLimitName.Value; CurrencyEditInsurLimit.Value:=DataModuleHM.AsaStoredProcShowInsurLimitInsurLimitMoney.Value; Close; end; // with MemoInsurLimitName.SetFocus; end; procedure TLimitForm.BitBtnSaveClick(Sender: TObject); var new:Boolean; begin new:=InsurLimitNum=-1; if MemoInsurLimitName.Text='' then begin ShowMessage('Введи Название'); MemoInsurLimitName.SetFocus; Exit; end; try // statements to try begin with DataModuleHM do begin AsaSessionHM.StartTransaction; AsaStoredProcRefrInsurLimit.ParamByName('@InsurLimitNum').Value:=InsurLimitNum; AsaStoredProcRefrInsurLimit.ParamByName('@InsurLimitName').Value:=MemoInsurLimitName.Text; AsaStoredProcRefrInsurLimit.ParamByName('@InsurLimitMoney').Value:=CurrencyEditInsurLimit.Value; AsaStoredProcRefrInsurLimit.ExecProc; InsurLimitNum:=AsaStoredProcRefrInsurLimit.ParamByName('@InsurLimitNum').Value; AsaSessionHM.Commit; end; if new then with InsNewMedForm.ComboBoxLimit do begin Items.AddObject(MemoInsurLimitName.Text, TObject(InsurLimitNum)); ItemIndex:=Items.Count-1; end; // with end; except on e: Exception do begin ShowMessage('Ошибка '+ e.Message); DataModuleHM.AsaSessionHM.RollBack; end; end; // try/except Close; end; procedure TLimitForm.MemoInsurLimitNameEnter(Sender: TObject); begin LoadKeyboardLayout('00000419', KLF_ACTIVATE); // русский end; end.
unit DS104; interface uses Windows; const DS104_DLL = 'DvrSdk.dll'; type VidComArray = array[0..127] of char; //======================================================================== // DvrSdk.Dll API 调用接口 //======================================================================== const //视频流类型数据结构 VSubType_RGB32 = $0; VSubType_RGB24 = $1; VSubType_RGB16 = $2; VSubType_RGB15 = $3; VSubType_YUY2 = $4; VSubType_BTYUV = $5; VSubType_Y8 = $6; VSubType_RGB8 = $7; VSubType_PL422 = $8; VSubType_PL411 = $9; VSubType_YUV12 = $A; VSubType_YUV9 = $B; VSubType_RAW = $E; //视频制式数据结构 VStandard_NTSC = $1; VStandard_PAL = $3; VStandard_SECAM = $6; //录像视频制式数据结构 VRecord_NTSC = $0; VRecord_PAL = $1; //视频属性数据结构 VProperty_Brightness = $0; VProperty_Contrast = $1; VProperty_Hue = $2; VProperty_Saturation = $3; // //定义 MPEG4 捕捉时工作模式数据结构 MPEG4Mode_ToFile = 0; // 只能用于捕捉成文件 MPEG4Mode_Both = 1; // 可以捕捉成文件也能网传 MPEG4Mode_ToTransmit = 2; // 只能用于网传 // 捕捉模式定义 // 例如:要捕捉只有视频的 MPEG4 文件和捕捉音视流保存为 .WAV 文件,请使用 // 参数:CaptureMode_VO_MPEG4_FILE | CaptureMode_AO_WAV_FILE CaptureMode_VA_MPEG4_FILE = $FFFFFFFF; // 捕捉音视频复合的 MPEG4 文件 CaptureMode_VO_MPEG4_FILE = $FFF70000; // 捕捉只有视频的 MPEG4 文件 CaptureMode_VO_YUY2_FILE = $FFF00000; // 捕捉未压缩 YUY2 文件 CaptureMode_VO_USER = $FF000000; // 将捕捉到的视频流提供给用户 CaptureMode_AO_WAV_USER = $000000FF; // 将捕捉到的未压缩音频流提供给用户 CaptureMode_AO_ADPCM_USER = $00000FFF; // 将捕捉到的压缩音频ADPCM流提供给用户 CaptureMode_AO_WAV_FILE = $0000FFF7; // 捕捉音视流保存为 .WAV 文件 // MPEG4 录制参数设置 type RecordMPEGPara = record RecProperty_BitRate: DWORD; // 位率 (范围:56KBPS ~ 10MBPS) RecProperty_KeyFrameInterval: DWORD; // 关键帧间隔 (要求:大于等于帧率) RecProperty_FrameRate: DWORD; // 帧率 (范围:1 ~ 25(PAL)/30(NTSC)帧) RecProperty_VStandard: integer; // 视频制式 (取值:0 为NTSC, 1 为PAL) end; PRecordMPEGPara = ^RecordMPEGPara; // 系统函数 - 对所有DVR设备全局堆进行初始化 function HxnDVR_Init(hWnd: THandle): DWORD; stdcall; external DS104_DLL name 'HxnDVR_Init'; // 系统函数 - 对所有DVR设备全局堆占用资源进行释放 procedure HxnDVR_UnInit(); stdcall; external DS104_DLL name 'HxnDVR_UnInit'; //获取DVR设备的实际总数量 function HxnDVR_GetDeviceAmount(): DWORD; stdcall; external DS104_DLL name 'HxnDVR_GetDeviceAmount'; //系统函数 - 启动指定卡号的音视频设备, 可多次调用选择视频输入端口号 function HxnDVR_ConnectDevice(dwCardID: DWORD; m_Insel: Integer): Boolean; stdcall; external DS104_DLL name 'HxnDVR_ConnectDevice'; // 系统函数 - 判断当前设备是否已经启动 function HxnDVR_IsConnected(dwCardID: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_IsConnected'; // 系统函数 - 关闭指定卡号的音视频设备 procedure HxnDVR_DisconnectDevice(dwCardID: DWORD); stdcall; external DS104_DLL name 'HxnDVR_DisconnectDevice'; //设置当前设备要显示视频制式 function HxnDVR_SetVStandard(dwCardID: DWORD; vformat: Integer): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetVStandard'; // 系统函数 - 设置捕捉视频属性(亮度、对比度、色度、饱和度和锐度(清晰度)等) function HxnDVR_SetVPropertyValue(dwCardID: DWORD; pro: DWORD; dwValue: DWORD): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetVPropertyValue'; // 系统函数 - 获取捕捉视频尺寸大小 procedure HxnDVR_GetVidCapSize(dwCardID: integer; lpdwCapWidth: PDWORD; lpdwCapHeight: PDWORD); stdcall; external DS104_DLL name 'HxnDVR_GetVidCapSize'; // 系统函数 - 设置捕捉视频尺寸大小 function HxnDVR_SetVidCapSize(dwCardID: DWORD; dwCapWidth: DWORD; dwCapHeight: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_SetVidCapSize'; // 系统函数 - 获取显示、快照视频尺寸大小 (SDK7000 有效) procedure HxnDVR_GetVidPreSize(dwCardID: DWORD; lpdwCapWidth: PDWORD; lpdwCapHeight: PDWORD); stdcall; external DS104_DLL name 'HxnDVR_GetVidPreSize'; // 系统函数 - 设置显示、快照视频尺寸大小 (SDK7000 有效) function HxnDVR_SetVidPreSize(dwCardID: DWORD; dwCapWidth: DWORD; dwCapHeight: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_SetVidPreSize'; // 系统函数 - 获取当前使用视频压缩卡的ID号, 必须先调用 HxnDVR_Init function HxnDVR_GetCurrentCardID(RegID: string): boolean; stdcall; external DS104_DLL name 'HxnDVR_GetCurrentCardID'; //确定是否显示指定卡号的视频图像(不显示情况下将不进行视频流传输,能进一步降低系统资源占用)。 function HxnDVR_ShowWindow(dwCardId: DWORD; isShow: Boolean): Boolean; stdcall; external DS104_DLL name 'HxnDVR_ShowWindow'; //当只需要显示单路尺寸高度大于288请使用此函数。 function HxnDVR_SetOneScreenAnomaly(dwCardId: DWORD; hWnd: THandle; rc: PRect): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetOneScreenAnomaly'; //当只需要显示四路视频时的情况,每尺寸高度大于288请使用此函数, function HxnDVR_SetFourScreenAnomaly(dwCardId1, dwCardId2, dwCardId3, dwCardId4: DWORD; hWnd: THandle; rc: PRect): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetFourScreenAnomaly'; // 显示函数 - 设定指定卡号的视频图像位置,并由 HxnDVR_ShowWindow 决定是否显示 function HxnDVR_SetWindowPos(dwCardID: DWORD; hWnd: DWORD; rc: PRect): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetWindowPos'; //全屏显示或恢复正常显示指定卡号的视频设备 function HxnDVR_SetFullScreen(dwCardID: DWORD; isFull: Boolean): Boolean; stdcall; external DS104_DLL name 'HxnDVR_SetFullScreen'; // 显示函数 - 设置Logo内容(如场景说明等) function HxnDVR_SetLogoText(dwCardID: DWORD; szLogoText: string): boolean; stdcall; external DS104_DLL name 'HxnDVR_SetLogoText'; // 显示函数 - 显示或隐藏Logo procedure HxnDVR_ShowLogo(dwCardID: DWORD; bShow: Boolean; x: integer; y: integer); stdcall; external DS104_DLL name 'HxnDVR_ShowLogo'; // 显示函数 - 显示或隐藏时间 procedure HxnDVR_ShowTime(dwCardID: DWORD; bShow: Boolean; x: integer; y: integer); stdcall; external DS104_DLL name 'HxnDVR_ShowTime'; // 显示函数 - 显示或隐藏日期 procedure HxnDVR_ShowDate(dwCardID: DWORD; bShow: boolean; x: integer; y: integer); stdcall; external DS104_DLL name 'HxnDVR_ShowDate'; // 显示函数 - 画质显示增强模式, 选择范围(0,1,...14) function HxnDVR_ShowInfocus(dwCardID: DWORD; iMode: integer): boolean; stdcall; external DS104_DLL name 'HxnDVR_ShowInfocus'; // 显示函数 - 图像卜莱兹显示模式, 选择范围(0,1,...14) function HxnDVR_ShowInBlaze(dwCardID: DWORD; iMode: integer): boolean; stdcall; external DS104_DLL name 'HxnDVR_ShowInBlaze'; // 录像函数 - 设置要录制的文件名称和捕捉模式, 其中 dwMode 参考捕捉模式定义 function HxnDVR_SetCaptureFile(dwCardID: DWORD; filename: string; dwMode: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_SetCaptureFile'; // 录像函数 - 开始捕捉流或文件 function HxnDVR_StartCapture(dwCardID: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_StartCapture'; // 录像函数 - 停止捕捉流或文件 procedure HxnDVR_StopCapture(dwCardID: DWORD); stdcall; external DS104_DLL name 'HxnDVR_StopCapture'; // 录像函数 - 判断指定卡是否正在进行捕捉 function HxnDVR_IsVideoCapture(dwCardID: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_IsVideoCapture'; // 录像函数 - 获取 MPEG4 压缩流的录制参数和捕捉模式属性 procedure HxnDVR_GetMPEG4Property(dwCardID: DWORD; mpgPara: PRecordMPEGPara; lpdwMode: PDWORD); stdcall; external DS104_DLL name 'HxnDVR_GetMPEG4Property'; // 录像函数 - 设置 MPEG4 压缩流的录制参数和捕捉模式属性 procedure HxnDVR_SetMPEG4Property(dwCardID: DWORD; mpgPara: PRecordMPEGPara; dwMode: DWORD); stdcall; external DS104_DLL name 'HxnDVR_SetMPEG4Property'; // 抓图函数 - 抓拍 BMP 图片 function HxnDVR_SaveToBmpFile(dwCardID: DWORD; filename: string): boolean; stdcall; external DS104_DLL name 'HxnDVR_SaveToBmpFile'; // 抓图函数 - 抓拍 JPG 图片 function HxnDVR_SaveToJpgFile(dwCardID: DWORD; filename: string; dwQuality: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_SaveToJpgFile'; // 抓图函数 - 将图像存入剪贴板 function HxnDVR_CopyToClipboard(dwCardID: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_CopyToClipboard'; //启动动态监测 function HxnDVR_StartMotionDetect(dwCardId: DWORD): Boolean; stdcall; external DS104_DLL name 'HxnDVR_StartMotionDetect'; //停止动态监测 procedure HxnDVR_StopMotionDetect(dwCardId: DWORD); stdcall; external DS104_DLL name 'HxnDVR_StopMotionDetec'; // 显示函数 - 设置视频显示帧率 function HxnDVR_SetDisplayFrame(dwCardID: DWORD; iFrame: integer): boolean; stdcall; external DS104_DLL name 'HxnDVR_SetDisplayFrame'; // 显示函数 - 判断当前通道是否有视频图像输入 function HxnDVR_IsVideoSignalLocked(dwCardID: DWORD): boolean; stdcall; external DS104_DLL name 'HxnDVR_IsVideoSignalLocked'; // 系统函数 - 后台播放一个指定WAV文件 function HxnDVR_PlaySoundFromFile(m_hWnd: integer; // 播放窗口句柄 m_filename: string; // 要播放的WAV文件名 dwPrimaryChannels: integer; // 音频通道数如:2 dwPrimaryFreq: integer; // 频率如:22050 dwPrimaryBitRate: integer // 位率如:16 ): boolean; stdcall; external DS104_DLL name 'HxnDVR_PlaySoundFromFile'; implementation end.
unit HttpResponse; interface type HCkBinData = Pointer; HCkByteData = Pointer; HCkString = Pointer; HCkStringBuilder = Pointer; HCkHttpResponse = Pointer; HCkTask = Pointer; function CkHttpResponse_Create: HCkHttpResponse; stdcall; procedure CkHttpResponse_Dispose(handle: HCkHttpResponse); stdcall; procedure CkHttpResponse_getBody(objHandle: HCkHttpResponse; outPropVal: HCkByteData); stdcall; procedure CkHttpResponse_getBodyQP(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__bodyQP(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getBodyStr(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__bodyStr(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getCharset(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__charset(objHandle: HCkHttpResponse): PWideChar; stdcall; function CkHttpResponse_getContentLength(objHandle: HCkHttpResponse): LongWord; stdcall; function CkHttpResponse_getContentLength64(objHandle: HCkHttpResponse): Int64; stdcall; procedure CkHttpResponse_getDateStr(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__dateStr(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getDebugLogFilePath(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; procedure CkHttpResponse_putDebugLogFilePath(objHandle: HCkHttpResponse; newPropVal: PWideChar); stdcall; function CkHttpResponse__debugLogFilePath(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getDomain(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__domain(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getFinalRedirectUrl(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__finalRedirectUrl(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getFullMime(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__fullMime(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getHeader(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__header(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getLastErrorHtml(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__lastErrorHtml(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getLastErrorText(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__lastErrorText(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getLastErrorXml(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__lastErrorXml(objHandle: HCkHttpResponse): PWideChar; stdcall; function CkHttpResponse_getLastMethodSuccess(objHandle: HCkHttpResponse): wordbool; stdcall; procedure CkHttpResponse_putLastMethodSuccess(objHandle: HCkHttpResponse; newPropVal: wordbool); stdcall; function CkHttpResponse_getNumCookies(objHandle: HCkHttpResponse): Integer; stdcall; function CkHttpResponse_getNumHeaderFields(objHandle: HCkHttpResponse): Integer; stdcall; function CkHttpResponse_getStatusCode(objHandle: HCkHttpResponse): Integer; stdcall; procedure CkHttpResponse_getStatusLine(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__statusLine(objHandle: HCkHttpResponse): PWideChar; stdcall; procedure CkHttpResponse_getStatusText(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__statusText(objHandle: HCkHttpResponse): PWideChar; stdcall; function CkHttpResponse_getVerboseLogging(objHandle: HCkHttpResponse): wordbool; stdcall; procedure CkHttpResponse_putVerboseLogging(objHandle: HCkHttpResponse; newPropVal: wordbool); stdcall; procedure CkHttpResponse_getVersion(objHandle: HCkHttpResponse; outPropVal: HCkString); stdcall; function CkHttpResponse__version(objHandle: HCkHttpResponse): PWideChar; stdcall; function CkHttpResponse_GetBodyBd(objHandle: HCkHttpResponse; binData: HCkBinData): wordbool; stdcall; function CkHttpResponse_GetBodySb(objHandle: HCkHttpResponse; sb: HCkStringBuilder): wordbool; stdcall; function CkHttpResponse_GetCookieDomain(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getCookieDomain(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetCookieExpiresStr(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getCookieExpiresStr(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetCookieName(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getCookieName(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetCookiePath(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getCookiePath(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetCookieValue(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getCookieValue(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetHeaderField(objHandle: HCkHttpResponse; fieldName: PWideChar; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getHeaderField(objHandle: HCkHttpResponse; fieldName: PWideChar): PWideChar; stdcall; function CkHttpResponse_GetHeaderFieldAttr(objHandle: HCkHttpResponse; fieldName: PWideChar; attrName: PWideChar; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getHeaderFieldAttr(objHandle: HCkHttpResponse; fieldName: PWideChar; attrName: PWideChar): PWideChar; stdcall; function CkHttpResponse_GetHeaderName(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getHeaderName(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_GetHeaderValue(objHandle: HCkHttpResponse; index: Integer; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__getHeaderValue(objHandle: HCkHttpResponse; index: Integer): PWideChar; stdcall; function CkHttpResponse_LoadTaskResult(objHandle: HCkHttpResponse; task: HCkTask): wordbool; stdcall; function CkHttpResponse_SaveBodyBinary(objHandle: HCkHttpResponse; path: PWideChar): wordbool; stdcall; function CkHttpResponse_SaveBodyText(objHandle: HCkHttpResponse; bCrlf: wordbool; path: PWideChar): wordbool; stdcall; function CkHttpResponse_SaveLastError(objHandle: HCkHttpResponse; path: PWideChar): wordbool; stdcall; function CkHttpResponse_UrlEncParamValue(objHandle: HCkHttpResponse; encodedParamString: PWideChar; paramName: PWideChar; outStr: HCkString): wordbool; stdcall; function CkHttpResponse__urlEncParamValue(objHandle: HCkHttpResponse; encodedParamString: PWideChar; paramName: PWideChar): PWideChar; stdcall; implementation {$Include chilkatDllPath.inc} function CkHttpResponse_Create; external DLLName; procedure CkHttpResponse_Dispose; external DLLName; procedure CkHttpResponse_getBody; external DLLName; procedure CkHttpResponse_getBodyQP; external DLLName; function CkHttpResponse__bodyQP; external DLLName; procedure CkHttpResponse_getBodyStr; external DLLName; function CkHttpResponse__bodyStr; external DLLName; procedure CkHttpResponse_getCharset; external DLLName; function CkHttpResponse__charset; external DLLName; function CkHttpResponse_getContentLength; external DLLName; function CkHttpResponse_getContentLength64; external DLLName; procedure CkHttpResponse_getDateStr; external DLLName; function CkHttpResponse__dateStr; external DLLName; procedure CkHttpResponse_getDebugLogFilePath; external DLLName; procedure CkHttpResponse_putDebugLogFilePath; external DLLName; function CkHttpResponse__debugLogFilePath; external DLLName; procedure CkHttpResponse_getDomain; external DLLName; function CkHttpResponse__domain; external DLLName; procedure CkHttpResponse_getFinalRedirectUrl; external DLLName; function CkHttpResponse__finalRedirectUrl; external DLLName; procedure CkHttpResponse_getFullMime; external DLLName; function CkHttpResponse__fullMime; external DLLName; procedure CkHttpResponse_getHeader; external DLLName; function CkHttpResponse__header; external DLLName; procedure CkHttpResponse_getLastErrorHtml; external DLLName; function CkHttpResponse__lastErrorHtml; external DLLName; procedure CkHttpResponse_getLastErrorText; external DLLName; function CkHttpResponse__lastErrorText; external DLLName; procedure CkHttpResponse_getLastErrorXml; external DLLName; function CkHttpResponse__lastErrorXml; external DLLName; function CkHttpResponse_getLastMethodSuccess; external DLLName; procedure CkHttpResponse_putLastMethodSuccess; external DLLName; function CkHttpResponse_getNumCookies; external DLLName; function CkHttpResponse_getNumHeaderFields; external DLLName; function CkHttpResponse_getStatusCode; external DLLName; procedure CkHttpResponse_getStatusLine; external DLLName; function CkHttpResponse__statusLine; external DLLName; procedure CkHttpResponse_getStatusText; external DLLName; function CkHttpResponse__statusText; external DLLName; function CkHttpResponse_getVerboseLogging; external DLLName; procedure CkHttpResponse_putVerboseLogging; external DLLName; procedure CkHttpResponse_getVersion; external DLLName; function CkHttpResponse__version; external DLLName; function CkHttpResponse_GetBodyBd; external DLLName; function CkHttpResponse_GetBodySb; external DLLName; function CkHttpResponse_GetCookieDomain; external DLLName; function CkHttpResponse__getCookieDomain; external DLLName; function CkHttpResponse_GetCookieExpiresStr; external DLLName; function CkHttpResponse__getCookieExpiresStr; external DLLName; function CkHttpResponse_GetCookieName; external DLLName; function CkHttpResponse__getCookieName; external DLLName; function CkHttpResponse_GetCookiePath; external DLLName; function CkHttpResponse__getCookiePath; external DLLName; function CkHttpResponse_GetCookieValue; external DLLName; function CkHttpResponse__getCookieValue; external DLLName; function CkHttpResponse_GetHeaderField; external DLLName; function CkHttpResponse__getHeaderField; external DLLName; function CkHttpResponse_GetHeaderFieldAttr; external DLLName; function CkHttpResponse__getHeaderFieldAttr; external DLLName; function CkHttpResponse_GetHeaderName; external DLLName; function CkHttpResponse__getHeaderName; external DLLName; function CkHttpResponse_GetHeaderValue; external DLLName; function CkHttpResponse__getHeaderValue; external DLLName; function CkHttpResponse_LoadTaskResult; external DLLName; function CkHttpResponse_SaveBodyBinary; external DLLName; function CkHttpResponse_SaveBodyText; external DLLName; function CkHttpResponse_SaveLastError; external DLLName; function CkHttpResponse_UrlEncParamValue; external DLLName; function CkHttpResponse__urlEncParamValue; external DLLName; end.
{Dado un archivo de números enteros no nulos, almacenar en un arreglo A aquellos que sean ascendentes. A partir de A generar B con la misma cantidad de elementos de A pero poniendo ceros en aquellas componentes simétricas donde la simétrica derecha no sea múltiplo de la izquierda. Escribir ambos arreglos. Ejemplo: Archivo : 5, 7, 1, 12, 15, -10, 10, 24, -25, 26, 50, 13 A = (5, 7, 12, 15, 24, 26, 50) B= (5, 0, 12, 15, 24, 0, 50)} program guia5ej9; type TV=array[1..100] of integer; procedure LeerV(VAR V:TV;VAR N:integer); {lee el primer vector} var arch:text; n1,n2:integer; begin N:=1; assign (arch,'ej9.txt'); reset(arch); read(Arch,n1); V[N]:=n1; while not eof (arch) do begin read(arch,n2); if N2>N1 then begin N:=N+1; V[N]:=n2; n1:=n2; end; end; close(arch); end; procedure mostrarV(V:TV; N:integer); {muestro mi primer vector} var i:integer; begin For i:=1 to N do write(V[i],' '); end; Procedure multiplosV (V:TV;N:INTEGER; VAR W:TV); {calculo cuales son los multiplos de los simetricos} var i:integer; begin For i:=1 to (N div 2) do begin if (V[(N-i+1)] mod V[i] = 0) then begin W[i]:=V[i]; W[(N-i+1)]:=V[(N-i+1)]; end else begin W[i]:=0; W[(N-i+1)]:=0; end; end; end; procedure MostrarW(W:TV;N:INTEGER); {muestro W} var i:integer; begin for i:=1 to N do write(W[i],' '); end; var V,W:TV; N:INTEGER; begin leerV(V,N); Writeln('el vector v es ');mostrarV(V,N); multiplosV(V,N,W); writeln(); writeln('el vector w es ');MostrarW(W,N); readln(); end.
unit ReportWriterImpl; interface uses ReportParent, Variants, MyExcelReport, Graphics, Math, DateUtils, SysUtils, uDataManager, uDataModel, Windows, lyhTools, uConstAndType, RzListVw, ComCtrls, uOrderModel, Classes, FrmOutPutExcel; type TReportWriteManger = class(TReportParent) private FTestTemplateFile: string; FReportDest: string; procedure WriteOneProduct(AvData: OleVariant; ARow: Integer; AMainProduct: TMainProduct); public constructor Create(const ATestTemplateFile, ADestFileName: string); destructor Destroy; override; procedure WriteProductList(ARow, ASheetNo: Integer; AOrderModel: TOrderModel); procedure WriteClientTotalList(AListView: TRzListView; AStartRow, AColCount: Integer; const AClientName: string); procedure WriteCompanyTotalList(AListView: TRzListView; AStartRow, AColCount: Integer); procedure WriteTotalList(AListView: TRzListView; AStartRow, AColCount: Integer; const AClientName: string; bIsClient: Boolean); //procedure SetDestFileName(const ADestFileName: string); procedure WriteTotalExcel(ADataList: TList; AOutputExcelType: TOutputExcelType; AOutPutExcelCondition: TOutPutExcelCondition); property ReportDest: string read FReportDest; end; function GetCurDateTimeBySystemTime: string; implementation uses uControlInf, uStaticFunction; function GetCurDateTimeBySystemTime: string; var fmt: TFormatSettings; begin GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fmt); fmt.DecimalSeparator := '.'; fmt.TimeSeparator := '-'; fmt.LongTimeFormat := 'hh-nn-ss'; fmt.ShortTimeFormat := 'hh-nn-ss'; fmt.DateSeparator := '-'; fmt.ShortDateFormat := 'yyyy-mm-dd'; fmt.LongDateFormat := 'yyyy-mm-dd'; Result := DateTimeToStr(Now, fmt); //LocalmsgTime := GMTToLocale(msgTime); end; { TReportWriteManger } constructor TReportWriteManger.Create(const ATestTemplateFile, ADestFileName: string); var sPath, sFileName, sDateTime: string; begin inherited Create; FTestTemplateFile := ATestTemplateFile; sPath := ExtractFilePath(ParamStr(0)); sFileName := ExtractFileName(ATestTemplateFile); sDateTime := '_' + GetCurDateTimeBySystemTime; if IsEmptyStr(ADestFileName) then FReportDest := sPath + ChangeFileExt(sFileName, '') + sDateTime + ExtractFileExt(sFileName) else FReportDest := ADestFileName; KillOffice; FExcel.OpenFileEx(FTestTemplateFile, FReportDest, True); end; destructor TReportWriteManger.Destroy; begin FExcel.ActiveSheetNo := 1; FExcel.Save(FReportDest); inherited; end; procedure TReportWriteManger.WriteClientTotalList(AListView: TRzListView; AStartRow, AColCount: Integer; const AClientName: string); var sNoOneContent: string; begin sNoOneContent := '客户:' + Trim(AClientName); FReportDest := ExtractFilePath(FReportDest) + AClientName + '_' + ChangeFileExt(ExtractFileName(FReportDest), '') + ExtractFileExt(FReportDest); WriteTotalList(AListView, AStartRow, AColCount, sNoOneContent, True); end; procedure TReportWriteManger.WriteTotalList(AListView: TRzListView; AStartRow, AColCount: Integer; const AClientName: string; bIsClient: Boolean); var fr: TFillRange; iRegionCount, iInc, iRowNo, i, j, iTotalRow: Integer; vData: OleVariant; AFont: TFont; CellPro: TCellProperty; AListItem: TListItem; sFieldName, sTotalFieldName: string; begin FExcel.ActiveSheetNo := 1; iRegionCount := AListView.Items.Count; if (iRegionCount > 0) then begin for i := 0 to iRegionCount - 1 do begin FExcel.InsertRowExt(AStartRow); end; fr.FromCell.Row := AStartRow; fr.FromCell.Col := 1; fr.ToCell.Row := fr.FromCell.Row + iRegionCount - 1; fr.ToCell.Col := AColCount; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, AColCount, clBlack, [], 10); vData := VarArrayCreate([1, iRegionCount, 1, AColCount], varVariant); iRowNo := 0; for i := 0 to iRegionCount - 1 do begin Inc(iRowNo); iInc := (iRowNo + 1) div 2; AListItem := AListView.Items[i]; vData[iRowNo, 1] := iInc; for j := 0 to AListItem.SubItems.Count - 1 do begin sFieldName := AListItem.SubItems[j]; vData[iRowNo, (j + 2)] := sFieldName; end; end; if bIsClient then begin FExcel.TypeText(1, 1, AClientName); end; //求合计 // if ARow = 2 then // begin // sTotalFieldName := AProductList.GetTotalValue(tvtTotalCount); // iTotalRow := 6 + iRegionCount; // FExcel.TypeText(iTotalRow, 3, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtTotalSaleMoney); // FExcel.TypeText(iTotalRow, 8, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtTotalDiscountMoney); // FExcel.TypeText(iTotalRow, 9, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtTotalCashMoney); // FExcel.TypeText(iTotalRow, 10, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtFareCost); // FExcel.TypeText(iTotalRow, 11, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtFixCost); // FExcel.TypeText(iTotalRow, 12, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtProfitMoney); // FExcel.TypeText(iTotalRow, 13, sTotalFieldName); // // // sTotalFieldName := AProductList.GetTotalValue(tvtFareRate); // FExcel.TypeText((iTotalRow + 1), 13, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtDiscountRate); // FExcel.TypeText((iTotalRow + 1), 17, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtProfitMoney); // FExcel.TypeText((iTotalRow + 2), 13, sTotalFieldName); // // sTotalFieldName := AProductList.GetTotalValue(tvtProfitRate); // FExcel.TypeText((iTotalRow + 2), 17, sTotalFieldName); // end; end else begin FExcel.InsertRowExt(AStartRow); fr.FromCell.Row := AStartRow; fr.FromCell.Col := 1; fr.ToCell.Row := fr.FromCell.Row; fr.ToCell.Col := AColCount; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, AColCount, clBlack, [], 10); vData := VarArrayCreate([1, 1, 1, AColCount], varVariant); for i := 1 to AColCount do begin vData[1, i] := ''; end; end; AFont := TFont.Create; try AFont.Size := 10; CellPro.Font := AFont; CellPro.Applyed := True; CellPro.BorderLineStyle := blLine; FExcel.FillProperty(fr, CellPro); FExcel.FillData(fr, vData); FExcel.SetRangeAlign(fr, haCenter); finally FreeAndNil(AFont); end; {* 设置左对齐 *} FExcel.SetRangeAlignDefault(fr); end; procedure TReportWriteManger.WriteCompanyTotalList(AListView: TRzListView; AStartRow, AColCount: Integer); var fr: TFillRange; iRegionCount, iInc, i, j, iTotalRow: Integer; vData: OleVariant; AFont: TFont; CellPro: TCellProperty; AMainProduct: TMainProduct; sFieldName, sTotalFieldName: string; begin WriteTotalList(AListView, AStartRow, AColCount, EmptyStr, False); end; procedure TReportWriteManger.WriteOneProduct(AvData: OleVariant; ARow: Integer; AMainProduct: TMainProduct); var i: Integer; sFieldName: string; begin if Assigned(AMainProduct) then begin AvData[ARow, 1] := AMainProduct.GUIDSeqID; for i := 0 to AMainProduct.ItemCount - 1 do begin sFieldName := AMainProduct.PropertyContent[i]; AvData[ARow, (i + 2)] := sFieldName; end; end else begin for i := 1 to 16 do begin AvData[ARow, i] := ''; end; end; end; procedure TReportWriteManger.WriteProductList(ARow, ASheetNo: Integer; AOrderModel: TOrderModel); var fr: TFillRange; iRegionCount, iInc, i, j, iTotalRow: Integer; vData: OleVariant; AFont: TFont; CellPro: TCellProperty; AMainProduct: TMainProduct; sFieldName, sTotalFieldName: string; AProductList: TProductList; dAvgValue: Double; iTotalCount: Integer; begin FExcel.ActiveSheetNo := ASheetNo; AProductList := AOrderModel.OrderProductDetailList; iRegionCount := AProductList.ItemCount; if (iRegionCount > 0) then begin for i := 0 to iRegionCount - 1 do begin FExcel.InsertRowExt(ARow); end; fr.FromCell.Row := ARow; fr.FromCell.Col := 1; fr.ToCell.Row := fr.FromCell.Row + iRegionCount - 1; fr.ToCell.Col := 18; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, 18, clBlack, [], 10); vData := VarArrayCreate([1, iRegionCount, 1, 18], varVariant); iInc := 0; for i := 0 to iRegionCount - 1 do begin Inc(iInc); AMainProduct := AProductList.ProductItem[i]; vData[iInc, 1] := AMainProduct.GUIDSeqID; for j := 0 to AMainProduct.ItemCount - 1 do begin sFieldName := AMainProduct.PropertyContent[j]; vData[iInc, (j + 2)] := sFieldName; end; end; if ARow = 2 then begin sTotalFieldName := AProductList.GetTotalValue(tvtTotalCount); iTotalRow := 6 + iRegionCount; FExcel.TypeText(iTotalRow, 3, sTotalFieldName); iTotalCount := StrToInt(sTotalFieldName); sTotalFieldName := gGlobalControl.GetClientNameByClientId(AOrderModel.ClientId); FExcel.TypeText((iTotalRow + 1), 3, sTotalFieldName); sTotalFieldName := DateToStr(AOrderModel.OrderTime); FExcel.TypeText((iTotalRow + 2), 3, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtTotalSaleMoney); FExcel.TypeText(iTotalRow, 8, sTotalFieldName); if iTotalCount > 0 then dAvgValue := StrToFloat(sTotalFieldName) / iTotalCount else dAvgValue := 0; sTotalFieldName := Format('%.2f', [dAvgValue]); FExcel.TypeText((iTotalRow + 1), 8, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtTotalDiscountMoney); FExcel.TypeText(iTotalRow, 9, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtTotalCashMoney); FExcel.TypeText(iTotalRow, 10, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtFareCost); FExcel.TypeText(iTotalRow, 11, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtFixCost); FExcel.TypeText(iTotalRow, 12, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtProfitMoney); FExcel.TypeText(iTotalRow, 13, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtFareRate); FExcel.TypeText((iTotalRow + 1), 13, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtDiscountRate); FExcel.TypeText((iTotalRow + 1), 17, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtProfitMoney); FExcel.TypeText((iTotalRow + 2), 13, sTotalFieldName); sTotalFieldName := AProductList.GetTotalValue(tvtProfitRate); FExcel.TypeText((iTotalRow + 2), 17, sTotalFieldName); end; end else begin FExcel.InsertRowExt(ARow); fr.FromCell.Row := ARow; fr.FromCell.Col := 1; fr.ToCell.Row := fr.FromCell.Row; fr.ToCell.Col := 18; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, 18, clBlack, [], 10); vData := VarArrayCreate([1, 1, 1, 18], varVariant); for i := 1 to 18 do begin vData[1, i] := ''; end; end; AFont := TFont.Create; try AFont.Size := 10; CellPro.Font := AFont; CellPro.Applyed := True; CellPro.BorderLineStyle := blLine; FExcel.FillProperty(fr, CellPro); FExcel.FillData(fr, vData); FExcel.SetRangeAlign(fr, haCenter); finally FreeAndNil(AFont); end; {* 设置左对齐 *} FExcel.SetRangeAlignDefault(fr); end; //procedure TReportWriteManger.SetDestFileName(const ADestFileName: string); //begin // FReportDest := ADestFileName; //end; procedure TReportWriteManger.WriteTotalExcel(ADataList: TList; AOutputExcelType: TOutputExcelType; AOutPutExcelCondition: TOutPutExcelCondition); var fr: TFillRange; iRegionCount, iRowNo, i, iColAdd, iTotalRow: Integer; vData: OleVariant; AFont: TFont; CellPro: TCellProperty; AListItem: TListItem; sFieldName, sTotalFieldName: string; iStartRow, iStartCol, iColCount: Integer; AOutPutTotalResult: TOutPutTotalResult; iTotalCount: Integer; dTotalSaleMoney, dAvgSaleByOneBox, dProduceMaterial, dProduceMaterialRate, dProduceCost, dProduceCostRate, dProduceTotal, dProduceTotalRate, dTotalFareCost, dTotalDiscountMoney, dTotalYearEndReward, dTotalOtherCost, dSaleTotal, dSaleTotalRate, dFinanceTotal, dFinanceTotalRate, dTotalCost, dTotalCostRate, dTotalProfit, dTotalProfitRate: Double; iSumTotalCount: Integer; dSumTotalSaleMoney, dSumAvgSaleByOneBox, dSumProduceMaterial, dSumProduceMaterialRate, dSumProduceCost, dSumProduceCostRate, dSumProduceTotal, dSumProduceTotalRate, dSumTotalFareCost, dSumTotalDiscountMoney, dSumTotalYearEndReward, dSumTotalOtherCost, dSumSaleTotal, dSumSaleTotalRate, dSumFinanceTotal, dSumFinanceTotalRate, dSumTotalCost, dSumTotalCostRate, dSumTotalProfit, dSumTotalProfitRate: Double; begin FExcel.ActiveSheetNo := 1; case AOutputExcelType of oetAllArea, oetAllClient, oetAllMonth, oetAllDay: begin iStartRow := 5; iColCount := 23; iStartCol := 2; end; oetAllClientByOneArea, oetAllMonthByOneArea, oetAllMonthByOneClient, oetAllDayByOneClient: begin iStartRow := 5; iColCount := 24; iStartCol := 3; end; else ; end; iSumTotalCount := 0; dSumTotalSaleMoney := 0; dSumProduceMaterial := 0; dSumProduceCost := 0; dSumTotalFareCost := 0; dSumTotalDiscountMoney := 0; dSumTotalYearEndReward := 0; dSumTotalOtherCost := 0; dSumFinanceTotal := 0; iRegionCount := ADataList.Count; if (iRegionCount > 0) then begin for i := 0 to iRegionCount - 1 do begin FExcel.InsertRowExt(iStartRow); end; fr.FromCell.Row := iStartRow; fr.FromCell.Col := iStartCol; fr.ToCell.Row := fr.FromCell.Row + iRegionCount - 1; fr.ToCell.Col := iColCount; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, iColCount, clBlack, [], 10); case AOutputExcelType of oetAllClientByOneArea, oetAllMonthByOneArea: begin FExcel.TypeText(5, 2, AOutPutExcelCondition.FAreaName); end; oetAllMonthByOneClient, oetAllDayByOneClient: begin FExcel.TypeText(5, 2, AOutPutExcelCondition.FClientName); end; else ; end; case AOutputExcelType of oetAllClientByOneArea, oetAllMonthByOneArea, oetAllMonthByOneClient, oetAllDayByOneClient: begin FExcel.CombineCells(5, 2, (5 + iRegionCount), 2); end; else ; end; vData := VarArrayCreate([1, iRegionCount, 1, (iColCount - iStartCol + 1)], varVariant); iRowNo := 0; for i := 0 to iRegionCount - 1 do begin Inc(iRowNo); FExcel.TypeText((iRowNo + 4), 1, IntToStr(iRowNo)); AOutPutTotalResult := TOutPutTotalResult(ADataList.Items[i]); iTotalCount := AOutPutTotalResult.FTotalCount; dTotalSaleMoney := AOutPutTotalResult.FTotalSaleMoney; dProduceMaterial := AOutPutTotalResult.FTotalProduceMaterial; dProduceCost := AOutPutTotalResult.FTotalProduceCost; dTotalFareCost := AOutPutTotalResult.FTotalFareCost; dTotalDiscountMoney := AOutPutTotalResult.FTotalDiscountMoney; dTotalYearEndReward := AOutPutTotalResult.FTotalYearEndReward; dTotalOtherCost := AOutPutTotalResult.FTotalOtherCost; dFinanceTotal := AOutPutTotalResult.FTotalFinanceCost; dAvgSaleByOneBox := dTotalSaleMoney / iTotalCount; dProduceMaterialRate := dProduceMaterial / dTotalSaleMoney; dProduceCostRate := dProduceCost / dTotalSaleMoney; dProduceTotal := dProduceMaterial + dProduceCost; dProduceTotalRate := dProduceTotal / dTotalSaleMoney; dSaleTotal := dTotalFareCost + dTotalDiscountMoney + dTotalYearEndReward + dTotalOtherCost; dSaleTotalRate := dSaleTotal / dTotalSaleMoney; dFinanceTotalRate := dFinanceTotal / dTotalSaleMoney; dTotalCost := dProduceTotal + dSaleTotal + dFinanceTotal; dTotalCostRate := dTotalCost / dTotalSaleMoney; dTotalProfit := dTotalSaleMoney - dTotalCost; dTotalProfitRate := dTotalProfit / dTotalSaleMoney; iSumTotalCount := GetOperaterResult(iSumTotalCount, iTotalCount); dSumTotalSaleMoney := GetOperaterResult(dSumTotalSaleMoney, dTotalSaleMoney); dSumProduceMaterial := GetOperaterResult(dSumProduceMaterial, dProduceMaterial); dSumProduceCost := GetOperaterResult(dSumProduceCost, dProduceCost); dSumTotalFareCost := GetOperaterResult(dSumTotalFareCost, dTotalFareCost); dSumTotalDiscountMoney := GetOperaterResult(dSumTotalDiscountMoney, dTotalDiscountMoney); dSumTotalYearEndReward := GetOperaterResult(dSumTotalYearEndReward, dTotalYearEndReward); dSumTotalOtherCost := GetOperaterResult(dSumTotalOtherCost, dTotalOtherCost); dSumFinanceTotal := GetOperaterResult(dSumFinanceTotal, dFinanceTotal); dSumAvgSaleByOneBox := dSumTotalSaleMoney / iSumTotalCount; dSumProduceMaterialRate := dSumProduceMaterial / dSumTotalSaleMoney; dSumProduceCostRate := dSumProduceCost / dSumTotalSaleMoney; dSumProduceTotal := dSumProduceMaterial + dSumProduceCost; dSumProduceTotalRate := dSumProduceTotal / dSumTotalSaleMoney; dSumSaleTotal := dSumTotalFareCost + dSumTotalDiscountMoney + dSumTotalYearEndReward + dSumTotalOtherCost; dSumSaleTotalRate := dSumSaleTotal / dSumTotalSaleMoney; dSumFinanceTotalRate := dSumFinanceTotal / dSumTotalSaleMoney; dSumTotalCost := dSumProduceTotal + dSumSaleTotal + dSumFinanceTotal; dSumTotalCostRate := dSumTotalCost / dSumTotalSaleMoney; dSumTotalProfit := dSumTotalSaleMoney - dSumTotalCost; dSumTotalProfitRate := dSumTotalProfit / dSumTotalSaleMoney; vData[iRowNo, 1] := AOutPutTotalResult.FGroupFieldValue; vData[iRowNo, 2] := iTotalCount; vData[iRowNo, 3] := GetFloatFormat(dTotalSaleMoney, 2); vData[iRowNo, 4] := GetFloatFormat(dAvgSaleByOneBox, 2); vData[iRowNo, 5] := GetFloatFormat(dProduceMaterial, 2); vData[iRowNo, 6] := GetFloatFormat(dProduceMaterialRate); //百分比 vData[iRowNo, 7] := GetFloatFormat(dProduceCost, 2); vData[iRowNo, 8] := GetFloatFormat(dProduceCostRate); //百分比 vData[iRowNo, 9] := GetFloatFormat(dProduceTotal, 2); vData[iRowNo, 10] := GetFloatFormat(dProduceTotalRate); //百分比 vData[iRowNo, 11] := GetFloatFormat(dTotalFareCost, 2); vData[iRowNo, 12] := GetFloatFormat(dTotalDiscountMoney, 2); vData[iRowNo, 13] := GetFloatFormat(dTotalYearEndReward, 2); vData[iRowNo, 14] := GetFloatFormat(dTotalOtherCost, 2); vData[iRowNo, 15] := GetFloatFormat(dSaleTotal, 2); vData[iRowNo, 16] := GetFloatFormat(dSaleTotalRate); //百分比 vData[iRowNo, 17] := GetFloatFormat(dFinanceTotal, 2); vData[iRowNo, 18] := GetFloatFormat(dFinanceTotalRate); //百分比 vData[iRowNo, 19] := GetFloatFormat(dTotalCost, 2); vData[iRowNo, 20] := GetFloatFormat(dTotalCostRate); // 百分比 vData[iRowNo, 21] := GetFloatFormat(dTotalProfit, 2); vData[iRowNo, 22] := GetFloatFormat(dTotalProfitRate); //百分比 end; iTotalRow := 5 + iRegionCount; iColAdd := 0; case AOutputExcelType of oetAllClientByOneArea, oetAllMonthByOneArea, oetAllMonthByOneClient, oetAllDayByOneClient: begin iColAdd := 1; end; else ; end; //求合计 if iTotalRow > 0 then begin sTotalFieldName := IntToStr(iSumTotalCount); FExcel.TypeText(iTotalRow, (3 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalSaleMoney, 2); FExcel.TypeText(iTotalRow, (4 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumAvgSaleByOneBox, 2); FExcel.TypeText(iTotalRow, (5 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceMaterial, 2); FExcel.TypeText(iTotalRow, (6 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceMaterialRate, 4); FExcel.TypeText(iTotalRow, (7 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceCost, 2); FExcel.TypeText(iTotalRow, (8 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceCostRate, 4); FExcel.TypeText(iTotalRow, (9 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceTotal, 2); FExcel.TypeText(iTotalRow, (10 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumProduceTotalRate, 4); FExcel.TypeText(iTotalRow, (11 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalFareCost, 2); FExcel.TypeText(iTotalRow, (12 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalDiscountMoney, 2); FExcel.TypeText(iTotalRow, (13 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalYearEndReward, 2); FExcel.TypeText(iTotalRow, (14 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalOtherCost, 2); FExcel.TypeText(iTotalRow, (15 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumSaleTotal, 2); FExcel.TypeText(iTotalRow, (16 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumSaleTotalRate, 4); FExcel.TypeText(iTotalRow, (17 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumFinanceTotal, 2); FExcel.TypeText(iTotalRow, (18 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumFinanceTotalRate, 4); FExcel.TypeText(iTotalRow, (19 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalCost, 2); FExcel.TypeText(iTotalRow, (20 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalCostRate, 4); FExcel.TypeText(iTotalRow, (21 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalProfit, 2); FExcel.TypeText(iTotalRow, (22 + iColAdd), sTotalFieldName); sTotalFieldName := GetFloatFormat(dSumTotalProfitRate, 4); FExcel.TypeText(iTotalRow, (23 + iColAdd), sTotalFieldName); end; end else begin FExcel.InsertRowExt(iStartRow); fr.FromCell.Row := iStartRow; fr.FromCell.Col := iStartCol; fr.ToCell.Row := fr.FromCell.Row; fr.ToCell.Col := iColCount; FExcel.SetRangeFonts(fr.FromCell.Row, fr.ToCell.Row, 1, iColCount, clBlack, [], 10); vData := VarArrayCreate([1, 1, 1, iColCount - iStartRow + 1], varVariant); for i := 1 to (iColCount - iStartRow + 1) do begin vData[1, i] := ''; end; end; AFont := TFont.Create; try AFont.Size := 10; CellPro.Font := AFont; CellPro.Applyed := True; CellPro.BorderLineStyle := blLine; FExcel.FillProperty(fr, CellPro); FExcel.FillData(fr, vData); FExcel.SetRangeAlign(fr, haCenter); finally FreeAndNil(AFont); end; {* 设置左对齐 *} FExcel.SetRangeAlignDefault(fr); end; end.
unit Test1LoggingUnit; interface uses System.Generics.Collections,sysUtils, TestsUnit,Test1ExceptionUnit, CodeSiteLogging; type Test1Logging = class(TInterfacedObject, Tests) private /// <link>aggregation</link> TestExcept: Test1Exception; public procedure setTest(caption:string); function getQuest:TList<String>; function getAnswer:TList<String>; function getCorrect:TDictionary<integer,integer>; published constructor create; end; implementation { Test1Logging } constructor Test1Logging.create; begin CodeSite.Send('Test1.create'); TestExcept:=Test1Exception.create; TestExcept.create; end; function Test1Logging.getAnswer: TList<String>; begin CodeSite.Send('Test1.getAnswer'); result:=TestExcept.getAnswer; end; function Test1Logging.getCorrect: TDictionary<integer, integer>; begin CodeSite.Send('Test1.getCorrect'); result:=TestExcept.getCorrect; end; function Test1Logging.getQuest: TList<String>; begin CodeSite.Send('Test1.getQuest'); result:=TestExcept.getQuest; end; procedure Test1Logging.setTest(caption: string); begin CodeSite.Send('Test1.setTest'); TestExcept.setTest(caption); end; end.
unit UDbfPagedFile; interface uses classes, SysUtils, Dialogs; type xBaseVersion = (xUnknown,xClipper,xBaseIII,xBaseIV,xBaseV,xBaseVII,xFoxPro,xVisualFoxPro); EPagedFile = Exception; TPagedFileMode = (pfOpen,pfCreate); TPagedFile = class(TObject) private _Stream : TStream; _HeaderSize : Integer; _RecordSize : Integer; _RecordCount:integer; _Header:pchar; _NeedRecalc:boolean; protected _Mode:TPagedFileMode; _AutoCreate:boolean; _ReadOnly:boolean; _Filename:string; protected procedure _SetRecordSize(value:integer); virtual; procedure _SetHeaderSize(value:integer); virtual; procedure _FillHeader(c:byte); function _GetRecordCount:integer; public constructor Create(lFileName:string;Mode:TPagedFileMode;AutoCreate,ReadOnly:Boolean); destructor Destroy; override; procedure Close; procedure Open(Mode:TPagedFileMode;AutoCreate:boolean;ReadOnly:Boolean); procedure ReadRecord(IntRecNum:Integer;Buffer:Pointer); procedure WriteRecord(IntRecNum:Integer;Buffer:Pointer); procedure WriteHeader; virtual; procedure _SetRecordCount(value:Integer); procedure WriteChar(c:byte); procedure SeekPage(page:Integer); property HeaderSize : Integer read _HeaderSize write _SetHeaderSize; property RecordSize : Integer read _RecordSize write _SetRecordSize; property RecordCount : integer read _GetRecordCount write _SetRecordCount; property Header : PChar read _Header; property FileName : string read _Filename; end; implementation uses UDbfStrings; //==================================================================== // TPagedFile //==================================================================== constructor TPagedFile.Create(lFileName:string;Mode:TPagedFileMode;AutoCreate,ReadOnly:Boolean); begin _filename:=Uppercase(lFileName); Open(Mode,AutoCreate,ReadOnly); _HeaderSize:=0; _RecordSize:=0; _RecordCount:=0; _Mode:=Mode; _AutoCreate:=AutoCreate; _ReadOnly:=ReadOnly; _Header:=nil; end; destructor TPagedFile.Destroy; begin Close; inherited; end; Procedure TPagedFile.Open(Mode:TPagedFileMode;AutoCreate,ReadOnly:Boolean); var fileopenmode:word; begin if not fileExists(_FileName) then begin if AutoCreate or (Mode = pfCreate) then fileopenmode:=fmCreate else raise EPagedFile.CreateFmt(STRING_FILE_NOT_FOUND,[_FileName]); end else begin if ReadOnly then fileopenmode := fmOpenRead + fmShareDenyNone else fileopenmode := fmOpenReadWrite + fmShareDenyNone; // + fmShareDenyWrite; end; _Stream:=TFileStream.Create(_FileName, fileopenmode); if Mode=pfCreate then _Stream.Size:=0; end; Procedure TPagedFile.Close; begin _Stream.Free; _Stream:=nil; end; procedure TPagedFile.SeekPage(page:Integer); var p:Integer; begin p:=_HeaderSize + (_RecordSize * (page-1) ); _Stream.Position := p; end; Procedure TPagedFile.ReadRecord(IntRecNum:Integer; Buffer:Pointer); begin SeekPage(IntRecNum); _Stream.Read(Buffer^,_RecordSize); end; procedure TPagedFile.WriteRecord(IntRecNum:Integer; Buffer:Pointer); begin SeekPage(IntRecNum); _Stream.Write(Buffer^, _RecordSize); if IntRecNum>=_RecordCount then _RecordCount:=IntRecNum; end; procedure TPagedFile.WriteHeader; begin _Stream.Position := 0; _Stream.Write(_Header^, _HeaderSize); end; procedure TPagedFile._SetHeaderSize(value:integer); begin if _HeaderSize<>value then begin if _Header<>nil then FreeMem(_Header); _HeaderSize:=value; if _HeaderSize<>0 then GetMem(_Header,_HeaderSize) else _Header:=nil; _NeedRecalc:=true; _FillHeader(0); _Stream.Position := 0; _Stream.Read(_Header^,_HeaderSize); end; end; procedure TPagedFile._FillHeader(c:byte); begin if _Header=nil then exit; FillChar(_Header^,_HeaderSize,c); end; procedure TPagedFile._SetRecordSize(value:integer); begin if _RecordSize<>value then begin _RecordSize:=value; _NeedRecalc:=true; end; end; function TPagedFile._GetRecordCount:integer; begin if _NeedRecalc then begin if (_RecordSize=0) or (_Stream=nil) then _RecordCount:=0 else _RecordCount:=(_Stream.Size - _HeaderSize) div _RecordSize; if _RecordCount<0 then _RecordCount:=0; _NeedRecalc:=false; end; result:=_RecordCount; end; procedure TPagedFile._SetRecordCount(value:Integer); begin if (_RecordCount<>Value) then begin _Stream.Size:=_HeaderSize + _RecordSize * value; _RecordCount:=value; end; end; procedure TPagedFile.WriteChar(c:byte); begin _Stream.Write(c, 1); end; end.
unit HmgPlaneFunctionalTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath, BZVectorMathEx; type { THmgPlaneFunctionalTest } THmgPlaneFunctionalTest = class(TVectorBaseTestCase) protected {$CODEALIGN RECORDMIN=16} vt5 : TBZVector; ph1,ph2,ph3 : TBZHmgPlane; //TBZHmgPlaneHelper; procedure Setup; override; published procedure TestCreate3Vec; procedure TestCreatePointNorm; procedure TestDefaultPlane; procedure TestNormalizeSelf; procedure TestNormalize; procedure TestDistanceToPoint; procedure TestAbsDistanceToPoint; procedure TestDistanceToSphere; procedure TestPerpendicular; procedure TestReflect; procedure TestIsInHalfSpace; // helpers procedure TestContainsBSphere; end; implementation { THmgPlaneFunctionalTest } procedure THmgPlaneFunctionalTest.Setup; begin inherited Setup; vt1.Create(10.350,16.470,4.482,1.0); // decent hpoints paralel to xy plane vt2.Create(20.350,18.470,4.482,1.0); vt3.Create(10.350,10.470,2.482,1.0); vt4.Create(20.350,17.470,4.482,1.0); ph1.Create(vt1,vt4,vt2); // plane @z 4.482 z+ norm end; procedure THmgPlaneFunctionalTest.TestCreate3Vec; begin // create from three points ph1.Create(vt1,vt2,vt3); // all points should satisfy // plane.A*Point.X + plane.B*Point.Y + plane.C*Point.Z + PlaneD = 0 fs1 := ph1.A * vt1.X + ph1.B * vt1.Y + ph1.C * vt1.Z + ph1.D; AssertTrue('TBZHmgPlane:Create3Vec:sub1 Point 1 does not lie on plane', IsEqual(fs1,0, 1e-5)); fs1 := ph1.A * vt2.X + ph1.B * vt2.Y + ph1.C * vt2.Z + ph1.D; AssertTrue('TBZHmgPlane:Create3Vec:sub2 Point 2 does not lie on plane', IsEqual(fs1,0, 1e-5)); fs1 := ph1.A * vt3.X + ph1.B * vt3.Y + ph1.C * vt3.Z + ph1.D; AssertTrue('TBZHmgPlane:Create3Vec:sub3 Point 3 does not lie on plane', IsEqual(fs1,0, 1e-5)); fs1 := ph1.A * vt4.X + ph1.B * vt4.Y + ph1.C * vt4.Z + ph1.D; AssertFalse('TBZHmgPlane:Create3Vec:sub4 Point 4 does should not lie on plane', IsEqual(fs1,0, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestCreatePointNorm; var norm: TBZVector; begin // first off create a known working plane ph1.Create(vt1,vt2,vt3); norm.AsVector3f := ph1.AsNormal3; ph2.Create(vt3,norm); AssertTrue('TBZHmgPlane:CreatePointNorm:Sub1 planes do not match', compare(ph1,ph2, 1e-5)); fs1 := ph2.A * vt1.X + ph2.B * vt1.Y + ph2.C * vt1.Z + ph2.D; AssertTrue('TBZHmgPlane:Create3Vec:sub2 Point 1 does not lie on plane', IsEqual(fs1,0, 1e-5)); fs1 := ph2.A * vt2.X + ph2.B * vt2.Y + ph2.C * vt2.Z + ph2.D; AssertTrue('TBZHmgPlane:Create3Vec:sub3 Point 2 does not lie on plane', IsEqual(fs1,0, 1e-5)); // make a non normalized vector with the same direction // this plane is good for norm := norm * 3.56; ph2.Create(vt3,norm); fs1 := ph2.A * vt1.X + ph2.B * vt1.Y + ph2.C * vt1.Z + ph2.D; AssertTrue('TBZHmgPlane:Create3Vec:sub4 Point 1 does not lie on plane', IsEqual(fs1,0, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestDefaultPlane; begin AssertTrue('TBZHmgPlane:NormalizeSelf:Sub1 planes do not match', IsEqual(ph1.x,0)); AssertTrue('TBZHmgPlane:NormalizeSelf:Sub1 planes do not match', IsEqual(ph1.y,0)); AssertTrue('TBZHmgPlane:NormalizeSelf:Sub1 planes do not match', IsEqual(ph1.z,1)); AssertTrue('TBZHmgPlane:NormalizeSelf:Sub1 planes do not match', IsEqual(ph1.W,-4.482)); end; procedure THmgPlaneFunctionalTest.TestNormalizeSelf; var norm: TBZVector; begin norm.AsVector3f := ph1.AsNormal3; ph2.Create(vt4,norm); AssertTrue('TBZHmgPlane:NormalizeSelf:Sub1 planes do not match', compare(ph1,ph2)); norm := norm * 3.56; ph2.Create(vt4,norm); AssertFalse('TBZHmgPlane:NormalizeSelf:Sub2 planes should not match', compare(ph1,ph2)); ph2.Normalize; AssertTrue('TBZHmgPlane:NormalizeSelf:Sub3 planes do not match', compare(ph1,ph2, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestNormalize; var norm: TBZVector; begin ph1.Create(vt1,vt2,vt4); norm.AsVector3f := ph1.AsNormal3; // norm.Create(4,4,4); norm := norm * 3.56; ph2.Create(vt4,norm); AssertFalse('TBZHmgPlane:Normalize:Sub1 planes should not match', compare(ph1,ph2)); ph3 := ph2.Normalized; AssertTrue('TBZHmgPlane:NormalizeSelf:Sub2 planes do not match', compare(ph1,ph3, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestDistanceToPoint; begin vt5.Create(0,0,0,1); // // is this plane any use to this test. AssertTrue('TBZHmgPlane:DistanceToPoint:Sub1 Plane not suitable for test', (Abs(ph1.W) > 1)); fs1 := ph1.Distance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub2 Lengths do not match', IsEqual(ph1.W, fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W; vt5.W := 1; fs1 := ph1.Distance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub3 Lengths do not match', IsEqual(0, fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W * 2; vt5.W := 1; fs1 := ph1.Distance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub4 Lengths do not match', IsEqual(-ph1.W, fs1, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestAbsDistanceToPoint; begin vt5.Create(0,0,0,1); ph1.Create(vt1,vt2,vt4); // is this plane any use to this test. AssertTrue('TBZHmgPlane:DistanceToPoint:Sub1 Plane not suitable for test', (Abs(ph1.W) > 1)); fs1 := ph1.AbsDistance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub2 Lengths do not match', IsEqual(Abs(ph1.W), fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W; vt5.W := 1; fs1 := ph1.AbsDistance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub3 Lengths do not match', IsEqual(0, fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W * 2; vt5.W := 1; fs1 := ph1.AbsDistance(vt5); AssertTrue('TBZHmgPlane:DistanceToPoint:Sub4 Lengths do not match', IsEqual(Abs(ph1.W), fs1, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestDistanceToSphere; begin vt5.Create(0,0,0,1); fs1 := ph1.Distance(vt5, 2); // is this plane any use to this test. AssertTrue('TBZHmgPlane:DistanceToSphere:Sub1 Plane not suitable for test', (Abs(ph1.W) > 1)); AssertTrue('TBZHmgPlane:DistanceToSphere:Sub2 Lengths do not match', IsEqual(ph1.W + 2, fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W; vt5.W := 1; fs1 := ph1.Distance(vt5, 6); AssertTrue('TBZHmgPlane:DistanceToSphere:Sub3 Lengths do not match', IsEqual(0, fs1, 1e-5)); vt5 := ph1.AsVector * -ph1.W * 2; vt5.W := 1; fs1 := ph1.Distance(vt5,2); AssertTrue('TBZHmgPlane:DistanceToSphere:Sub4 Lengths do not match', IsEqual(-ph1.W - 2, fs1, 1e-5)); end; procedure THmgPlaneFunctionalTest.TestIsInHalfSpace; begin vt5.Create(0,0,0,1); nb := ph1.IsInHalfSpace(vt5); // is this plane any use to this test. AssertTrue('TBZHmgPlane:IsInHalfSpace:Sub1 Plane not suitable for test', (Abs(ph1.W) > 1)); if ph1.W > 0 then // origin should be in half space AssertTrue('TBZHmgPlane:InHalfSpace:Sub2 half space failed', nb) else AssertFalse('TBZHmgPlane:InHalfSpace:Sub2 half space failed', nb); vt5 := ph1.AsVector * (abs(ph1.W) * 2); vt5.W := 1; nb := ph1.IsInHalfSpace(vt5); if ph1.W > 0 then // origin should be in half space AssertFalse('TBZHmgPlane:InHalfSpace:Sub3 half space failed', nb) else AssertTrue('TBZHmgPlane:InHalfSpace:Sub3 half space failed', nb); end; procedure THmgPlaneFunctionalTest.TestPerpendicular; begin vt1.Create(2,2,2,1); ph1.Create(NullHmgPoint,XHmgPoint,YHmgPoint); // z perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub1 X failed ', 2, vt4.X); AssertEquals('Perpendicular:Sub2 Y failed ', 2, vt4.Y); AssertEquals('Perpendicular:Sub3 Z failed ', 0, vt4.Z); // Z cancelled out AssertEquals('Perpendicular:Sub4 W failed ', 1, vt4.W); ph1.Create(NullHmgPoint,YHmgPoint,XHmgPoint); // -z perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub5 X failed ', 2, vt4.X); AssertEquals('Perpendicular:Sub6 Y failed ', 2, vt4.Y); AssertEquals('Perpendicular:Sub7 Z failed ', 0, vt4.Z); AssertEquals('Perpendicular:Sub8 W failed ', 1, vt4.W); ph1.Create(NullHmgPoint,YHmgPoint,ZHmgPoint); // x perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub9 X failed ', 0, vt4.X); AssertEquals('Perpendicular:Sub10 Y failed ', 2, vt4.Y); AssertEquals('Perpendicular:Sub11 Z failed ', 2, vt4.Z); AssertEquals('Perpendicular:Sub12 W failed ', 1, vt4.W); ph1.Create(NullHmgPoint,ZHmgPoint,YHmgPoint); // -x perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub13 X failed ', 0, vt4.X); AssertEquals('Perpendicular:Sub14 Y failed ', 2, vt4.Y); AssertEquals('Perpendicular:Sub15 Z failed ', 2, vt4.Z); AssertEquals('Perpendicular:Sub16 W failed ', 1, vt4.W); ph1.Create(NullHmgPoint,ZHmgPoint,XHmgPoint); // y perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub21 X failed ', 2, vt4.X); AssertEquals('Perpendicular:Sub22 Y failed ', 0, vt4.Y); AssertEquals('Perpendicular:Sub23 Z failed ', 2, vt4.Z); AssertEquals('Perpendicular:Sub24 W failed ', 1, vt4.W); ph1.Create(NullHmgPoint,XHmgPoint,ZHmgPoint); // -y perp vt4 := ph1.Perpendicular(vt1); AssertEquals('Perpendicular:Sub17 X failed ', 2, vt4.X); AssertEquals('Perpendicular:Sub18 Y failed ', 0, vt4.Y); AssertEquals('Perpendicular:Sub19 Z failed ', 2, vt4.Z); AssertEquals('Perpendicular:Sub20 W failed ', 1, vt4.W); end; procedure THmgPlaneFunctionalTest.TestReflect; begin ph1.Create(NullHmgPoint,XHmgPoint,YHmgPoint); // z perp normalised plane. vt1.Create(1,0,-1,0); // vector heading in x dir down towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub1 X failed ', 1, vt4.X); // should continue in x dir AssertEquals('Reflect:Sub2 Y failed ', 0, vt4.Y); // get no y component AssertEquals('Reflect:Sub3 Z failed ', 1, vt4.Z); // same Angle but upward i.e. reversed Z AssertEquals('Reflect:Sub4 W failed ', 0, vt4.W); vt1.Create(1,0,1,0); // vector heading in x dir up towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub5 X failed ', 1, vt4.X); // should continue in x dir AssertEquals('Reflect:Sub6 Y failed ', 0, vt4.Y); // get no y component AssertEquals('Reflect:Sub7 Z failed ', -1, vt4.Z); // same Angle but downward i.e. reversed Z AssertEquals('Reflect:Sub8 W failed ', 0, vt4.W); ph1.Create(NullHmgPoint,YHmgPoint,ZHmgPoint); // x perp vt1.Create(-1,1,1,0); // vector heading in y,z dir down towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub9 X failed ', 1, vt4.X); // same Angle but upward i.e. reversed x AssertEquals('Reflect:Sub10 Y failed ', 1, vt4.Y); // should continue in y dir AssertEquals('Reflect:Sub11 Z failed ', 1, vt4.Z); // should continue in z dir AssertEquals('Reflect:Sub12 W failed ', 0, vt4.W); vt1.Create(1,1,1,0); // vector heading in y,z dir up towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub13 X failed ', -1, vt4.X); // same Angle but downward i.e. reversed x AssertEquals('Reflect:Sub14 Y failed ', 1, vt4.Y); // should continue in y dir AssertEquals('Reflect:Sub15 Z failed ', 1, vt4.Z); // should continue in z dir AssertEquals('Reflect:Sub16 W failed ', 0, vt4.W); ph1.Create(NullHmgPoint,ZHmgPoint,XHmgPoint); // y perp vt1.Create(1,-1,1,0); // vector heading in x,z dir down towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub17 X failed ', 1, vt4.X); // should continue in x dir AssertEquals('Reflect:Sub18 Y failed ', 1, vt4.Y); // same Angle but upward i.e. reversed y AssertEquals('Reflect:Sub19 Z failed ', 1, vt4.Z); // should continue in z dir AssertEquals('Reflect:Sub20 W failed ', 0, vt4.W); vt1.Create(1,1,1,0); // vector heading in y,z dir up towards plane vt4:= ph1.Reflect(vt1); AssertEquals('Reflect:Sub21 X failed ', 1, vt4.X); // should continue in x dir AssertEquals('Reflect:Sub22 Y failed ', -1, vt4.Y); // same Angle but downward i.e. reversed y AssertEquals('Reflect:Sub23 Z failed ', 1, vt4.Z); // should continue in z dir AssertEquals('Reflect:Sub24 W failed ', 0, vt4.W); end; procedure THmgPlaneFunctionalTest.TestContainsBSphere; var sp: TBZBoundingSphere; ct: TBZSpaceContains; begin vt5.Create(0,0,0,1); // is this plane any use to this test. AssertTrue('TBZHmgPlane:ContainsBSphere:Sub1 Plane not suitable for test', (Abs(ph1.W) > 2)); // sphere should not be touching plane sp.Create(vt5,1); ct := ph1.Contains(sp); AssertTrue('TBZHmgPlane:ContainsBSphere:Sub2 Plane should not contain BSphere', (ScNoOverlap = ct)); // grow sphere so it does touch the plane sp.Radius:= abs(ph1.W * 1.1); ct := ph1.Contains(sp); AssertTrue('TBZHmgPlane:ContainsBSphere:Sub3 Plane should partially contain BSphere', (ScContainsPartially = ct)); // is vt5 instance still center instance // shrink sphere sp.Radius := 1; vt5 := ph1.AsVector * abs(ph1.W); // set vt5 to sit on plane AssertFalse('TBZHmgPlane:ContainsBSphere:Sub4 Points are the same instance something changed', Compare(vt5,sp.Center)); // small sphere center now sits on plane sp.Center := vt5; ct := ph1.Contains(sp); AssertTrue('TBZHmgPlane:ContainsBSphere:Sub5 Plane should contain BSphere', (ScContainsPartially = ct)); vt5 := ph1.AsVector * (abs(ph1.W) * 2); // set sphere to sit in other side of plane vt5.W := 1; sp.Center := vt5; ct := ph1.Contains(sp); AssertTrue('TBZHmgPlane:ContainsBSphere:Sub6 Plane should fully contain BSphere', (ScContainsFully = ct)); end; initialization RegisterTest(REPORT_GROUP_PLANE_HELP, THmgPlaneFunctionalTest); end.
unit sCheckBox; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, sFade{$IFNDEF DELPHI5}, Types{$ENDIF}, {$IFDEF TNTUNICODE}TntControls, TntActnList, TntForms, TntClasses, {$ENDIF} StdCtrls, sCommonData, sConst, sDefaults, imglist{$IFDEF LOGGED}, sDebugMsgs{$ENDIF}; type {$IFNDEF NOTFORHELP} TsImageIndex = integer; {$ENDIF} // NOTFORHELP TsCheckBox = class(TCustomCheckBox) {$IFNDEF NOTFORHELP} private FCommonData: TsCommonData; FDisabledKind: TsDisabledKind; FGlyphUnChecked: TBitmap; FGlyphChecked: TBitmap; FTextIndent: integer; FPressed : boolean; FShowFocus: Boolean; FMargin: integer; FadeTimer : TsFadeTimer; FImages: TCustomImageList; FImgChecked: TsImageIndex; FImgUnchecked: TsImageIndex; FAnimatEvents: TacAnimatEvents; {$IFNDEF DELPHI7UP} FWordWrap : boolean; procedure SetWordWrap(const Value: boolean); {$ENDIF} procedure SetDisabledKind(const Value: TsDisabledKind); procedure SetGlyphChecked(const Value: TBitmap); procedure SetGlyphUnChecked(const Value: TBitmap); procedure SetTextIndent(const Value: integer); procedure SetShowFocus(const Value: Boolean); procedure SetMargin(const Value: integer); procedure SetReadOnly(const Value: boolean); procedure SetImageChecked(const Value: TsImageIndex); procedure SetImages(const Value: TCustomImageList); procedure SetImageUnChecked(const Value: TsImageIndex); {$IFDEF TNTUNICODE} function GetCaption: TWideCaption; procedure SetCaption(const Value: TWideCaption); function GetHint: WideString; procedure SetHint(const Value: WideString); function IsCaptionStored: Boolean; function IsHintStored: Boolean; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; {$ENDIF} protected FReadOnly: boolean; function GetReadOnly: boolean; virtual; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; procedure SetChecked(Value: Boolean); override; procedure PaintHandler(M : TWMPaint); procedure PaintControl(DC : HDC); procedure DrawCheckText; procedure DrawCheckArea; procedure DrawSkinGlyph(i : integer); procedure PaintGlyph(Bmp : TBitmap; const Index : integer); function SkinGlyphWidth(i : integer) : integer; function SkinGlyphHeight(i : integer) : integer; function SkinCheckRect(i : integer): TRect; function Glyph : TBitmap; function CheckRect: TRect; function GlyphWidth : integer; function GlyphHeight : integer; function GlyphMaskIndex(State : TCheckBoxState) : smallint; procedure PrepareCache; {$IFDEF TNTUNICODE} procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; {$ENDIF} public function GetControlsAlignment: TAlignment; override; procedure AfterConstruction; override; constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure WndProc(var Message: TMessage); override; published {$IFDEF TNTUNICODE} property Caption: TWideCaption read GetCaption write SetCaption stored IsCaptionStored; property Hint: WideString read GetHint write SetHint stored IsHintStored; {$ELSE} property Caption; {$ENDIF} property Action; property Align; property Alignment; property AllowGrayed; property Anchors; property AutoSize default True; property BiDiMode; property Checked; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property State; property TabOrder; property TabStop; property Visible; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; property Margin : integer read FMargin write SetMargin default 2; {$ENDIF} // NOTFORHELP property AnimatEvents : TacAnimatEvents read FAnimatEvents write FAnimatEvents default [aeGlobalDef]; property SkinData : TsCommonData read FCommonData write FCommonData; property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind; property GlyphChecked : TBitmap read FGlyphChecked write SetGlyphChecked; property GlyphUnChecked : TBitmap read FGlyphUnChecked write SetGlyphUnChecked; property ImgChecked : TsImageIndex read FImgChecked write SetImageChecked; property ImgUnchecked : TsImageIndex read FImgUnchecked write SetImageUnChecked; property Images : TCustomImageList read FImages write SetImages; property ReadOnly : boolean read GetReadOnly write SetReadOnly default False; property ShowFocus: Boolean read FShowFocus write SetShowFocus default True; property TextIndent : integer read FTextIndent write SetTextIndent default 0; {$IFNDEF DELPHI7UP} property WordWrap : boolean read FWordWrap write SetWordWrap default False; {$ELSE} property WordWrap default False; {$ENDIF} {$IFDEF D2007} property OnMouseEnter; property OnMouseLeave; {$ENDIF} end; {$IFNDEF NOTFORHELP} var PaintState : integer = -1; {$ENDIF} implementation uses sGraphUtils, acntUtils, sAlphaGraph, sVclUtils, sStylesimply, sSkinProps, acAlphaImageList, Math, sMessages, sSKinManager{$IFDEF CHECKXP}, UxTheme, Themes{$ENDIF}; { TsCheckBox } procedure TsCheckBox.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin {$IFDEF TNTUNICODE} TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); {$ENDIF} FCommonData.BGChanged := True; inherited; Repaint; end; procedure TsCheckBox.AfterConstruction; begin inherited; SkinData.Loaded; end; function TsCheckBox.GetControlsAlignment: TAlignment; begin if not UseRightToLeftAlignment then Result := Alignment else if Alignment = taRightJustify then Result := taLeftJustify else Result := taRightJustify; end; function TsCheckBox.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; var ss : TSize; R : TRect; w, h : integer; begin Result := False; if FCommonData.Skinned then begin if csLoading in ComponentState then Exit; if AutoSize then begin ss := GetStringSize(Font.Handle, Caption); R := CheckRect; NewWidth := WidthOf(R) + 2 * Margin + (ss.cx + FTextIndent + 8) * integer(Caption <> ''); NewHeight := Max(HeightOf(R), 2 * Margin + ss.cy * integer(Caption <> '')) + 2; Result := True; w := NewWidth; h := NewHeight; end; end else begin if AutoSize then begin ss := GetStringSize(Font.Handle, Caption); NewWidth := ss.cx + 20; NewHeight := max(ss.cy + 4, 20); Result := True; end else begin w := NewWidth; h := NewHeight; Result := inherited CanAutoSize(w, h); NewWidth := w; NewHeight := h; end; end; end; function TsCheckBox.CheckRect: TRect; var i : integer; begin if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin if GetControlsAlignment = taRightJustify then Result := Rect(Margin, (Height - GlyphHeight) div 2, Margin + GlyphWidth, GlyphHeight + (Height - GlyphHeight) div 2) else Result := Rect(Width - GlyphWidth - Margin, (Height - GlyphHeight) div 2, Width - Margin, GlyphHeight + (Height - GlyphHeight) div 2) end else if FGlyphChecked.Width > 0 then begin if GetControlsAlignment = taRightJustify then Result := Rect(Margin, (Height - GlyphHeight) div 2, Margin + GlyphWidth, GlyphHeight + (Height - GlyphHeight) div 2) else Result := Rect(Width - GlyphWidth - Margin, (Height - GlyphHeight) div 2, Width - Margin, GlyphHeight + (Height - GlyphHeight) div 2) end else begin i := GlyphMaskIndex(cbChecked); if FCommonData.SkinManager.IsValidImgIndex(i) then Result := SkinCheckRect(i) else Result := Rect(0, 0, 16, 16); end; end; {$IFDEF TNTUNICODE} procedure TsCheckBox.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsWideCharAccel(Message.CharCode, Caption) and CanFocus then begin SetFocus; if Focused then Toggle; Result := 1; end else Broadcast(Message); end; {$ENDIF} constructor TsCheckBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommonData := TsCommonData.Create(Self, False); FCommonData.COC := COC_TsCheckBox; FCommonData.FOwnerControl := Self; FadeTimer := nil; FMargin := 2; FShowFocus := True; FTextIndent := 0; FDisabledKind := DefDisabledKind; FGlyphChecked := TBitmap.Create; FGlyphUnChecked := TBitmap.Create; FAnimatEvents := [aeGlobalDef]; {$IFNDEF DELPHI7UP} FWordWrap := False; {$ELSE} WordWrap := False; {$ENDIF} FPressed := False; AutoSize := True; end; {$IFDEF TNTUNICODE} procedure TsCheckBox.CreateWindowHandle(const Params: TCreateParams); begin CreateUnicodeHandle(Self, Params, 'BUTTON'); end; procedure TsCheckBox.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; {$ENDIF} destructor TsCheckBox.Destroy; begin StopFading(FadeTimer, FCommonData); if Assigned(FCommonData) then FreeAndNil(FCommonData); if Assigned(FGlyphChecked) then FreeAndNil(FGlyphChecked); if Assigned(FGlyphUnchecked) then FreeAndNil(FGlyphUnChecked); if Assigned(FadeTimer) then FreeAndNil(FadeTimer); inherited Destroy; end; const CheckBoxStates : array[0..2] of TCheckBoxState = (cbUnchecked, cbChecked, cbGrayed); procedure TsCheckBox.DrawCheckArea; var CheckArea: TRect; i, ImgIndex, GlyphCount, GlyphIndex : integer; TempBmp : TBitmap; R : TRect; begin if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin ImgIndex := iffi(Checked, ImgChecked, ImgUnChecked); if (ImgIndex < 0) then Exit; R := CheckRect; GlyphCount := Images.Width div Images.Height; if (GlyphCount > 1) and (Images.Width mod Images.Height = 0) then begin // If complex image TempBmp := TBitmap.Create; if Images is TsAlphaImageList then begin if not TsAlphaImageList(Images).GetBitmap32(ImgIndex, TempBmp) then Exit end {$IFDEF DELPHI5} else Images.GetBitmap(ImgIndex, TempBmp); {$ELSE} else if not Images.GetBitmap(ImgIndex, TempBmp) then Exit; {$ENDIF} if FPressed then GlyphIndex := min(2, GlyphCount - 1) else if ControlIsActive(FCommonData) and not ReadOnly then GlyphIndex := min(1, GlyphCount - 1) else GlyphIndex := 0; PaintGlyph(TempBmp, GlyphIndex); FreeAndNil(TempBmp); end else Images.Draw(FCommonData.FCacheBmp.Canvas, R.Left, R.Top, ImgIndex, True); end else if Glyph <> nil then begin CheckArea := CheckRect; GlyphCount := Glyph.Width div Glyph.Height; if FPressed then GlyphIndex := min(2, GlyphCount - 1) else if ControlIsActive(FCommonData) and not ReadOnly then GlyphIndex := min(1, GlyphCount - 1) else GlyphIndex := 0; if Glyph.Width <> 0 then PaintGlyph(Glyph, GlyphIndex); end else begin if PaintState <> - 1 then i := GlyphMaskIndex(CheckBoxStates[PaintState]) else i := GlyphMaskIndex(State); if SkinData.SkinManager.IsValidImgIndex(i) then DrawSkinGlyph(i); end; end; procedure TsCheckBox.DrawCheckText; var rText: TRect; Fmt: integer; t, b, w, h, dx : integer; begin if Caption <> '' then begin w := Width - (WidthOf(CheckRect) + FTextIndent + 2 * Margin + 2); rText := Rect(0, 0, w, 0); Fmt := DT_CALCRECT; if WordWrap then Fmt := Fmt or DT_WORDBREAK else Fmt := Fmt or DT_SINGLELINE; AcDrawText(FCommonData.FCacheBMP.Canvas.Handle, Caption, rText, Fmt); h := HeightOf(rText); dx := WidthOf(rText); t := Max((Height - h) div 2, Margin); b := t + h; Fmt := DT_TOP; if Alignment = taRightJustify then begin if IsRightToLeft then begin rText.Right := Width - Margin - WidthOf(CheckRect) - FTextIndent - 4; rText.Left := rText.Right - dx; rText.Top := t; rText.Bottom := b; if not WordWrap then Fmt := DT_RIGHT; end else begin rText := Rect(Width - w - Margin + 2, t, Width - w - Margin + 2 + dx, b); end; end else begin rText := Rect(Margin, t, w + Margin, b); end; OffsetRect(rText, -integer(WordWrap), -1); if WordWrap then Fmt := Fmt or DT_WORDBREAK else Fmt := Fmt or DT_SINGLELINE; if UseRightToLeftReading then Fmt := Fmt or DT_RTLREADING; acWriteTextEx(FCommonData.FCacheBmp.Canvas, PacChar(Caption), True, rText, Fmt, FCommonData, ControlIsActive(FCommonData) and not ReadOnly); FCommonData.FCacheBmp.Canvas.Pen.Style := psClear; FCommonData.FCacheBmp.Canvas.Brush.Style := bsSolid; if Focused and ShowFocus then begin dec(rText.Bottom, integer(not WordWrap)); inc(rText.Top); InflateRect(rText, 1, 1); FocusRect(FCommonData.FCacheBmp.Canvas, rText); end; end; end; procedure TsCheckBox.DrawSkinGlyph(i: integer); var R : TRect; Mode : integer; begin if FCommonData.FCacheBmp.Width < 1 then exit; R := SkinCheckRect(i); if FPressed then Mode := 2 else if ControlIsActive(FCommonData) and not ReadOnly then Mode := 1 else Mode := 0; sAlphaGraph.DrawSkinGlyph(FCommonData.FCacheBmp, R.TopLeft, Mode, 1, FCommonData.SkinManager.ma[i], MakeCacheInfo(SkinData.FCacheBmp)) end; {$IFDEF TNTUNICODE} function TsCheckBox.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; function TsCheckBox.GetCaption: TWideCaption; begin Result := TntControl_GetText(Self) end; function TsCheckBox.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; {$ENDIF} function TsCheckBox.GetReadOnly: boolean; begin Result := FReadOnly; end; function TsCheckBox.GlyphHeight: integer; begin if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin Result := Images.Height; end else begin if Glyph <> nil then Result := Glyph.Height else Result := 16; end; end; function TsCheckBox.GlyphMaskIndex(State: TCheckBoxState): smallint; begin case State of cbChecked : Result := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinManager.ConstData.IndexGLobalInfo, s_GLobalInfo, s_CheckBoxChecked); cbUnchecked : Result := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinManager.ConstData.IndexGLobalInfo, s_GLobalInfo, s_CheckBoxUnChecked) else Result := FCommonData.SkinManager.GetMaskIndex(FCommonData.SkinManager.ConstData.IndexGLobalInfo, s_GLobalInfo, s_CheckBoxGrayed); end; end; function TsCheckBox.GlyphWidth: integer; begin if Assigned(Images) and (ImgChecked > -1) and (ImgUnChecked > -1) then begin if Images.Width mod Images.Height = 0 then Result := Images.Width div (Images.Width div Images.Height) else Result := Images.Width; end else begin if Glyph <> nil then begin if Glyph.Width mod Glyph.Height = 0 then Result := Glyph.Width div (Glyph.Width div Glyph.Height) else Result := Glyph.Width; end else Result := 16; end; end; {$IFDEF TNTUNICODE} function TsCheckBox.IsCaptionStored: Boolean; begin Result := TntControl_IsCaptionStored(Self) end; function TsCheckBox.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; {$ENDIF} procedure TsCheckBox.Loaded; begin inherited; SkinData.Loaded; AdjustSize; end; procedure TsCheckBox.PaintControl(DC : HDC); begin if not FCommonData.Updating and not (Assigned(FadeTimer) and FadeTimer.Enabled {and (FadeTimer.Iterations > FadeTimer.FadeLevel)}) then begin PrepareCache; UpdateCorners(FCommonData, 0); BitBlt(DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); end; end; procedure TsCheckBox.PaintGlyph(Bmp: TBitmap; const Index : integer); var R : TRect; begin if FCommonData.FCacheBmp.Width = 0 then exit; R := CheckRect; if Bmp.PixelFormat = pfDevice then Bmp.HandleType := bmDIB; if Bmp.PixelFormat <> pf32bit then Bmp.PixelFormat := pf32bit; CopyByMask(Rect(R.Left, R.Top, R.Right, R.Bottom), Rect(GlyphWidth * Index, 0, GlyphWidth * (Index + 1), GlyphHeight), FCommonData.FCacheBmp, Bmp, EmptyCI, True); end; procedure TsCheckBox.PaintHandler(M: TWMPaint); var PS: TPaintStruct; DC : hdc; SavedDC: hdc; begin DC := M.DC; if (DC = 0) or (SkinData.CtrlSkinState and ACS_PRINTING <> ACS_PRINTING) then DC := BeginPaint(Handle, PS); SavedDC := SaveDC(DC); try if not FCommonData.Updating then PaintControl(DC) else FCommonData.FUpdating := True; finally RestoreDC(DC, SavedDC); if (M.DC = 0) or (SkinData.CtrlSkinState and ACS_PRINTING <> ACS_PRINTING) then EndPaint(Handle, PS); end; end; procedure TsCheckBox.PrepareCache; var BGInfo : TacBGInfo; begin InitCacheBmp(SkinData); FCommonData.FCacheBmp.Canvas.Font.Assign(Font); FCommonData.FCacheBmp.Canvas.Lock; BGInfo.DrawDC := FCommonData.FCacheBmp.Canvas.Handle; BGInfo.PleaseDraw := True; BGInfo.Offset := Point(Left, Top); BGInfo.R := Rect(0, 0, Width, Height); GetBGInfo(@BGInfo, Parent); if BGInfo.BgType = btUnknown then begin // If parent is not AlphaControl BGInfo.Bmp := FCommonData.FCacheBmp; BGInfo.BgType := btCache; end; FCommonData.FCacheBmp.Canvas.Unlock; PaintItem(FCommonData, BGInfoToCI(@BGInfo), True, integer(ControlIsActive(FCommonData) and not ReadOnly), Rect(0, 0, FCommonData.FCacheBmp.Width, Height), Point(Left, Top), FCommonData.FCacheBmp, False); DrawCheckText; DrawCheckArea; if not Enabled then BmpDisabledKind(FCommonData.FCacheBmp, FDisabledKind, Parent, BGInfoToCI(@BGInfo), Point(Left, Top)); FCommonData.BGChanged := False end; {$IFDEF TNTUNICODE} procedure TsCheckBox.SetCaption(const Value: TWideCaption); begin TntControl_SetText(Self, Value); end; {$ENDIF} procedure TsCheckBox.SetChecked(Value: Boolean); begin if not (csLoading in ComponentState) then begin if (Value <> Checked) then FCommonData.BGChanged := True; inherited; if FCommonData.BGChanged then Repaint; end; end; {$IFNDEF DELPHI7UP} procedure TsCheckBox.SetWordWrap(const Value: boolean); begin if FWordWrap <> Value then begin FWordWrap := Value; FCommonData.BGChanged := True; if AutoSize then AutoSize := False; Repaint; end; end; {$ENDIF} procedure TsCheckBox.SetDisabledKind(const Value: TsDisabledKind); begin if FDisabledKind <> Value then begin FDisabledKind := Value; FCommonData.Invalidate; end; end; procedure TsCheckBox.SetGlyphChecked(const Value: TBitmap); begin FGlyphChecked.Assign(Value); if AutoSize then AdjustSize; FCommonData.Invalidate; end; procedure TsCheckBox.SetGlyphUnChecked(const Value: TBitmap); begin FGlyphUnChecked.Assign(Value); if AutoSize then AdjustSize; Invalidate; end; {$IFDEF TNTUNICODE} procedure TsCheckBox.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; {$ENDIF} procedure TsCheckBox.SetImageChecked(const Value: TsImageIndex); begin if FImgChecked <> Value then begin FImgChecked := Value; if AutoSize then AdjustSize; if Checked then SkinData.Invalidate; end; end; procedure TsCheckBox.SetImages(const Value: TCustomImageList); begin if FImages <> Value then begin FImages := Value; if AutoSize then AdjustSize; SkinData.Invalidate; end; end; procedure TsCheckBox.SetImageUnChecked(const Value: TsImageIndex); begin if FImgUnchecked <> Value then begin FImgUnchecked := Value; if AutoSize then AdjustSize; if not Checked then SkinData.Invalidate; end; end; procedure TsCheckBox.SetMargin(const Value: integer); begin if FMargin <> Value then begin FMargin := Value; if AutoSize then AdjustSize; Invalidate; end; end; procedure TsCheckBox.SetReadOnly(const Value: boolean); begin FReadOnly := Value; end; procedure TsCheckBox.SetShowFocus(const Value: Boolean); begin if FShowFocus <> Value then begin FShowFocus := Value; Invalidate; end; end; procedure TsCheckBox.SetTextIndent(const Value: integer); begin if FTextIndent <> Value then begin FTextIndent := Value; if AutoSize then AdjustSize; Invalidate; end; end; function TsCheckBox.Glyph: TBitmap; begin if Checked then Result := GlyphChecked else Result := GlyphUnChecked; if Result.Empty then Result := nil; end; function TsCheckBox.SkinCheckRect(i: integer): TRect; var h, w, hdiv : integer; begin h := SkinGlyphHeight(i); w := SkinGlyphWidth(i); hdiv := (Height - h) div 2; if GetControlsAlignment = taRightJustify then begin Result := Rect(Margin, hdiv, Margin + w, h + hdiv); end else begin Result := Rect(Width - w - Margin, hdiv, Width - Margin, h + hdiv); end; end; function TsCheckBox.SkinGlyphHeight(i: integer): integer; begin with FCommonData.SkinManager do if Assigned(ma[i].Bmp) then Result := ma[i].Bmp.Height div 2 else Result := HeightOf(ma[i].R) div (ma[i].MaskType + 1); end; function TsCheckBox.SkinGlyphWidth(i: integer): integer; begin with FCommonData.SkinManager do if Assigned(ma[i].Bmp) then Result := ma[i].Bmp.Width div 3 else Result := WidthOf(ma[i].R) div ma[i].ImageCount; end; procedure TsCheckBox.WndProc(var Message: TMessage); begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_CTRLHANDLED : begin Message.Result := 1; Exit end; AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end; AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); if HandleAllocated then SendMessage(Handle, BM_SETCHECK, Integer(State), 0); if not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, nil, nil); Repaint; exit end; AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); AdjustSize; Repaint; exit end; AC_PREPARECACHE : PrepareCache; AC_STOPFADING : begin StopFading(FadeTimer, FCommonData); Exit end; AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin StopFading(FadeTimer, FCommonData); CommonWndProc(Message, FCommonData); exit end end; if (FCommonData <> nil) and FCommonData.Skinned(True) then case Message.Msg of CM_MOUSEENTER : if Enabled and not (csDesigning in ComponentState) and not FCommonData.FMouseAbove then begin FCommonData.FMouseAbove := True; DoChangePaint(FadeTimer, FCommonData, False, EventEnabled(aeMouseEnter, FAnimatEvents)); end; CM_MOUSELEAVE : if Enabled and not (csDesigning in ComponentState) then begin FCommonData.FMouseAbove := False; FPressed := False; DoChangePaint(FadeTimer, FCommonData, False, EventEnabled(aeMouseLeave, FAnimatEvents)); end; WM_SETFOCUS, CM_ENTER : if not (csDesigning in ComponentState) then begin if Enabled then begin inherited; FCommonData.BGChanged := True; if FadeTimer = nil then Repaint else FadeTimer.Change; // Fast repaint end; Exit; end; WM_KILLFOCUS, CM_EXIT: if not (csDesigning in ComponentState) then begin if Enabled then begin if FadeTimer <> nil then StopFading(FadeTimer, FCommonData); Perform(WM_SETREDRAW, 0, 0); inherited; Perform(WM_SETREDRAW, 1, 0); FCommonData.FFocused := False; FCommonData.FMouseAbove := False; FCommonData.Invalidate; Exit end; end; end; if not ControlIsReady(Self) then inherited else begin CommonWndProc(Message, FCommonData); if FCommonData.Skinned(True) then begin if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_ENDPARENTUPDATE : if FCommonData.Updating or FCommonData.HalfVisible then begin FCommonData.Updating := False; if not (csDesigning in ComponentState) then Repaint; end end else case Message.Msg of WM_ENABLE, WM_NCPAINT : Exit; // Disabling of blinking when switched {$IFDEF CHECKXP} WM_UPDATEUISTATE : begin if SkinData.Skinned and UseThemes and not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, ' ', ' '); Exit; end; {$ENDIF} CM_ENABLEDCHANGED : begin inherited; Repaint; Exit end; CM_CHANGED : begin if not (csDesigning in ComponentState) then begin if Checked then DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseUp, FAnimatEvents), fdUp) else DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseUp, FAnimatEvents)); end else FCommonData.Invalidate; end; BM_SETCHECK : begin if (FadeTimer <> nil) and (FadeTimer.FadeLevel < FadeTimer.Iterations) then StopFading(FadeTimer, FCommonData); Exit; end; WM_ERASEBKGND : begin Message.Result := 1; Exit; end; WM_PRINT : begin SkinData.FUpdating := False; PaintHandler(TWMPaint(Message)); end; WM_PAINT : begin PaintHandler(TWMPaint(Message)); if not (csDesigning in ComponentState) then Exit; end; CM_TEXTCHANGED : begin if AutoSize then AdjustSize; Repaint; Exit; end; WM_KEYDOWN : if Enabled and not (csDesigning in ComponentState) and (TWMKey(Message).CharCode = VK_SPACE) then begin if ReadOnly then Exit; FPressed := True; if not Focused then begin ClicksDisabled := True; Windows.SetFocus(Handle); ClicksDisabled := False; end; Repaint; if Assigned(OnKeyDown) then OnKeydown(Self, TWMKeyDown(Message).CharCode, KeysToShiftState(word(TWMKeyDown(Message).KeyData))); Exit; end; WM_LBUTTONDBLCLK, WM_LBUTTONDOWN : if not (csDesigning in ComponentState) and Enabled and (DragMode = dmManual) then begin if ReadOnly then Exit; FPressed := True; DoChangePaint(FadeTimer, FCommonData, True, EventEnabled(aeMouseDown, FAnimatEvents)); if not Focused then begin ClicksDisabled := True; Windows.SetFocus(Handle); ClicksDisabled := False; end; if WM_LBUTTONDBLCLK = Message.Msg then begin if Assigned(OnDblClick) then OnDblClick(Self) end else if Assigned(OnMouseDown) then OnMouseDown(Self, mbLeft, KeysToShiftState(TWMMouse(Message).Keys), TWMMouse(Message).XPos, TWMMouse(Message).YPos); Exit; end; WM_KEYUP : if not (csDesigning in ComponentState) and Enabled then begin if ReadOnly then Exit; if FPressed then begin FPressed := False; Toggle; end else FPressed := False; if Assigned(OnKeyUp) then OnKeyUp(Self, TWMKey(Message).CharCode, KeysToShiftState(TWMKey(Message).KeyData)); if Assigned(FadeTimer) and FadeTimer.Enabled and (Width <> SkinData.FCacheBmp.Width) then begin // Repaint after animation if size of control is changed StopFading(FadeTimer, FCommonData); Repaint; end; Exit; end; WM_LBUTTONUP : if not (csDesigning in ComponentState) and Enabled then begin if ReadOnly then Exit; if FPressed then begin FPressed := False; Toggle; end else FPressed := False; if Assigned(OnMouseUp) then OnMouseUp(Self, mbLeft, KeysToShiftState(TWMMouse(Message).Keys), TWMMouse(Message).XPos, TWMMouse(Message).YPos); if Assigned(FadeTimer) and FadeTimer.Enabled and (Width <> SkinData.FCacheBmp.Width) then begin // Repaint after animation if size of control is changed StopFading(FadeTimer, FCommonData); Repaint; end; Exit; end; end end else case Message.Msg of CM_TEXTCHANGED : begin if AutoSize then AdjustSize; end; WM_KEYDOWN, WM_LBUTTONDOWN : FPressed := True; WM_KEYUP, WM_LBUTTONUP : FPressed := False; WM_LBUTTONDBLCLK : if ReadOnly then Exit; BM_SETSTATE, BM_SETCHECK : if not (csCreating in ControlState) and FPressed and ReadOnly then Exit; end; inherited; end; end; end.
unit DBT; interface uses Windows; type TWMDeviceChange = record Msg : cardinal; Event : UINT; dwData : pointer; Result : longint; end; type PDevBroadcastHdr = ^TDevBroadcastHdr; TDevBroadcastHdr = packed record dbcd_size: integer; dbcd_devicetype: DWORD; dbcd_reserved: DWORD; end; type PDevBroadcastVolume = ^TDevBroadcastVolume; TDevBroadcastVolume = packed record dbcv_size: DWORD; dbcv_devicetype: DWORD; dbcv_reserved: DWORD; dbcv_unitmask: DWORD; dbcv_flags: Word; end; const DBT_DEVICEARRIVAL = $8000; DBT_DEVICEQUERYREMOVE = $8001; DBT_DEVICEQUERYREMOVEFAILED = $8002; DBT_DEVICEREMOVEPENDING = $8003; DBT_DEVICEREMOVECOMPLETE = $8004; DBT_DEVICETYPESPECIFIC = $8005; DBT_DEVTYP_OEM = $00000000; DBT_DEVTYP_DEVNODE = $00000001; DBT_DEVTYP_VOLUME = $00000002; DBT_DEVTYP_PORT = $00000003; DBT_DEVTYP_NET = $00000004; DBT_DEVTYP_DEVICEINTERFACE = $00000005; DBT_DEVTYP_HANDLE = $00000006; function GetDiskName(UnitMask : longint) : string; implementation function GetDiskName(UnitMask : longint) : string; var index : integer; begin for index := 0 to 26 do begin if ((UnitMask and 1) <> 0) then break; UnitMask := UnitMask shr 1; end; Result := Char(integer('A')+index); end; end.
unit DotNetTypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; resourcestring rsDNTEnd = 'END'; rsDNTVoid = 'void'; rsDNTBool = 'bool'; rsDNTChar = 'char'; rsDNTByteSigned = 'Byte (Signed)'; rsDNTByte = 'Byte'; rsDNT2ByteSigned = '2 Byte (Signed)'; rsDNT2Byte = '2 Byte'; rsDNT4ByteSigned = '4 Byte (Signed)'; rsDNT4Byte = '4 Byte'; rsDNT8ByteSigned = '8 Byte (Signed)'; rsDNT8Byte = '8 Byte'; rsDNTFloat = 'Float'; rsDNTDouble = 'Double'; rsDNTString = 'String'; rsDNTPointer = 'Pointer'; rsDNTReference = 'Reference'; rsDNTValueType = 'ValueType'; rsDNTClass = 'Class'; rsDNTVar = 'Var'; rsDNTArray = 'Array'; rsDNTGenericInst = 'GenericInst'; rsDNTTypedByRef = 'Typed By Ref'; rsDNTSigned = 'Signed'; rsDNTUnsigned = 'Unsigned'; rsDNTFunctionPointer = 'Function Pointer'; rsDNTObject = 'Object'; rsDNTSZArray = 'SZ Array'; rsDNTMVar = 'MVar'; rsDNTCMOD_REQD = 'CMOD_REQD'; rsDNTCMOD_OPT = 'CMOD_OPT'; rsDNTInternal = 'Internal'; rsDNTMAX = 'MAX'; rsDNTModifier = 'Modifier'; rsDNTSentinel = 'Sentinel'; rsDNTPinned = 'Pinned'; const ELEMENT_TYPE_END = $00; ELEMENT_TYPE_VOID = $01; ELEMENT_TYPE_BOOLEAN = $02; ELEMENT_TYPE_CHAR = $03; ELEMENT_TYPE_I1 = $04; ELEMENT_TYPE_U1 = $05; ELEMENT_TYPE_I2 = $06; ELEMENT_TYPE_U2 = $07; ELEMENT_TYPE_I4 = $08; ELEMENT_TYPE_U4 = $09; ELEMENT_TYPE_I8 = $0a; ELEMENT_TYPE_U8 = $0b; ELEMENT_TYPE_R4 = $0c; ELEMENT_TYPE_R8 = $0d; ELEMENT_TYPE_STRING = $0e; // every type above PTR will be simple type ELEMENT_TYPE_PTR = $0f; // PTR <type> ELEMENT_TYPE_BYREF = $10; // BYREF <type> // Please use ELEMENT_TYPE_VALUETYPE. ELEMENT_TYPE_VALUECLASS is deprecated. ELEMENT_TYPE_VALUETYPE = $11; // VALUETYPE <class Token> ELEMENT_TYPE_CLASS = $12; // CLASS <class Token> ELEMENT_TYPE_VAR = $13; // a class type variable VAR <number> ELEMENT_TYPE_ARRAY = $14; // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ... ELEMENT_TYPE_GENERICINST = $15; // GENERICINST <generic type> <argCnt> <arg1> ... <argn> ELEMENT_TYPE_TYPEDBYREF = $16; // TYPEDREF (it takes no args) a typed referece to some other type ELEMENT_TYPE_I = $18; // native integer size ELEMENT_TYPE_U = $19; // native unsigned integer size ELEMENT_TYPE_FNPTR = $1b; // FNPTR <complete sig for the function including calling convention> ELEMENT_TYPE_OBJECT = $1c; // Shortcut for System.Object ELEMENT_TYPE_SZARRAY = $1d; // Shortcut for single dimension zero lower bound array // SZARRAY <type> ELEMENT_TYPE_MVAR = $1e; // a method type variable MVAR <number> // This is only for binding ELEMENT_TYPE_CMOD_REQD = $1f; // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef> ELEMENT_TYPE_CMOD_OPT = $20; // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef> // This is for signatures generated internally (which will not be persisted in any way). ELEMENT_TYPE_INTERNAL = $21; // INTERNAL <typehandle> // Note that this is the max of base type excluding modifiers ELEMENT_TYPE_MAX = $22; // first invalid element type ELEMENT_TYPE_MODIFIER = $40; ELEMENT_TYPE_SENTINEL = $41; ELEMENT_TYPE_PINNED = $45; //CorFieldAttr: fdFieldAccessMask = $0007; fdPrivateScope = $0000; // Member not referenceable. fdPrivate = $0001; // Accessible only by the parent type. fdFamANDAssem = $0002; // Accessible by sub-types only in this Assembly. fdAssembly = $0003; // Accessibly by anyone in the Assembly. fdFamily = $0004; // Accessible only by type and sub-types. fdFamORAssem = $0005; // Accessibly by sub-types anywhere plus anyone in assembly. fdPublic = $0006; // Accessibly by anyone who has visibility to this scope. // end member access mask // field contract attributes. fdStatic = $0010; // Defined on type else per instance. fdInitOnly = $0020; // Field may only be initialized not written to after init. fdLiteral = $0040; // Value is compile time constant. fdNotSerialized = $0080; // Field does not have to be serialized when type is remoted. fdSpecialName = $0200; // field is special. Name describes how. // interop attributes fdPinvokeImpl = $2000; // Implementation is forwarded through pinvoke. // Reserved flags for runtime use only. fdReservedMask = $9500; fdRTSpecialName = $0400; // Runtime(metadata internal APIs) should check name encoding. fdHasFieldMarshal = $1000; // Field has marshalling information. fdHasDefault = $8000; // Field has default. fdHasFieldRVA = $0100; // Field has RVA. function DotNetTypeToString(dntype: dword):string; implementation function DotNetTypeToString(dntype: dword):string; begin result:=rsDNTPointer; case dntype of ELEMENT_TYPE_END : result:=rsDNTEnd; ELEMENT_TYPE_VOID : result:=rsDNTVoid; ELEMENT_TYPE_BOOLEAN : result:=rsDNTBool; ELEMENT_TYPE_CHAR : result:=rsDNTChar; ELEMENT_TYPE_I1 : result:=rsDNTByteSigned; ELEMENT_TYPE_U1 : result:=rsDNTByte; ELEMENT_TYPE_I2 : result:=rsDNT2ByteSigned; ELEMENT_TYPE_U2 : result:=rsDNT2Byte; ELEMENT_TYPE_I4 : result:=rsDNT4ByteSigned; ELEMENT_TYPE_U4 : result:=rsDNT4Byte; ELEMENT_TYPE_I8 : result:=rsDNT8ByteSigned; ELEMENT_TYPE_U8 : result:=rsDNT8Byte; ELEMENT_TYPE_R4 : result:=rsDNTFloat; ELEMENT_TYPE_R8 : result:=rsDNTDouble; ELEMENT_TYPE_STRING : result:=rsDNTString; ELEMENT_TYPE_PTR : result:=rsDNTPointer; ELEMENT_TYPE_BYREF : result:=rsDNTReference; ELEMENT_TYPE_VALUETYPE : result:=rsDNTValueType; ELEMENT_TYPE_CLASS : result:=rsDNTClass; ELEMENT_TYPE_VAR : result:=rsDNTVar; ELEMENT_TYPE_ARRAY : result:=rsDNTArray; ELEMENT_TYPE_GENERICINST : result:=rsDNTGenericInst; ELEMENT_TYPE_TYPEDBYREF : result:=rsDNTTypedByRef; ELEMENT_TYPE_I : result:=rsDNTSigned; ELEMENT_TYPE_U : result:=rsDNTUnsigned; ELEMENT_TYPE_FNPTR : result:=rsDNTFunctionPointer; ELEMENT_TYPE_OBJECT : result:=rsDNTObject; ELEMENT_TYPE_SZARRAY : result:=rsDNTSZArray; ELEMENT_TYPE_MVAR : result:=rsDNTMVar; ELEMENT_TYPE_CMOD_REQD : result:=rsDNTCMOD_REQD; ELEMENT_TYPE_CMOD_OPT : result:=rsDNTCMOD_OPT; ELEMENT_TYPE_INTERNAL : result:=rsDNTInternal; ELEMENT_TYPE_MAX : result:=rsDNTMAX; ELEMENT_TYPE_MODIFIER : result:=rsDNTModifier; ELEMENT_TYPE_SENTINEL : result:=rsDNTSentinel; ELEMENT_TYPE_PINNED : result:=rsDNTPinned; end; end; end.
Unit SearchBookings; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB, Data.Win.ADODB, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Imaging.jpeg, Vcl.Menus; type TFRMSearchBookings = class(TForm) ADOQBookingDetails: TADOQuery; DSBookingDetails: TDataSource; DBGBookingDetails: TDBGrid; BTNToday: TButton; BTNLNCH: TButton; BTNEDIN: TButton; BTNLDIN: TButton; BTNSearchByDate: TButton; BTNTomorrow: TButton; DPDate: TDateTimePicker; Label4: TLabel; BTNActive: TButton; BTNNoShow: TButton; BTNSettled: TButton; BTNCancelBooking: TButton; Label5: TLabel; Panel2: TPanel; Image2: TImage; BookingsDate: TLabel; Panel3: TPanel; Shape7: TShape; Shape1: TShape; Shape8: TShape; Shape2: TShape; Shape3: TShape; Shape4: TShape; Shape5: TShape; Shape6: TShape; TableLBL1: TLabel; TableLBL2: TLabel; TableLBL3: TLabel; TableLBL4: TLabel; TableLBL5: TLabel; TableLBL6: TLabel; TableLBL7: TLabel; TableLBL8: TLabel; Disabled1: TLabel; Disabled2: TLabel; Disabled3: TLabel; Disabled4: TLabel; Disabled5: TLabel; Disabled6: TLabel; Disabled7: TLabel; Disabled8: TLabel; Child1: TLabel; Child2: TLabel; Child3: TLabel; Child4: TLabel; Child5: TLabel; Child6: TLabel; Child7: TLabel; Child8: TLabel; LBLTitle: TLabel; LBLFirstname: TLabel; LBLSurname: TLabel; LBLPhoneNumber: TLabel; LBLEmail: TLabel; LBLCustomerID: TLabel; LBLStatus: TLabel; LBLBookingRef: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Bevel1: TBevel; ADOQDeleteBooking: TADOQuery; ADOQDeleteTables: TADOQuery; Label11: TLabel; Label12: TLabel; Label13: TLabel; LBLSitting: TLabel; LBLStartTime: TLabel; LBLEndTime: TLabel; MainMenu: TMainMenu; FileItem: TMenuItem; ExitItem: TMenuItem; HelpItem: TMenuItem; procedure FormCreate(Sender: TObject); procedure BTNSearchByDateClick(Sender: TObject); procedure BTNSettledClick(Sender: TObject); procedure BTNActiveClick(Sender: TObject); procedure BTNNoShowClick(Sender: TObject); procedure BTNTodayClick(Sender: TObject); procedure BTNTomorrowClick(Sender: TObject); procedure BTNCancelBookingClick(Sender: TObject); procedure BTNLNCHClick(Sender: TObject); procedure BTNEDINClick(Sender: TObject); procedure BTNLDINClick(Sender: TObject); private ReturnQuery : String; Procedure Reset; Procedure BookedTables; Procedure GetCustomerDetails; Procedure FindBooking(Parameter: String); public { Public declarations } end; var FRMSearchBookings: TFRMSearchBookings; TableList: Array [1..10] Of TShape; //Allows max 10 tables to be stored LabelList, DisabledSpaceList, ChildSpaceList: Array [1..10] Of TLabel; Index: Integer; implementation Uses LocateDatabase; {$R *.dfm} Procedure TFRMSearchBookings.Reset; Begin For Index := 1 To 8 Do Begin TableList[Index].Brush.Color := clRed; LabelList[Index].Visible := False; DisabledSpaceList[Index].Visible := False; ChildSpaceList[Index].Visible := False; LBLStatus.Caption := ''; LBLBookingRef.Caption := ''; LBLCustomerID.Caption := ''; LBLTitle.Caption := ''; LBLFirstname.Caption := ''; LBLSurname.Caption := ''; LBLPhoneNumber.Caption := ''; LBLEmail.Caption := ''; BookingsDate.Caption := ''; LBLSitting.Caption := ''; LBLStartTime.Caption := ''; LBLEndTime.Caption := ''; End; End; Procedure TFRMSearchBookings.BookedTables; Var Index: Integer; Begin ADOQBookingDetails.First; //Looks at the first record in the database While NOT ADOQBookingDetails.Eof Do Begin If ADOQBookingDetails['Status'] = 'Reserved' then Begin For Index := 1 to 10 Do IF ADOQBookingDetails['TableNumber'] = Index Then Begin TableList[Index].Brush.Color := clBlue; LabelList[Index].Visible := True; LabelList[Index].Color := clBlue; IF DisabledSpaceList[Index].Caption <> '' Then Begin DisabledSpaceList[Index].Visible := True; DisabledSpaceList[Index].Color := clBlue; End; IF ChildSpaceList[Index].Caption <> '' Then Begin ChildSpaceList[Index].Visible := True; ChildSpaceList[Index].Color := clBlue; End; End; ADOQBookingDetails.Next;//Pointer moves to next record in the database End; //Ends If ADOQBookingDetails['Status'] = 'Active' then Begin For Index := 1 to 10 Do IF ADOQBookingDetails['TableNumber'] = Index Then Begin TableList[Index].Brush.Color := clLime; LabelList[Index].Visible := True; LabelList[Index].Color := clLime; IF DisabledSpaceList[Index].Caption <> '' Then Begin DisabledSpaceList[Index].Visible := True; DisabledSpaceList[Index].Color := clLime; End; IF ChildSpaceList[Index].Caption <> '' Then Begin ChildSpaceList[Index].Visible := True; ChildSpaceList[Index].Color := clLime; End; End; ADOQBookingDetails.Next;//Pointer moves to next record in the database End; //Ends IF (ADOQBookingDetails['Status'] = 'Settled') Or (ADOQBookingDetails['Status'] = 'No Show') Then Begin Reset; ADOQBookingDetails.Next; //Pointer moves to next record in the database End; //Ends End; End; Procedure TFRMSearchBookings.GetCustomerDetails; Begin LBLStatus.Caption := ADOQBookingDetails['Status']; LBLBookingRef.Caption := ADOQBookingDetails['BookingReference']; LBLCustomerID.Caption := ADOQBookingDetails['Customer.CustomerID']; LBLTitle.Caption := ADOQBookingDetails['Title']; LBLFirstname.Caption := ADOQBookingDetails['FirstName']; LBLSurname.Caption := ADOQBookingDetails['Surname']; LBLPhoneNumber.Caption := ADOQBookingDetails['PhoneNumber']; LBLEmail.Caption := ADOQBookingDetails['Email']; LBLSitting.Caption := ADOQBookingDetails['SittingID']; LBLStartTime.Caption := ADOQBookingDetails['StartTime']; LBLEndTime.Caption := ADOQBookingDetails['EndTime']; End; //Procedure to search the database for a booking made on user entered date Procedure TFRMSearchBookings.FindBooking(Parameter: String); Begin FormCreate(Self); Reset; ADOQBookingDetails.Close; ADOQBookingDetails.Parameters[0].Value := Parameter; ADOQBookingDetails.Open; BookingsDate.Caption := Parameter; //Label text changes searched date IF ADOQBookingDetails.RecordCount = 0 Then ShowMessage ('No Booking made for selected date') Else Begin BookedTables; GetCustomerDetails; End; End; {**********Procedures to change booking status**********} //Change status to 'Active' Procedure TFRMSearchBookings.BTNActiveClick(Sender: TObject); Begin IF ADOQBookingDetails.RecordCount = 0 THEN ShowMessage ('No Booking Slected') ELSE Begin ADOQBookingDetails.Edit; ADOQBookingDetails['Status']:= 'Active'; ADOQBookingDetails.Post; ShowMessage ('Booking Status Changed'); BTNSearchByDateClick(Self); End; End; //Change status to 'Settled' Procedure TFRMSearchBookings.BTNSettledClick(Sender: TObject); Begin IF ADOQBookingDetails.RecordCount = 0 THEN ShowMessage ('No Booking Slected') ELSE Begin ADOQBookingDetails.Edit; ADOQBookingDetails['Status']:= 'Settled'; ADOQBookingDetails.Post; ShowMessage ('Booking Status Changed'); End; End; //Change status to 'No Show' procedure TFRMSearchBookings.BTNNoShowClick(Sender: TObject); Begin IF ADOQBookingDetails.RecordCount = 0 THEN ShowMessage ('No Booking Slected') ELSE Begin ADOQBookingDetails.Edit; ADOQBookingDetails['Status']:= 'No Show'; ADOQBookingDetails.Post; ShowMessage ('Booking Status Changed'); End; End; //Procedure to cancel a selected booking //First deletes all booked tables associated with booking then deletes booking Procedure TFRMSearchBookings.BTNCancelBookingClick(Sender: TObject); Var Index: Integer; Begin IF ADOQBookingDetails.RecordCount = 0 THEN ShowMessage ('No Booking Slected') Else Begin ADOQDeleteTables.Close; ADOQDeleteTables.Parameters[0].Value := ADOQBookingDetails['BookingReference']; ADOQDeleteTables.Open; ADOQDeleteBooking.Close; ADOQDeleteBooking.Parameters[0].Value := ADOQBookingDetails['BookingReference']; ADOQDeleteBooking.Open; IF messagebox(0,'Confirm booking cancellation','Options', +mb_YesNo +mb_IconWarning) = 6 Then Begin ADOQDeleteTables.First; While NOT ADOQDeleteTables.Eof Do ADOQDeleteTables.Delete; ADOQDeleteTables.Next; ADOQDeleteBooking.Delete; ShowMessage ('Selected Booking has been cancelled'); FormCreate(Self); ADOQBookingDetails.Close; End Else ShowMessage('Selected Booking has not been cancelled'); End; End; Procedure TFRMSearchBookings.BTNEDINClick(Sender: TObject); Begin Reset; FindBooking(DateToStr(DPDate.Date)); End; Procedure TFRMSearchBookings.BTNLDINClick(Sender: TObject); Begin Reset; FindBooking(DateToStr(DPDate.Date)); End; Procedure TFRMSearchBookings.BTNLNCHClick(Sender: TObject); Var Sitting: String; Begin ADOQBookingDetails.Close; ADOQBookingDetails.SQL.Clear; ADOQBookingDetails.SQL.Add('SELECT Customer.*, Booking.BookingReference, ' +'Booking.CustomerID, Booking.DateOfReservation' +', Booking.SittingID, Booking.NumPeople, ' +'Booking.[DisabledSpace?], ' +'Booking.[ChildSpace?], Booking.Status, ' +'TableBooking.TableNumber, Sitting.StartTime, ' +'Sitting.EndTime'); ADOQBookingDetails.SQL.Add('FROM Sitting INNER JOIN ((Customer INNER JOIN ' +'Booking ON Customer.CustomerID = ' +'Booking.CustomerID) INNER JOIN TableBooking ' +'ON Booking.BookingReference = ' +'TableBooking.BookingReference) ON ' +'Sitting.SittingID = Booking.SittingID'); ADOQBookingDetails.SQL.Add('WHERE ((Booking.DateOfDining) = [Selected Date]) ' +'And ((Booking.Sitting) = [Sitting]'); ADOQBookingDetails.Open; ADOQBookingDetails.Parameters[0].Value := DateToStr(DateToStr(DPDate.Date)); ADOQBookingDetails.Parameters[1].Value := 'Lunch'; End; procedure TFRMSearchBookings.BTNSearchByDateClick(Sender: TObject); Var Index: Integer; Begin Reset; FindBooking(DateToStr(DPDate.Date)); End; Procedure TFRMSearchBookings.BTNTodayClick(Sender: TObject); Begin Reset; FindBooking(DateToStr(Date)); End; Procedure TFRMSearchBookings.BTNTomorrowClick(Sender: TObject); Begin Reset; FindBooking(DateToStr(Date+1)); End; Procedure TFRMSearchBookings.FormCreate(Sender: TObject); Var I: Integer; Begin //Run procedure 'ReadPath' from form LocateDatase to read //Ini file and retrive Database Path FRMDatabaseLocate.ReadPath; //Set connection of all TADOQuery's to path from Ini file For I := 0 to ComponentCount - 1 Do IF (Components[I] is TADOQuery) Then TADOQuery(Components[I]).ConnectionString := DatabaseSource; //Set connection of all TADOTable's to path from Ini file For I := 0 to ComponentCount - 1 Do IF (Components[I] is TADOTable) Then TADOTable(Components[I]).ConnectionString := DatabaseSource; TableList[1] := Shape1; TableList[2] := Shape2; TableList[3] := Shape3; TableList[4] := Shape4; TableList[5] := Shape5; TableList[6] := Shape6; TableList[7] := Shape7; TableList[8] := Shape8; //********************* //Insert all label names into Array of TLabels LabelList[1] := TableLBL1; LabelList[2] := TableLBL2; LabelList[3] := TableLBL3; LabelList[4] := TableLBL4; //TShapes which represent the LabelList[5] := TableLBL5; //different physical tables LabelList[6] := TableLBL6; LabelList[7] := TableLBL7; LabelList[8] := TableLBL8; //******************************* DisabledSpaceList[1] := Disabled1; DisabledSpaceList[2] := Disabled2; DisabledSpaceList[3] := Disabled3; DisabledSpaceList[4] := Disabled4; //Labels to show if table DisabledSpaceList[5] := Disabled5; //has disabled access DisabledSpaceList[6] := Disabled6; DisabledSpaceList[7] := Disabled7; DisabledSpaceList[8] := Disabled8; //******************************* ChildSpaceList[1] := Child1; ChildSpaceList[2] := Child2; ChildSpaceList[3] := Child3; ChildSpaceList[4] := Child4; //Labels to show tables have child space ChildSpaceList[5] := Child5; ChildSpaceList[6] := Child6; ChildSpaceList[7] := Child7; ChildSpaceList[8] := Child8; Reset; DPDate.Date := Date; //Add SQL to ADOQBookingDetails so booking and customer details //can be retrived ADOQBookingDetails.Close; ADOQBookingDetails.SQL.Clear; ADOQBookingDetails.SQL.Add('SELECT Customer.*, Booking.BookingReference, ' +'Booking.CustomerID, Booking.DateOfReservation' +', Booking.SittingID, Booking.NumPeople, ' +'Booking.[DisabledSpace?], ' +'Booking.[ChildSpace?], Booking.Status, ' +'TableBooking.TableNumber, Sitting.StartTime, ' +'Sitting.EndTime'); ADOQBookingDetails.SQL.Add('FROM Sitting INNER JOIN ((Customer INNER JOIN ' +'Booking ON Customer.CustomerID = ' +'Booking.CustomerID) INNER JOIN TableBooking ' +'ON Booking.BookingReference = ' +'TableBooking.BookingReference) ON ' +'Sitting.SittingID = Booking.SittingID'); ADOQBookingDetails.SQL.Add('WHERE ((Booking.DateOfDining)=' +'[Enter Booking Date]);'); ADOQBookingDetails.Open; //Add SQL to ADOQDeleteTables so tables for selected booking can be deleted ADOQDeleteTables.Close; ADOQDeleteTables.SQL.Clear; ADOQDeleteTables.SQL.Add('SELECT *'); ADOQDeleteTables.SQL.Add('FROM TableBooking'); ADOQDeleteTables.SQL.Add('WHERE BookingReference = BookingRef'); ADOQDeleteTables.Open; //Add SQL to ADOQDeleteBooking so slected booking can be deleted from database ADOQDeleteBooking.Close; ADOQDeleteBooking.SQL.Clear; ADOQDeleteBooking.SQL.Add('SELECT *'); ADOQDeleteBooking.SQL.Add('FROM Booking'); ADOQDeleteBooking.SQL.Add('WHERE BookingReference = BookingRef'); ADOQDeleteBooking.Open; End; End.
{------------------------------------ 功能说明:Sys包插件对象 创建日期:2010.04.23 作者:WZW 版权:WZW -------------------------------------} unit SysPlugin; interface uses SysUtils, Classes, Windows, MenuRegIntf, SysModule, RegIntf, uTangramModule; type TSysPlugin = class(TModule) private procedure ExitApp(Sender: TObject); procedure ConfigToolClick(Sender: TObject); procedure SvcInfoClick(Sender: TObject); procedure AboutClick(Sender: TObject); protected public constructor Create; override; destructor Destroy; override; procedure Init; override; procedure final; override; //procedure Register(Flags: Integer; Intf: IInterface); override; class procedure RegisterModule(Reg: IRegistry); override; class procedure UnRegisterModule(Reg: IRegistry); override; class procedure RegMenu(Reg: IMenuReg); class procedure UnRegMenu(Reg: IMenuReg); end; implementation uses SysSvc, SysFactory, SysFactoryEx, ViewSvcInfo, MainFormIntf, MenuEventBinderIntf, MenuDispatcher, SysAbout; const InstallKey = 'SYSTEM\LOADMODULE'; ValueKey = 'Module=%s;load=True'; Key_ExitApp = 'ID_52E96456-AB56-4425-9907-49BC58BCD521'; Key_ConfigTool = 'ID_45E78B02-1029-4916-8D83-6C4381DDB255'; Key_SvcInfo = 'ID_B5641F93-5CCC-4E58-8EBD-D39D3612374F'; Key_Line = 'ID_633B5F92-82F9-419B-A3B4-0A5074914DCA'; Key_About = 'ID_35E209E7-3934-4457-81D6-18C3178A91B2'; { TSysPlugin } class procedure TSysPlugin.RegisterModule(Reg: IRegistry); var ModuleFullName, ModuleName, Value: string; begin //注册菜单 Self.RegMenu(Reg as IMenuReg); //注册包 if Reg.OpenKey(InstallKey, True) then begin ModuleFullName := SysUtils.GetModuleName(HInstance); ModuleName := ExtractFileName(ModuleFullName); Value := Format(ValueKey, [ModuleFullName]); Reg.WriteString(ModuleName, Value); Reg.SaveData; end; end; class procedure TSysPlugin.RegMenu(Reg: IMenuReg); begin Reg.RegMenu(Key_Line, '文件\-'); Reg.RegMenu(Key_ExitApp, '文件\退出系统'); Reg.RegMenu(Key_SvcInfo, '工具\系统接口'); Reg.RegMenu(Key_ConfigTool, '工具\配置工具'); Reg.RegMenu(Key_About, '帮助\关于'); end; class procedure TSysPlugin.UnRegisterModule(Reg: IRegistry); var ModuleName: string; begin //取消注册菜单 Self.UnRegMenu(Reg as IMenuReg); //取消注册包 if Reg.OpenKey(InstallKey) then begin ModuleName := ExtractFileName(SysUtils.GetModuleName(HInstance)); if Reg.DeleteValue(ModuleName) then Reg.SaveData; end; end; class procedure TSysPlugin.UnRegMenu(Reg: IMenuReg); begin Reg.UnRegMenu(Key_Line); Reg.UnRegMenu(Key_ExitApp); Reg.UnRegMenu(Key_SvcInfo); Reg.UnRegMenu(Key_ConfigTool); Reg.UnRegMenu(Key_About); end; constructor TSysPlugin.Create; var obj: TObject; begin inherited; obj := TMenuDispatcher.Create; TObjFactory.Create(IMenuEventBinder, obj, True); end; destructor TSysPlugin.Destroy; begin inherited; end; procedure TSysPlugin.ConfigToolClick(Sender: TObject); var ConfigTool: string; begin ConfigTool := ExtractFilePath(ParamStr(0)) + 'ConfigTool.exe'; if FileExists(ConfigTool) then WinExec(PAnsiChar(AnsiString(ConfigTool)), SW_SHOWDEFAULT) else raise Exception.CreateFmt('末找到%s!', [ConfigTool]); end; procedure TSysPlugin.ExitApp(Sender: TObject); begin (SysService as IMainForm).ExitApplication; end; procedure TSysPlugin.final; begin inherited; end; procedure TSysPlugin.Init; var MenuEventBinder: IMenuEventBinder; begin inherited; //绑定菜单事件 MenuEventBinder := SysService as IMenuEventBinder; MenuEventBinder.RegMenuEvent(Key_ExitApp, Self.ExitApp); MenuEventBinder.RegMenuEvent(Key_SvcInfo, Self.SvcInfoClick); MenuEventBinder.RegMenuEvent(Key_ConfigTool, Self.ConfigToolClick); MenuEventBinder.RegMenuEvent(Key_About, Self.AboutClick); end; procedure TSysPlugin.SvcInfoClick(Sender: TObject); begin frm_SvcInfo := Tfrm_SvcInfo.Create(nil); frm_SvcInfo.ShowModal; frm_SvcInfo.Free; end; procedure TSysPlugin.AboutClick(Sender: TObject); begin TFrm_About.Execute; end; initialization RegisterModuleClass(TSysPlugin); finalization end.
Algoritmo "Calculadora"; Inicio logico: processo; real: c; inteiro: a, b; caractere: op; exiba("Digite uma das operações: "); receba(op) exiba("Digite um numero: "); receba(a); exiba("Digite outro numero: "); receba(b); processo <- verdadeiro; escolha(op) caso "+": c <- a + b; pare; caso "-": c <- a - b; pare; caso "*": c <- a * b; pare; caso "/": c <- a / b; pare; senao: exiba("A operação não aceita!"); processo <- falso; fim-escolha se processo então exiba("A operação resultou em ", c); senão exiba("A operação não foi reconhecida"); fim-se fim
(***************************************************************************) (* Programmname : HIMEM.PAS V1.1 *) (* Programmautor : Michael Rippl *) (* Compiler : Quick Pascal V1.0 *) (* Inhalt : Routinen fr Zugriff auf XMS V2.0 Memory *) (* Bemerkung : Muá wegen EMS Konflikten manuell initialisiert werden *) (* Letzte Žnderung : 05-Sep-1990 *) (***************************************************************************) UNIT HiMem; INTERFACE TYPE LongWord = RECORD (* Typ eines 32-Bit Wortes *) LowWord, (* Bits 0 bis 15 *) HighWord : WORD; (* Bits 16 bis 31 *) END; XmsMove = RECORD (* Typ der Move-Struktur *) Length : LONGINT; (* Blockl„nge in Bytes *) SrcHandle : WORD; (* Handle vom Quellblock *) SrcOffset : LONGINT; (* 32-Bit Quelladresse *) TarHandle : WORD; (* Handle vom Zielblock *) TarOffset : LONGINT; (* 32-Bit Zieladresse *) END; CONST XmsMemOk = $00; (* Status alles in Ordnung *) FctNotImplemented = $80; (* Funktion nicht da *) VDiskDetected = $81; (* RamDisk vorhanden *) A20ErrorOccured = $82; (* A20 Fehler aufgetreten *) HmaDoesNotExist = $90; (* Kein HMA vorhanden *) HmaAlreadyInUse = $91; (* HMA schon in Benutzung *) DXLessThanHmaMin = $92; (* DX-Gr”áe kleiner HMAMIN *) HmaNotAllocated = $93; (* HMA war nicht belegt *) A20IsStillEnabled = $94; (* A20 Line ist noch an *) AllXmsAllocated = $A0; (* XMS Speicher belegt *) AllXmsHandlesUsed = $A1; (* Alle XMS Handles weg *) HandleIsInvalid = $A2; (* Unzul„ssiges Handle *) InvalidSrcHandle = $A3; (* Quell-Handle unzul„ssig *) InvalidSrcOffset = $A4; (* Quell-Offset unzul„ssig *) InvalidTarHandle = $A5; (* Ziel-Handle unzul„ssig *) InvalidTarOffset = $A6; (* Ziel-Offset unzul„ssig *) InvalidLength = $A7; (* Unzul„ssige Blockl„nge *) InvalidMoveOverlap = $A8; (* Move-šberlappung falsch *) ParityErrorOccured = $A9; (* Parity Fehler *) BlockIsNotLocked = $AA; (* Block nicht gelock't *) HandleIsLocked = $AB; (* Handle ist geschtzt *) LockCountOverflow = $AC; (* Lock-Z„hler šberlauf *) LockFailed = $AD; (* Lock fehlgeschlagen *) SmallerUmbAvail = $B0; (* Kleinerer UMB vorhanden *) NoUmbAvail = $B1; (* Kein UMB vorhanden *) InvalidUmbSegment = $B2; (* Falsches UMB Segment *) VAR XmsMemAvail : BOOLEAN; (* XMS Speicher da *) XmsMemSize : WORD; (* Gr”áe vom XMS Speicher *) XmsMemStatus : BYTE; (* Status des Speichers *) (* Diese Prozedur initialisiert die HiMem Unit *) PROCEDURE InitXms; (* Diese Prozedur ermittelt die Versionsnummer des XMS Treibers *) PROCEDURE GetXmsVersion(VAR VerHigh, VerLow : BYTE); (* Diese Prozedur ermittelt die interne Revision des XMS Treibers *) PROCEDURE GetInternRevision(VAR RevHigh, RevLow : BYTE); (* Diese Prozedur versucht den HiMem-Bereich zu reservieren *) PROCEDURE RequestHighMemArea(Size : WORD); (* Diese Prozedur gibt den HiMem-Bereich wieder frei *) PROCEDURE ReleaseHighMemArea; (* Diese Prozedur schaltet die A20 Line an *) PROCEDURE GlobalEnableA20; (* Diese Prozedur schaltet die A20 Line aus *) PROCEDURE GlobalDisableA20; (* Diese Prozedur schaltet die A20 Line an (lokal) *) PROCEDURE LocalEnableA20; (* Diese Prozedur schaltet die A20 Line aus (lokal) *) PROCEDURE LocalDisableA20; (* Diese Funktion prft, ob die A20 Line physikalisch angeschaltet ist *) FUNCTION QueryA20 : BOOLEAN; (* Diese Prozedur holt Informationen ber den verfgbaren XMS-Speicher *) PROCEDURE QueryFreeXms(VAR LargestFree, TotalAmount : WORD); (* Diese Prozedur belegt einen XMS Speicherblock *) PROCEDURE AllocXmsBlock(Size : WORD; VAR Handle : WORD); (* Diese Prozedur gibt einen XMS Speicherblock wieder frei *) PROCEDURE FreeXmsBlock(Handle : WORD); (* Diese Prozedur verschiebt einen Speicherblock *) PROCEDURE MoveXmsBlock(MemBlock : XmsMove); (* Diese Prozedur lock't einen Speicherblock *) PROCEDURE LockXmsBlock(Handle : WORD; VAR BaseAddress : LONGINT); (* Diese Prozedur entfernt einen Lock von einem Speicherblock *) PROCEDURE UnlockXmsBlock(Handle : WORD); (* Diese Prozedur holt erweiterte Informationen ber ein Handle *) PROCEDURE GetHandleInfo(Handle : WORD; VAR LockCount, FreeHandles : BYTE; VAR BlockLength : WORD); (* Diese Prozedur „ndert die Gr”áe eines Speicherblocks *) PROCEDURE ReAllocXmsBlock(Handle, NewSize : WORD); (* Diese Prozedur belegt einen Upper Memory Block fr den Aufrufer *) PROCEDURE RequestUpperMemBlock(Paragraphs : WORD; VAR Segment, Size : WORD); (* Diese Prozedur gibt einen Upper Memory Block wieder frei *) PROCEDURE ReleaseUpperMemBlock(Segment : WORD); IMPLEMENTATION USES Dos; (* Units einbinden *) TYPE Address = RECORD (* Far-Adresse *) Offset, (* Offsetanteil *) Segment : WORD; (* Segmentanteil *) END; VAR XmsControl : Address; (* XMS Basisadresse *) XmsRegs : REGISTERS; (* Registerbergabe an XMS *) LargestFree : WORD; (* Gr”áter freier Block *) (*$F+ Diese Prozedur ruft die Basisfunktion des XMS-Treibers auf *) PROCEDURE CallXMS; EXTERNAL; (*$F-*) (*$L HiMem.Obj *) (* Diese Prozedur ermittelt die Versionsnummer des XMS Treibers *) PROCEDURE GetXmsVersion(VAR VerHigh, VerLow : BYTE); BEGIN XmsRegs.AH := $00; (* XMS Version ermitteln *) CallXMS; (* XMS Treiber aufrufen *) VerHigh := XmsRegs.AH; (* Stellen vor dem Punkt *) VerLow := XmsRegs.AL; (* Stellen nach dem Punkt *) END; (* GetXmsVersion *) (* Diese Prozedur ermittelt die interne Revision des XMS Treibers *) PROCEDURE GetInternRevision(VAR RevHigh, RevLow : BYTE); BEGIN XmsRegs.AH := $00; (* XMS Version ermitteln *) CallXMS; (* XMS Treiber aufrufen *) RevHigh := XmsRegs.BH; (* Stellen vor dem Punkt *) RevLow := XmsRegs.BL; (* Stellen nach dem Punkt *) END; (* GetInternRevision *) (* Diese Prozedur versucht den HiMem-Bereich zu reservieren *) PROCEDURE RequestHighMemArea(Size : WORD); BEGIN XmsRegs.AH := $01; (* HiMem-Bereich belegen *) XmsRegs.DX := Size; (* Gr”áe des Bereichs *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* RequestHighMemArea *) (* Diese Prozedur gibt den HiMem-Bereich wieder frei *) PROCEDURE ReleaseHighMemArea; BEGIN XmsRegs.AH := $02; (* HiMem-Bereich freigeben *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* ReleaseHighMemArea *) (* Diese Prozedur schaltet die A20 Line an *) PROCEDURE GlobalEnableA20; BEGIN XmsRegs.AH := $03; (* A20 Line erm”glichen *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* GlobalEnableA20 *) (* Diese Prozedur schaltet die A20 Line aus *) PROCEDURE GlobalDisableA20; BEGIN XmsRegs.AH := $04; (* A20 Line ausschalten *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* GlobalDisableA20 *) (* Diese Prozedur schaltet die A20 Line an (lokal) *) PROCEDURE LocalEnableA20; BEGIN XmsRegs.AH := $05; (* A20 Line erm”glichen *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* LocalEnableA20 *) (* Diese Prozedur schaltet die A20 Line aus (lokal) *) PROCEDURE LocalDisableA20; BEGIN XmsRegs.AH := $06; (* A20 Line ausschalten *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* LocalDisableA20 *) (* Diese Funktion prft, ob die A20 Line physikalisch angeschaltet ist *) FUNCTION QueryA20 : BOOLEAN; BEGIN XmsRegs.AH := $07; (* A20 Line berprfen *) CallXMS; (* XMS Treiber aufrufen *) QueryA20 := XmsRegs.AX = $0001; (* Status zurckgeben *) XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* QueryA20 *) (* Diese Prozedur holt Informationen ber den verfgbaren XMS-Speicher *) PROCEDURE QueryFreeXms(VAR LargestFree, TotalAmount : WORD); BEGIN XmsRegs.AH := $08; (* XMS Speicherinformation *) CallXMS; (* XMS Treiber aufrufen *) LargestFree := XmsRegs.AX; (* Gr”áter freier Block *) TotalAmount := XmsRegs.DX; (* Gesamtspeicher frei *) XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* QueryFreeXms *) (* Diese Prozedur belegt einen XMS Speicherblock *) PROCEDURE AllocXmsBlock(Size : WORD; VAR Handle : WORD); BEGIN XmsRegs.AH := $09; (* XMS Speicher belegen *) XmsRegs.DX := Size; (* Gr”áe vom Speicherblock *) CallXMS; (* XMS Treiber aufrufen *) Handle := XmsRegs.DX; (* Nummer des Handles *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* AllocXmsBlock *) (* Diese Prozedur gibt einen XMS Speicherblock wieder frei *) PROCEDURE FreeXmsBlock(Handle : WORD); BEGIN XmsRegs.AH := $0A; (* XMS Speicher freigeben *) XmsRegs.DX := Handle; (* Handle des Blocks *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* FreeXmsBlock *) (* Diese Prozedur verschiebt einen Speicherblock *) PROCEDURE MoveXmsBlock(MemBlock : XmsMove); BEGIN XmsRegs.AH := $0B; (* XMS Block kopieren *) XmsRegs.DS := Seg(MemBlock); (* Block-Segmentadresse *) XmsRegs.SI := Ofs(MemBlock); (* Block-Offsetadresse *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* MoveXmsBlock *) (* Diese Prozedur lock't einen Speicherblock *) PROCEDURE LockXmsBlock(Handle : WORD; VAR BaseAddress : LONGINT); BEGIN XmsRegs.AH := $0C; (* XMS Block festmachen *) XmsRegs.DX := Handle; (* Handle des Blocks *) CallXMS; (* XMS Treiber aufrufen *) LongWord(BaseAddress).LowWord := XmsRegs.DX; (* Bits 0-15 der Adresse *) LongWord(BaseAddress).HighWord := XmsRegs.BX; (* Bits 16-31 der Adresse *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* LockXmsBlock *) (* Diese Prozedur entfernt einen Lock von einem Speicherblock *) PROCEDURE UnlockXmsBlock(Handle : WORD); BEGIN XmsRegs.AH := $0D; (* XMS Block freimachen *) XmsRegs.DX := Handle; (* Handle des Blocks *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* UnlockXmsBlock *) (* Diese Prozedur holt erweiterte Informationen ber ein Handle *) PROCEDURE GetHandleInfo(Handle : WORD; VAR LockCount, FreeHandles : BYTE; VAR BlockLength : WORD); BEGIN XmsRegs.AH := $0E; (* XMS Blockinfo holen *) XmsRegs.DX := Handle; (* Handle des Blocks *) CallXMS; (* XMS Treiber aufrufen *) LockCount := XmsRegs.BH; (* Lock's auf dem Block *) FreeHandles := XmsRegs.BL; (* Freie Handles im System *) BlockLength := XmsRegs.DX; (* Blockl„nge in KB *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* GetHandleInfo *) (* Diese Prozedur „ndert die Gr”áe eines Speicherblocks *) PROCEDURE ReAllocXmsBlock(Handle, NewSize : WORD); BEGIN XmsRegs.AH := $0F; (* XMS Blockgr”áe „ndern *) XmsRegs.DX := Handle; (* Handle des Blocks *) XmsRegs.BX := NewSize; (* Neue Gr”áe des Blocks *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* ReAllocXmsBlock *) (* Diese Prozedur belegt einen Upper Memory Block fr den Aufrufer *) PROCEDURE RequestUpperMemBlock(Paragraphs : WORD; VAR Segment, Size : WORD); BEGIN XmsRegs.AH := $10; (* UMB belegen *) XmsRegs.DX := Paragraphs; (* Gr”áe des Blocks *) CallXMS; (* XMS Treiber aufrufen *) Segment := XmsRegs.BX; (* Segment des UMB's *) Size := XmsRegs.DX; (* Bei Fehler freie Par's *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* RequestUpperMemBlock *) (* Diese Prozedur gibt einen Upper Memory Block wieder frei *) PROCEDURE ReleaseUpperMemBlock(Segment : WORD); BEGIN XmsRegs.AH := $11; (* UMB freigeben *) XmsRegs.DX := Segment; (* Segment des Blocks *) CallXMS; (* XMS Treiber aufrufen *) IF XmsRegs.AX = $0001 THEN XmsMemStatus := XmsMemOk ELSE XmsMemStatus := XmsRegs.BL; (* Fehlerstatus vermerken *) END; (* ReleaseUpperMemBlock *) (* Diese Prozedur initialisiert die HiMem Unit *) PROCEDURE InitXms; VAR Regs : REGISTERS; BEGIN Regs.AX := $4300; (* XMS Speicher vorhanden *) Intr($2F, Regs); (* Multiplex Interrupt *) XmsMemAvail := Regs.AL = $80; IF XmsMemAvail THEN (* XMS Speicher vorhanden *) BEGIN Regs.AX := $4310; (* XMS Funktionsadresse *) Intr($2F, Regs); (* Multiplex Interrupt *) XmsControl.Offset := Regs.BX; (* Offset der Funktion *) XmsControl.Segment := Regs.ES; (* Segment der Funktion *) QueryFreeXms(LargestFree, XmsMemSize); (* Speichergr”áen holen *) XmsMemStatus := XmsMemOk; (* Status ist in Ordnung *) END; END; (* InitXms *) BEGIN (* Initialisierung *) XmsMemAvail := FALSE; (* Kein XMS Speicher da *) XmsMemStatus := XmsMemOk; (* Status ist in Ordnung *) XmsMemSize := 0; (* Gr”áe des XMS Speichers *) END. (* HiMem *)
unit Command.AnalyseProject; interface uses System.SysUtils, System.Classes, DelphiAST, DelphiAST.Classes, SimpleParser.Lexer.Types, DelphiAST.SimpleParserEx, IncludeHandler, {} Metrics.Project, Metrics.UnitM, Metrics.UnitMethod, Metrics.ClassM, Metrics.ClassMethod, Filters.Method; type TAnalyseProjectCommand = class private fReport: TStringList; fProjectMetrics: TProjectMetrics; procedure GenerateCsv(const methods: TArray<TUnitMethodMetrics>); procedure GenerateMethodReportConsole(const methods : TArray<TUnitMethodMetrics>); procedure GenerateClassReportConsole(const aClassMetrics: TClassMetrics); public constructor Create; destructor Destroy; override; procedure Execute(const aFiles: TArray<string>; aMethodFilters: TMethodFilters = nil); procedure SaveReportToFile(const aFileName: string); end; implementation uses Calculators.ProjectMetrics; constructor TAnalyseProjectCommand.Create; begin fReport := TStringList.Create; fProjectMetrics := TProjectMetrics.Create; end; destructor TAnalyseProjectCommand.Destroy; begin fProjectMetrics.Free; fReport.Free; inherited; end; procedure TAnalyseProjectCommand.SaveReportToFile(const aFileName: string); begin fReport.SaveToFile(aFileName); end; procedure TAnalyseProjectCommand.GenerateClassReportConsole(const aClassMetrics : TClassMetrics); var Method: TClassMethodMetrics; begin writeln(Format('%s = class', [aClassMetrics.NameOfClass])); for Method in aClassMetrics.GetMethods do begin if Method.UnitMethod = nil then writeln(Format(' %s %s', [Method.Visibility.ToSymbol(), Method.Name])) else writeln(Format(' %s %s => %s [L:%d]', [Method.Visibility.ToSymbol(), Method.Name, Method.UnitMethod.Name, Method.UnitMethod.Lenght])); end; end; procedure TAnalyseProjectCommand.GenerateMethodReportConsole (const methods: TArray<TUnitMethodMetrics>); var Method: TUnitMethodMetrics; previousUnit: string; begin previousUnit := ''; for Method in methods do begin if Method.FullUnitName <> previousUnit then writeln(Method.FullUnitName); previousUnit := Method.FullUnitName; writeln(Format(' - %s %s = [Lenght: %d] [Level: %d]', [Method.Kind, Method.Name, Method.Lenght, Method.Complexity])); end; end; var CurrentOrderNumber: Integer = 1; procedure TAnalyseProjectCommand.GenerateCsv(const methods : TArray<TUnitMethodMetrics>); var Method: TUnitMethodMetrics; begin fReport.Add(Format('"%s","%s","%s","%s","%s"', ['No', 'Unit location', 'Method', 'Length', 'Complexity'])); for Method in methods do begin fReport.Add(Format('%d,"%s","%s %s",%d,%d', [CurrentOrderNumber, Method.FullUnitName, Method.Kind, Method.Name, Method.Lenght, Method.Complexity])); inc(CurrentOrderNumber); end; end; procedure TAnalyseProjectCommand.Execute(const aFiles: TArray<string>; aMethodFilters: TMethodFilters = nil); var idx: Integer; methods: TArray<TUnitMethodMetrics>; classMetricsList: TArray<TClassMetrics>; classMetrics: TClassMetrics; begin fReport.Clear; for idx := 0 to High(aFiles) do begin Write(Format('Progress: %d. (files: %d/%d)'#13, [round(100 / Length(aFiles) * idx), idx, Length(aFiles)])); TProjectCalculator.Calculate(aFiles[idx], fProjectMetrics); end; classMetricsList := fProjectMetrics.GetClassesAll(); methods := fProjectMetrics.FilterMethods(aMethodFilters); // ---- console report ----- for classMetrics in classMetricsList do GenerateClassReportConsole(classMetrics); writeln; GenerateMethodReportConsole(methods); // -------- GenerateCsv(methods); end; end.
unit Order.Validator; interface uses DataProxy.Order; type TOrderValidator = class function IsValid(aOrder: TOrderProxy): Boolean; end; implementation uses System.Variants; function TOrderValidator.IsValid(aOrder: TOrderProxy): Boolean; var valid: Boolean; begin valid := not(aOrder.OrderDate.isNull) and not(aOrder.RequiredDate.isNull) and (aOrder.OrderDate.Value < aOrder.RequiredDate.Value) and (aOrder.ShippedDate.isNull or (aOrder.OrderDate.Value < aOrder.ShippedDate.Value)); Result := valid; {$IFDEF CONSOLEAPP} WriteLn('Validating Order....'); {$ENDIF} end; end.
unit Work.DB; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.Grids, HGM.Controls.VirtualTable, SQLLang, SQLiteTable3; type TUID = record ID:Integer; Caption:string; class function Create(AID:Integer; ACaption:string):TUID; static; end; TDatabaseCore = class private FDBFileName:string; FSQL:TSQLiteDatabase; FWork:Boolean; FQCount:Integer; procedure OnQuery(Sender:TObject; SQL:string); procedure CreateSysTable; public function GetNextVal(Index:string):Integer; constructor Create(AFileName:string); destructor Destroy; property Work:Boolean read FWork; property SQL:TSQLiteDatabase read FSQL; property QCount:Integer read FQCount; end; function CreateFIO(F, I, O:string):string; function CreateFullFIO(F, I, O:string):string; implementation function CreateFIO(F, I, O:string):string; begin Result:=F; if Length(I) > 0 then begin Result:=Result + ' ' + I[1]+'.'; if Length(O) > 0 then Result:=Result + ' ' + O[1] + '.'; end; end; function CreateFullFIO(F, I, O:string):string; begin Result:=F; if Length(I) > 0 then begin Result:=Result + ' ' + I; if Length(O) > 0 then Result:=Result + ' ' + O; end; end; { TDatabaseCore } constructor TDatabaseCore.Create(AFileName: string); begin FDBFileName:=AFileName; FWork:=False; FQCount:=0; try FSQL:=TSQLiteDatabase.Create(FDBFileName); FSQL.OnQuery:=OnQuery; CreateSysTable; FWork:=True; except FWork:=False; end; end; procedure TDatabaseCore.CreateSysTable; begin if not FSQL.TableExists('CRM_SYS_INDEX') then begin with SQLLang.SQL.CreateTable('CRM_SYS_INDEX') do begin AddField('SEC_INDEX', ftString); AddField('VALUE', ftInteger); SQL.ExecSQL(GetSQL); EndCreate; end; end; end; destructor TDatabaseCore.Destroy; begin FSQL.Free; end; function TDatabaseCore.GetNextVal(Index: string):Integer; var Value:Integer; begin with SQLLang.SQL.Select('CRM_SYS_INDEX') do begin AddField('VALUE'); WhereFieldEqual('SEC_INDEX', Index); Value:=SQL.GetTableValue(GetSQL); EndCreate; end; if Value < 0 then begin with SQLLang.SQL.InsertInto('CRM_SYS_INDEX') do begin AddValue('SEC_INDEX', Index); AddValue('VALUE', 10001); Result:=10001; SQL.ExecSQL(GetSQL); EndCreate; end; end else begin Result:=Value+1; with SQLLang.SQL.Update('CRM_SYS_INDEX') do begin AddValue('VALUE', Result); WhereFieldEqual('SEC_INDEX', Index); SQL.ExecSQL(GetSQL); EndCreate; end; end; end; procedure TDatabaseCore.OnQuery(Sender: TObject; SQL: string); begin Inc(FQCount); end; { TUID } class function TUID.Create(AID:Integer; ACaption:string): TUID; begin Result.ID:=AID; Result.Caption:=ACaption; end; end.
unit Algoritmo.TorreDeHanoi; interface uses Vcl.ExtCtrls, Desenha.Discos; type // Classe que implementa o algoritmo da torre de hanˇi TAlgoritmo = class public procedure Hanoi(AQuantidadeDiscos: Integer; var APinoOrigem, APinoDestino, APinoAuxiliar: TDesenjaDiscos.TPino ); end; implementation uses Winapi.Windows; { TAlgoritmo } procedure TAlgoritmo.Hanoi(AQuantidadeDiscos: Integer; var APinoOrigem, APinoDestino, APinoAuxiliar: TDesenjaDiscos.TPino ); procedure Mover(); var IndicePinoOrigem, IndicePinoDestino: Integer; begin // Pega o ultimo elemento no pino de origem; IndicePinoOrigem:= Length( APinoOrigem.Discos ) - 1 ; // Aloca espašo no pino destino IndicePinoDestino:= Length( APinoDestino.Discos ); SetLength( APinoDestino.Discos, IndicePinoDestino + 1); // E grava o novo valor no pino destino APinoDestino.Discos[ IndicePinoDestino ].Cor:= APinoOrigem.Discos[ IndicePinoOrigem ].Cor; APinoDestino.Discos[ IndicePinoDestino ].Tamanho := APinoOrigem.Discos[ IndicePinoOrigem ].Tamanho; // Apaga o disco que vai ser movido TDesenjaDiscos.Apagar( APinoOrigem.Painel, IndicePinoOrigem, APinoOrigem.Discos[IndicePinoOrigem].Tamanho, APinoOrigem.Discos[IndicePinoOrigem].Cor ); // Remover o disco pino de origem; SetLength( APinoOrigem.Discos, IndicePinoOrigem ); // Desenha o disco no pino destino TDesenjaDiscos.DesenharDiscos( APinoDestino.Painel, IndicePinoDestino, APinoDestino.Discos[IndicePinoDestino].Tamanho, APinoDestino.Discos[IndicePinoDestino].Cor ); Sleep( 500 ); end; begin if ( AQuantidadeDiscos = 1 ) then begin Mover() end else begin Hanoi( AQuantidadeDiscos - 1, APinoOrigem, APinoAuxiliar, APinoDestino); Mover(); Hanoi( AQuantidadeDiscos - 1, APinoAuxiliar, APinoDestino, APinoOrigem); end; end; end.
(* MIT License Copyright (c) 2018 Ondrej Kelle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) unit Compat; interface {$include common.inc} {$ifdef FPC} {$macro ON} {$endif} uses SysUtils; {$ifndef HAS_NATIVEUINT} type PNativeUInt = ^NativeUInt; NativeUInt = Cardinal; {$endif} {$ifndef HAS_RAWBYTESTRING} type RawByteString = AnsiString; {$endif} {$ifndef HAS_UINTPTR} type PUIntPtr = ^UIntPtr; UIntPtr = NativeUInt; {$endif} {$ifndef HAS_WSTRPOS} function WStrPos(const Str1, Str2: PWideChar): PWideChar; {$endif} type PUnicodeChar = ^UnicodeChar; UnicodeChar = WideChar; {$ifndef SUPPORTS_UNICODE_STRING} type PUnicodeString = ^UnicodeString; UnicodeString = WideString; {$endif} function GetBuildInfoString: string; function GetExeFileVersionString: string; {$ifdef FPC} var UTF8ToString: function(const S: RawByteString): UnicodeString = @UTF8Decode; {$endif} {$ifdef DELPHI} // initialize to US format settings (use point as decimal separator for float values) var DefaultFormatSettings: TFormatSettings; {$ifndef HAS_WIDESTRUTILS} function WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring; {$endif} {$ifndef UNICODE} var UTF8ToString: function(const S: UTF8String): WideString; {$endif} {$endif} implementation {$ifdef FPC} uses {$ifdef WINDOWS} winpeimagereader, {$endif} {$ifdef LINUX} elfreader, {$endif} {$ifdef DARWIN} machoreader, {$endif} fileinfo; {$endif} {$ifdef FPC} function GetBuildInfoString: string; begin Result := Format('FPC %d.%d.%d for %s-%s', [FPC_VERSION, FPC_RELEASE, FPC_PATCH, lowercase({$i %FPCTARGETOS%}), lowercase({$i %FPCTARGETCPU%})]) end; function GetExeFileVersionString: string; var FileVersionInfo: TFileVersionInfo; begin FileVersionInfo := TFileVersionInfo.Create(nil); try FileVersionInfo.ReadFileInfo; Result := FileVersionInfo.VersionStrings.Values['FileVersion']; finally FileVersionInfo.Free; end; end; {$ifndef HAS_WSTRPOS} function WStrPos(const Str1, Str2: PWideChar): PWideChar; begin Result := strpos(Str1, Str2); end; {$endif} {$endif} {$ifdef DELPHI} {$ifndef HAS_WIDESTRUTILS} function WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring; var SearchStr, Patt, NewStr: Widestring; Offset: Integer; begin if rfIgnoreCase in Flags then begin SearchStr := WideUpperCase(S); Patt := WideUpperCase(OldPattern); end else begin SearchStr := S; Patt := OldPattern; end; NewStr := S; Result := ''; while SearchStr <> '' do begin Offset := Pos(Patt, SearchStr); if Offset = 0 then begin Result := Result + NewStr; Break; end; Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern; NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt); if not (rfReplaceAll in Flags) then begin Result := Result + NewStr; Break; end; SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt); end; end; {$endif} {$ifdef DELPHIXE2_UP} const ArchitectureStrings: array[TOSVersion.TArchitecture] of string = ('x86', 'x64', 'arm32'{$ifdef DELPHIX_TOKYO_UP}, 'arm64'{$endif}); PlatformStrings: array[TOSVersion.TPlatform] of string = ('Windows', 'MacOS', 'iOS', 'Android', 'WinRT', 'Linux'); {$endif} function GetBuildInfoString: string; begin {$ifdef DELPHIXE2_UP} Result := Format('Delphi %.1f for %s-%s', [System.CompilerVersion, PlatformStrings[TOSVersion.Platform], ArchitectureStrings[TOSVersion.Architecture]], DefaultFormatSettings); {$else} Result := Format('Delphi %.1f for Windows-x86', [CompilerVersion], DefaultFormatSettings); {$endif} end; function GetExeFileVersionString: string; var Ver: LongRec; begin Ver := LongRec(GetFileVersion(Paramstr(0))); Result := Format('%u.%u', [Ver.Hi, Ver.Lo]); end; {$ifndef HAS_WSTRPOS} function WStrPos(const Str1, Str2: PWideChar): PWideChar; var Str, SubStr: PWideChar; Ch: WideChar; begin Result := nil; if (Str1 = nil) or (Str1^ = #0) or (Str2 = nil) or (Str2^ = #0) then Exit; Result := Str1; Ch := Str2^; repeat if Result^ = Ch then begin Str := Result; SubStr := Str2; repeat Inc(Str); Inc(SubStr); if SubStr^ = #0 then exit; if Str^ = #0 then begin Result := nil; exit; end; if Str^ <> SubStr^ then break; until (FALSE); end; Inc(Result); until (Result^ = #0); Result := nil; end; {$endif} {$endif} initialization {$ifdef DELPHI} {$ifndef UNICODE} UTF8ToString := @UTF8Decode; {$endif} {$ifdef DELPHIXE_UP} DefaultFormatSettings := TFormatSettings.Create('en-US'); {$else} GetLocaleFormatSettings(1033, DefaultFormatSettings); {$endif} {$endif} {$ifdef FPC} {$ifdef WINDOWS} GetLocaleFormatSettings(1033, DefaultFormatSettings); {$endif} {$endif} finalization end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Canvas; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$if defined(fpc) and (defined(cpux86_64) or defined(cpuamd64))} {$optimization off,level1} {$ifend} interface uses SysUtils, Classes, Math, PUCU, PasMP, Vulkan, Generics.Collections, PasVulkan.Types, PasVulkan.Math, PasVulkan.Utils, PasVulkan.Collections, PasVulkan.CircularDoublyLinkedList, PasVulkan.Framework, PasVulkan.Sprites, PasVulkan.SignedDistanceField2D, PasVulkan.Font; const pvcvsRenderingModeShift=0; pvcvsObjectModeShift=2; pvcvsFillStyleShift=10; pvcvsFillWrapModeShift=12; pvcvsSignedDistanceFieldVariantShift=14; type PpvCanvasRenderingMode=^TpvCanvasRenderingMode; TpvCanvasRenderingMode= ( Normal=0, SignedDistanceField=1 ); PpvCanvasBlendingMode=^TpvCanvasBlendingMode; TpvCanvasBlendingMode= ( None=0, NoDiscard=1, AlphaBlending=2, AdditiveBlending=3, OnlyDepth=4 ); PpvCanvasLineJoin=^TpvCanvasLineJoin; TpvCanvasLineJoin= ( Bevel, Miter, Round ); PpvCanvasLineCap=^TpvCanvasLineCap; TpvCanvasLineCap= ( Butt, Square, Round ); PpvCanvasFillRule=^TpvCanvasFillRule; TpvCanvasFillRule= ( DoNotMatter, // for pure raw speed, where is no guarantee winding fill rule correctness of triangulation NonZero, EvenOdd ); PpvCanvasFillStyle=^TpvCanvasFillStyle; TpvCanvasFillStyle= ( Color=0, Image=1, LinearGradient=2, RadialGradient=3 ); PpvCanvasFillWrapMode=^TpvCanvasFillWrapMode; TpvCanvasFillWrapMode= ( None=0, WrappedRepeat=1, MirroredRepeat=2 ); PpvCanvasTextHorizontalAlignment=^TpvCanvasTextHorizontalAlignment; TpvCanvasTextHorizontalAlignment= ( Leading, Center, Tailing ); ppvCanvasTextVerticalAlignment=^TpvCanvasTextVerticalAlignment; TpvCanvasTextVerticalAlignment= ( Leading, Middle, Tailing ); PpvCanvasPathCommandType=^TpvCanvasPathCommandType; TpvCanvasPathCommandType= ( MoveTo, LineTo, QuadraticCurveTo, CubicCurveTo, ArcTo, Close ); PpvCanvasPathCommandPoints=^TpvCanvasPathCommandPoints; TpvCanvasPathCommandPoints=array[0..2] of TpvVector2; PpvCanvasPathCommand=^TpvCanvasPathCommand; TpvCanvasPathCommand=record CommandType:TpvCanvasPathCommandType; Points:TpvCanvasPathCommandPoints; end; TpvCanvasPathCommands=array of TpvCanvasPathCommand; TpvCanvas=class; TpvCanvasStrokePatternDashes=array of TpvDouble; PpvCanvasStrokePattern=^TpvCanvasStrokePattern; TpvCanvasStrokePattern=record private fDashes:TpvCanvasStrokePatternDashes; fDashSize:TpvDouble; fStart:TpvDouble; public constructor Create(const aPattern:string;const aDashSize,aStart:TpvDouble); overload; constructor Create(const aPattern:string;const aDashSize:TpvDouble); overload; constructor Create(const aPattern:string); overload; constructor Create(const aDashes:array of TpvDouble;const aDashSize,aStart:TpvDouble); overload; constructor Create(const aDashes:array of TpvDouble;const aDashSize:TpvDouble); overload; constructor Create(const aDashes:array of TpvDouble); overload; class operator Implicit(const aPattern:string):TpvCanvasStrokePattern; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const aPattern:string):TpvCanvasStrokePattern; {$ifdef CAN_INLINE}inline;{$endif} class operator Implicit(const aDashes:TpvCanvasStrokePatternDashes):TpvCanvasStrokePattern; {$ifdef CAN_INLINE}inline;{$endif} class operator Explicit(const aDashes:TpvCanvasStrokePatternDashes):TpvCanvasStrokePattern; {$ifdef CAN_INLINE}inline;{$endif} class function Empty:TpvCanvasStrokePattern; static; {$ifdef CAN_INLINE}inline;{$endif} property Steps:TpvCanvasStrokePatternDashes read fDashes write fDashes; property DashSize:TpvDouble read fDashSize write fDashSize; property Start:TpvDouble read fStart write fStart; end; TpvCanvasPath=class(TPersistent) private fCommands:TpvCanvasPathCommands; fCountCommands:TpvInt32; function NewCommand:PpvCanvasPathCommand; public constructor Create; reintroduce; destructor Destroy; override; procedure Assign(aSource:TPersistent); override; function BeginPath:TpvCanvasPath; function EndPath:TpvCanvasPath; function ClosePath:TpvCanvasPath; function MoveTo(const aP0:TpvVector2):TpvCanvasPath; function LineTo(const aP0:TpvVector2):TpvCanvasPath; function QuadraticCurveTo(const aC0,aA0:TpvVector2):TpvCanvasPath; function CubicCurveTo(const aC0,aC1,aA0:TpvVector2):TpvCanvasPath; function ArcTo(const aP0,aP1:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; function Arc(const aCenter:TpvVector2;const aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvasPath; function Ellipse(const aCenter,aRadius:TpvVector2):TpvCanvasPath; function Circle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; function Rectangle(const aCenter,aBounds:TpvVector2):TpvCanvasPath; function RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvasPath; overload; function RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; overload; end; { TpvCanvasState } TpvCanvasState=class(TPersistent) private fBlendingMode:TpvCanvasBlendingMode; fZPosition:TpvFloat; fLineWidth:TpvFloat; fMiterLimit:TpvFloat; fLineJoin:TpvCanvasLineJoin; fLineCap:TpvCanvasLineCap; fFillRule:TpvCanvasFillRule; fFillStyle:TpvCanvasFillStyle; fFillWrapMode:TpvCanvasFillWrapMode; fColor:TpvVector4; fClipRect:TpvRect; fClipSpaceClipRect:TpvRect; fScissor:TVkRect2D; fProjectionMatrix:TpvMatrix4x4; fViewMatrix:TpvMatrix4x4; fModelMatrix:TpvMatrix4x4; fFillMatrix:TpvMatrix4x4; fFont:TpvFont; fFontSize:TpvFloat; fTextHorizontalAlignment:TpvCanvasTextHorizontalAlignment; fTextVerticalAlignment:TpvCanvasTextVerticalAlignment; fPath:TpvCanvasPath; fTexture:TObject; fAtlasTexture:TObject; fGUIElementMode:boolean; fStrokePattern:TpvCanvasStrokePattern; procedure UpdateClipSpaceClipRect(const aCanvas:TpvCanvas); function GetColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetStartColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetStartColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetStopColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetStopColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetFillMatrix:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFillMatrix(const aMatrix:TpvMatrix4x4); {$ifdef CAN_INLINE}inline;{$endif} procedure Reset; public constructor Create; reintroduce; destructor Destroy; override; procedure Assign(aSource:TPersistent); override; public property Color:TpvVector4 read GetColor write SetColor; property StartColor:TpvVector4 read GetStartColor write SetStartColor; property StopColor:TpvVector4 read GetStopColor write SetStopColor; property ClipRect:TpvRect read fClipRect write fClipRect; property Scissor:TVkRect2D read fScissor write fScissor; property ProjectionMatrix:TpvMatrix4x4 read fProjectionMatrix write fProjectionMatrix; property ViewMatrix:TpvMatrix4x4 read fViewMatrix write fViewMatrix; property ModelMatrix:TpvMatrix4x4 read fModelMatrix write fModelMatrix; property FillMatrix:TpvMatrix4x4 read GetFillMatrix write SetFillMatrix; property StrokePattern:TpvCanvasStrokePattern read fStrokePattern write fStrokePattern; published property BlendingMode:TpvCanvasBlendingMode read fBlendingMode write fBlendingMode; property ZPosition:TpvFloat read fZPosition write fZPosition; property LineWidth:TpvFloat read fLineWidth write fLineWidth; property MiterLimit:TpvFloat read fMiterLimit write fMiterLimit; property LineJoin:TpvCanvasLineJoin read fLineJoin write fLineJoin; property LineCap:TpvCanvasLineCap read fLineCap write fLineCap; property FillRule:TpvCanvasFillRule read fFillRule write fFillRule; property FillStyle:TpvCanvasFillStyle read fFillStyle write fFillStyle; property FillWrapMode:TpvCanvasFillWrapMode read fFillWrapMode write fFillWrapMode; property Font:TpvFont read fFont write fFont; property FontSize:TpvFloat read fFontSize write fFontSize; property TextHorizontalAlignment:TpvCanvasTextHorizontalAlignment read fTextHorizontalAlignment write fTextHorizontalAlignment; property TextVerticalAlignment:TpvCanvasTextVerticalAlignment read fTextVerticalAlignment write fTextVerticalAlignment; property Path:TpvCanvasPath read fPath write fPath; property Texture:TObject read fTexture write fTexture; end; TpvCanvasStateStack=class(TObjectStack<TpvCanvasState>); PpvCanvasShapeCacheVertex=^TpvCanvasShapeCacheVertex; TpvCanvasShapeCacheVertex=record ObjectMode:TVkUInt32; Position:TpvVector2; MetaInfo:TpvVector4; Offset:TpvVector2; end; PpvCanvasShapeCacheLinePoint=^TpvCanvasShapeCacheLinePoint; TpvCanvasShapeCacheLinePoint=record Position:TpvVector2; case boolean of false:( Middle:TpvVector2; ); true:( Last:TpvInt32; ); end; TpvCanvasShapeCacheLinePoints=array of TpvCanvasShapeCacheLinePoint; PpvCanvasShapeCacheSegmentScalar=^TpvCanvasShapeCacheSegmentScalar; TpvCanvasShapeCacheSegmentScalar=TpvDouble; PpvCanvasShapeCacheSegmentPoint=^TpvCanvasShapeCacheSegmentPoint; TpvCanvasShapeCacheSegmentPoint=record x:TpvCanvasShapeCacheSegmentScalar; y:TpvCanvasShapeCacheSegmentScalar; end; PpvCanvasShapeCacheSegmentTwoPoints=^TpvCanvasShapeCacheSegmentTwoPoints; TpvCanvasShapeCacheSegmentTwoPoints=array[0..1] of TpvInt32; PpvCanvasShapeCacheSegment=^TpvCanvasShapeCacheSegment; TpvCanvasShapeCacheSegment=record Previous:TpvInt32; Next:TpvInt32; Points:TpvCanvasShapeCacheSegmentTwoPoints; AABBMin:TpvCanvasShapeCacheSegmentPoint; AABBMax:TpvCanvasShapeCacheSegmentPoint; end; TpvCanvasShapeCacheSegments=array of TpvCanvasShapeCacheSegment; PpvCanvasShapeCacheSegmentUniquePoint=^TpvCanvasShapeCacheSegmentUniquePoint; TpvCanvasShapeCacheSegmentUniquePoint=record HashNext:TpvInt32; Hash:TpvUInt32; Point:TpvCanvasShapeCacheSegmentPoint; end; TpvCanvasShapeCacheSegmentUniquePoints=array of TpvCanvasShapeCacheSegmentUniquePoint; TpvCanvasShapeCacheSegmentUniquePointIndices=array of TpvInt32; PpvCanvasShapeCacheVertices=^TpvCanvasShapeCacheVertices; TpvCanvasShapeCacheVertices=array of TpvCanvasShapeCacheVertex; TpvCanvasShapeCacheIndices=array of TpvInt32; PpvCanvasShapeCachePart=^TpvCanvasShapeCachePart; TpvCanvasShapeCachePart=record BaseVertexIndex:TpvInt32; BaseIndexIndex:TpvInt32; CountVertices:TpvInt32; CountIndices:TpvInt32; end; TpvCanvasShapeCacheParts=array of TpvCanvasShapeCachePart; TpvCanvasShapeCacheYCoordinates=array of TpvCanvasShapeCacheSegmentScalar; EpvCanvasShape=class(Exception); TpvCanvasShape=class private const pvCanvasShapeCacheSegmentUniquePointHashSize=1 shl 12; pvCanvasShapeCacheSegmentUniquePointHashMask=pvCanvasShapeCacheSegmentUniquePointHashSize-1; type TpvCanvasShapeCacheSegmentUniquePointHashTable=array of TpvInt32; private fCacheTemporaryLinePoints:TpvCanvasShapeCacheLinePoints; fCacheLinePoints:TpvCanvasShapeCacheLinePoints; fCacheSegments:TpvCanvasShapeCacheSegments; fCacheSegmentUniquePoints:TpvCanvasShapeCacheSegmentUniquePoints; fCacheSegmentUniquePointHashTable:TpvCanvasShapeCacheSegmentUniquePointHashTable; fCacheVertices:TpvCanvasShapeCacheVertices; fCacheIndices:TpvCanvasShapeCacheIndices; fCacheParts:TpvCanvasShapeCacheParts; fCacheYCoordinates:TpvCanvasShapeCacheYCoordinates; fCacheTemporaryYCoordinates:TpvCanvasShapeCacheYCoordinates; fCountCacheTemporaryLinePoints:TpvInt32; fCountCacheLinePoints:TpvInt32; fCountCacheSegments:TpvInt32; fCountCacheSegmentUniquePoints:TpvInt32; fCountCacheVertices:TpvInt32; fCountCacheIndices:TpvInt32; fCountCacheParts:TpvInt32; fCountCacheYCoordinates:TpvInt32; fCacheFirstSegment:TpvInt32; fCacheLastSegment:TpvInt32; fForcedCurveTessellationTolerance:TpvDouble; fCurveTessellationTolerance:TpvDouble; fCurveTessellationToleranceSquared:TpvDouble; procedure InitializeCurveTessellationTolerance(const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); procedure BeginPart(const aCountVertices:TpvInt32=0;const aCountIndices:TpvInt32=0); procedure EndPart; function AddVertex(const Position:TpvVector2;const ObjectMode:TpvUInt8;const MetaInfo:TpvVector4;const Offset:TpvVector2):TpvInt32; function AddIndex(const VertexIndex:TpvInt32):TpvInt32; function GetWindingNumberAtPointInPolygon(const Point:TpvVector2):TpvInt32; public constructor Create; reintroduce; destructor Destroy; override; procedure Reset; procedure StrokeFromPath(const aPath:TpvCanvasPath;const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); procedure FillFromPath(const aPath:TpvCanvasPath;const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); property ForcedCurveTessellationTolerance:TpvDouble read fForcedCurveTessellationTolerance write fForcedCurveTessellationTolerance; end; PpvCanvasVertex=^TpvCanvasVertex; TpvCanvasVertex=packed record // Size Offset Position:TpvVector3; // 12 bytes (3x 32-bit floats) = Color:TpvHalfFloatVector4; // + 8 bytes (4x 16-bit half-floats) = TextureCoord:TpvVector3; // + 12 bytes (3x 32-bit floats) = State:TpvUInt32; // + 4 bytes (1x 32-bit unsigned integer) = ClipRect:TpvRect; // + 16 bytes (4x 32-bit floats) = MetaInfo:TpvVector4; // + 16 bytes (4x 32-bit floats) = end; // = 68 bytes per vertex TpvCanvasVertices=array of TpvCanvasVertex; TpvCanvasVulkanBuffers=array of TpvVulkanBuffer; PpvCanvasVertexBuffer=^TpvCanvasVertexBuffer; TpvCanvasVertexBuffer=array[0..(32768*4)-1] of TpvCanvasVertex; TpvCanvasVertexBuffers=array of TpvCanvasVertexBuffer; TpvCanvasVertexBufferSizes=array of TVkSizeInt; PpvCanvasIndexBuffer=^TpvCanvasIndexBuffer; TpvCanvasIndexBuffer=array[0..((SizeOf(TpvCanvasVertexBuffer) div (SizeOf(TpvCanvasVertex)*4))*6)-1] of TpvUInt32; TpvCanvasIndexBuffers=array of TpvCanvasIndexBuffer; TpvCanvasIndexBufferSizes=array of TVkSizeInt; TpvCanvasHook=procedure(const aData:TpvPointer;const aVulkanCommandBuffer:TpvVulkanCommandBuffer;const aBufferIndex:TpvInt32) of object; TpvCanvasQueueItemKind= ( None, Normal, Hook ); PpvCanvasPushConstants=^TpvCanvasPushConstants; TpvCanvasPushConstants=record TransformMatrix:TpvMatrix4x4; FillMatrix:TpvMatrix4x4; end; TpvCanvasVulkanDescriptor=class; TpvCanvasVulkanDescriptorLinkedListNode=TpvCircularDoublyLinkedListNode<TpvCanvasVulkanDescriptor>; TpvCanvasVulkanDescriptor=class(TpvCanvasVulkanDescriptorLinkedListNode) private fCanvas:TpvCanvas; fDescriptorPool:TpvVulkanDescriptorPool; fDescriptorSet:TpvVulkanDescriptorSet; fDescriptorTexture:TObject; fLastUsedFrameNumber:TpvNativeUInt; public constructor Create(const aCanvas:TpvCanvas); reintroduce; destructor Destroy; override; published property Canvas:TpvCanvas read fCanvas; property DescriptorPool:TpvVulkanDescriptorPool read fDescriptorPool write fDescriptorPool; property DescriptorSet:TpvVulkanDescriptorSet read fDescriptorSet write fDescriptorSet; property DescriptorTexture:TObject read fDescriptorTexture write fDescriptorTexture; property LastUsedFrameNumber:TpvNativeUInt read fLastUsedFrameNumber write fLastUsedFrameNumber; end; TpvCanvasTextureDescriptorSetHashMap=class(TpvHashMap<TObject,TpvCanvasVulkanDescriptor>); PpvCanvasQueueItem=^TpvCanvasQueueItem; TpvCanvasQueueItem=record Kind:TpvCanvasQueueItemKind; BufferIndex:TpvInt32; Descriptor:TpvCanvasVulkanDescriptor; BlendingMode:TpvCanvasBlendingMode; TextureMode:TpvInt32; StartVertexIndex:TpvInt32; StartIndexIndex:TpvInt32; CountVertices:TpvInt32; CountIndices:TpvInt32; Scissor:TVkRect2D; PushConstants:TpvCanvasPushConstants; Hook:TpvCanvasHook; HookData:TVkPointer; end; TpvCanvasQueueItems=array of TpvCanvasQueueItem; PpvCanvasTextGlyphRect=^TpvCanvasTextGlyphRect; TpvCanvasTextGlyphRect=TpvRect; TpvCanvasTextGlyphRects=TpvRectArray; PpvCanvasBuffer=^TpvCanvasBuffer; TpvCanvasBuffer=record fSpinLock:TpvInt32; fVulkanVertexBuffers:TpvCanvasVulkanBuffers; fVulkanIndexBuffers:TpvCanvasVulkanBuffers; fVertexBuffers:TpvCanvasVertexBuffers; fVertexBufferSizes:TpvCanvasVertexBufferSizes; fIndexBuffers:TpvCanvasIndexBuffers; fIndexBufferSizes:TpvCanvasIndexBufferSizes; fCountAllocatedBuffers:TpvInt32; fCountUsedBuffers:TpvInt32; fQueueItems:TpvCanvasQueueItems; fCountQueueItems:TpvInt32; end; TpvCanvasBuffers=array of TpvCanvasBuffer; TpvCanvasCommon=class private class var fLock:TPasMPInt32; private fDevice:TpvVulkanDevice; fReferenceCounter:TpvInt32; fCanvasVertexShaderModule:TpvVulkanShaderModule; fCanvasVertexNoTextureShaderModule:TpvVulkanShaderModule; fCanvasFragmentGUINoTextureShaderModule:TpvVulkanShaderModule; fCanvasFragmentNoTextureShaderModule:TpvVulkanShaderModule; fCanvasFragmentTextureShaderModule:TpvVulkanShaderModule; fCanvasFragmentAtlasTextureShaderModule:TpvVulkanShaderModule; fCanvasFragmentVectorPathShaderModule:TpvVulkanShaderModule; fCanvasFragmentGUINoTextureNoBlendingShaderModule:TpvVulkanShaderModule; fCanvasFragmentNoTextureNoBlendingShaderModule:TpvVulkanShaderModule; fCanvasFragmentTextureNoBlendingShaderModule:TpvVulkanShaderModule; fCanvasFragmentAtlasTextureNoBlendingShaderModule:TpvVulkanShaderModule; fCanvasFragmentVectorPathNoBlendingShaderModule:TpvVulkanShaderModule; fCanvasFragmentGUINoTextureNoBlendingNoDiscardShaderModule:TpvVulkanShaderModule; fCanvasFragmentNoTextureNoBlendingNoDiscardShaderModule:TpvVulkanShaderModule; fCanvasFragmentTextureNoBlendingNoDiscardShaderModule:TpvVulkanShaderModule; fCanvasFragmentAtlasTextureNoBlendingNoDiscardShaderModule:TpvVulkanShaderModule; fCanvasFragmentVectorPathNoBlendingNoDiscardShaderModule:TpvVulkanShaderModule; fVulkanPipelineCanvasShaderStageVertex:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageVertexNoTexture:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentGUINoTexture:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentNoTexture:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentTexture:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentAtlasTexture:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentVectorPath:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlending:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlending:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentTextureNoBlending:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlending:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlending:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlendingNoDiscard:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlendingNoDiscard:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentTextureNoBlendingNoDiscard:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlendingNoDiscard:TpvVulkanPipelineShaderStage; fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlendingNoDiscard:TpvVulkanPipelineShaderStage; public constructor Create(const aDevice:TpvVulkanDevice); reintroduce; destructor Destroy; override; class function Acquire(const aDevice:TpvVulkanDevice):TpvCanvasCommon; class procedure Release(const aDevice:TpvVulkanDevice); end; TpvCanvasVulkanPipelineLayouts=array[TpvCanvasBlendingMode,0..3] of TpvVulkanPipelineLayout; TpvCanvasVulkanGraphicsPipelines=array[TpvCanvasBlendingMode,0..3] of TpvVulkanGraphicsPipeline; TpvCanvas=class private fDevice:TpvVulkanDevice; fCanvasCommon:TpvCanvasCommon; fPipelineCache:TpvVulkanPipelineCache; fVulkanDescriptors:TpvCanvasVulkanDescriptorLinkedListNode; fVulkanDescriptorSetGUINoTextureLayout:TpvVulkanDescriptorSetLayout; fVulkanDescriptorSetNoTextureLayout:TpvVulkanDescriptorSetLayout; fVulkanDescriptorSetTextureLayout:TpvVulkanDescriptorSetLayout; fVulkanDescriptorSetVectorPathLayout:TpvVulkanDescriptorSetLayout; fCountVulkanDescriptors:TpvInt32; fVulkanTextureDescriptorSetHashMap:TpvCanvasTextureDescriptorSetHashMap; fVulkanRenderPass:TpvVulkanRenderPass; fVulkanPipelineLayouts:TpvCanvasVulkanPipelineLayouts; fVulkanGraphicsPipelines:TpvCanvasVulkanGraphicsPipelines; fVulkanCanvasBuffers:TpvCanvasBuffers; fCountBuffers:TpvInt32; fCurrentFillBuffer:PpvCanvasBuffer; fCountProcessingBuffers:TpvInt32; fCurrentFrameNumber:TpvNativeUInt; fWidth:TpvInt32; fHeight:TpvInt32; fViewPort:TVkViewport; fPointerToViewport:PVkViewport; fCurrentVulkanBufferIndex:TpvInt32; fCurrentVulkanVertexBufferOffset:TpvInt32; fCurrentVulkanIndexBufferOffset:TpvInt32; fCurrentCountVertices:TVkSizeInt; fCurrentCountIndices:TVkSizeInt; fCurrentDestinationVertexBufferPointer:PpvCanvasVertexBuffer; fCurrentDestinationIndexBufferPointer:PpvCanvasIndexBuffer; fInternalRenderingMode:TpvCanvasRenderingMode; fSignedDistanceFieldVariant:TpvSignedDistanceField2DVariant; fShape:TpvCanvasShape; fState:TpvCanvasState; fStateStack:TpvCanvasStateStack; procedure SetVulkanRenderPass(const aVulkanRenderPass:TpvVulkanRenderPass); procedure SetCountBuffers(const aCountBuffers:TpvInt32); function GetTexture:TObject; {$ifdef CAN_INLINE}inline;{$endif} procedure SetTexture(const aTexture:TObject); function GetAtlasTexture:TObject; {$ifdef CAN_INLINE}inline;{$endif} procedure SetAtlasTexture(const aTexture:TObject); function GetGUIElementMode:boolean; {$ifdef CAN_INLINE}inline;{$endif} procedure SetGUIElementMode(const aGUIElementMode:boolean); function GetBlendingMode:TpvCanvasBlendingMode; {$ifdef CAN_INLINE}inline;{$endif} procedure SetBlendingMode(const aBlendingMode:TpvCanvasBlendingMode); function GetZPosition:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetZPosition(const aZPosition:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetLineWidth:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetLineWidth(const aLineWidth:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetMiterLimit:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetMiterLimit(const aMiterLimit:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetLineJoin:TpvCanvasLineJoin; {$ifdef CAN_INLINE}inline;{$endif} procedure SetLineJoin(const aLineJoin:TpvCanvasLineJoin); {$ifdef CAN_INLINE}inline;{$endif} function GetLineCap:TpvCanvasLineCap; {$ifdef CAN_INLINE}inline;{$endif} procedure SetLineCap(const aLineCap:TpvCanvasLineCap); {$ifdef CAN_INLINE}inline;{$endif} function GetFillRule:TpvCanvasFillRule; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFillRule(const aFillRule:TpvCanvasFillRule); {$ifdef CAN_INLINE}inline;{$endif} function GetFillStyle:TpvCanvasFillStyle; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFillStyle(const aFillStyle:TpvCanvasFillStyle); {$ifdef CAN_INLINE}inline;{$endif} function GetFillWrapMode:TpvCanvasFillWrapMode; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFillWrapMode(const aFillWrapMode:TpvCanvasFillWrapMode); {$ifdef CAN_INLINE}inline;{$endif} function GetColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetStartColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetStartColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetStopColor:TpvVector4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetStopColor(const aColor:TpvVector4); {$ifdef CAN_INLINE}inline;{$endif} function GetProjectionMatrix:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetProjectionMatrix(const aProjectionMatrix:TpvMatrix4x4); function GetViewMatrix:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetViewMatrix(const aViewMatrix:TpvMatrix4x4); function GetModelMatrix:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetModelMatrix(const aModelMatrix:TpvMatrix4x4); {$ifdef CAN_INLINE}inline;{$endif} function GetFillMatrix:TpvMatrix4x4; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFillMatrix(const aMatrix:TpvMatrix4x4); {$ifdef CAN_INLINE}inline;{$endif} function GetStrokePattern:TpvCanvasStrokePattern; {$ifdef CAN_INLINE}inline;{$endif} procedure SetStrokePattern(const aStrokePattern:TpvCanvasStrokePattern); {$ifdef CAN_INLINE}inline;{$endif} function GetFont:TpvFont; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFont(const aFont:TpvFont); {$ifdef CAN_INLINE}inline;{$endif} function GetFontSize:TpvFloat; {$ifdef CAN_INLINE}inline;{$endif} procedure SetFontSize(const aFontSize:TpvFloat); {$ifdef CAN_INLINE}inline;{$endif} function GetTextHorizontalAlignment:TpvCanvasTextHorizontalAlignment; {$ifdef CAN_INLINE}inline;{$endif} procedure SetTextHorizontalAlignment(aTextHorizontalAlignment:TpvCanvasTextHorizontalAlignment); {$ifdef CAN_INLINE}inline;{$endif} function GetTextVerticalAlignment:TpvCanvasTextVerticalAlignment; {$ifdef CAN_INLINE}inline;{$endif} procedure SetTextVerticalAlignment(aTextVerticalAlignment:TpvCanvasTextVerticalAlignment); {$ifdef CAN_INLINE}inline;{$endif} procedure GetNextDestinationVertexBuffer; function ClipCheck(const aX0,aY0,aX1,aY1:TpvFloat):boolean; function GetVertexState:TpvUInt32; {$ifdef CAN_INLINE}inline;{$endif} procedure GarbageCollectDescriptors; public constructor Create(const aDevice:TpvVulkanDevice; const aPipelineCache:TpvVulkanPipelineCache; const aCountProcessingBuffers:TpvInt32=4); reintroduce; destructor Destroy; override; procedure Start(const aBufferIndex:TpvInt32); procedure Stop; procedure DeleteTextureFromCachedDescriptors(const aTexture:TObject); procedure Flush; procedure SetScissor(const aScissor:TVkRect2D); overload; procedure SetScissor(const aLeft,aTop,aWidth,aHeight:TpvInt32); overload; function GetClipRect:TpvRect; procedure SetClipRect(const aClipRect:TVkRect2D); overload; procedure SetClipRect(const aClipRect:TpvRect); overload; procedure SetClipRect(const aLeft,aTop,aWidth,aHeight:TpvInt32); overload; public procedure EnsureSufficientReserveUsableSpace(const aCountVertices,aCountIndices:TpvInt32); function AddVertex(const aPosition:TpvVector2;const aTexCoord:TpvVector3;const aColor:TpvVector4):TpvInt32; function AddIndex(const aVertexIndex:TpvInt32):TpvInt32; {$ifdef CAN_INLINE}inline;{$endif} public procedure ExecuteUpload(const aVulkanTransferQueue:TpvVulkanQueue;const aVulkanTransferCommandBuffer:TpvVulkanCommandBuffer;const aVulkanTransferCommandBufferFence:TpvVulkanFence;const aBufferIndex:TpvInt32); procedure ExecuteDraw(const aVulkanCommandBuffer:TpvVulkanCommandBuffer;const aBufferIndex:TpvInt32); public function Push:TpvCanvas; function Pop:TpvCanvas; public function Hook(const aHook:TpvCanvasHook;const aData:TpvPointer):TpvCanvas; overload; public function DrawSprite(const aSprite:TpvSprite;const aSrc,aDest:TpvRect):TpvCanvas; overload; function DrawSprite(const aSprite:TpvSprite;const aSrc,aDest:TpvRect;const aOrigin:TpvVector2;const aRotationAngle:TpvFloat):TpvCanvas; overload; function DrawSprite(const aSprite:TpvSprite;const aPosition:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawSprite(const aSprite:TpvSprite):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} public procedure DrawSpriteProc(const aSprite:TpvSprite;const aSrc,aDest:TpvRect); inline; public function DrawNinePatchSprite(const aSprite:TpvSprite;const aNinePatch:TpvSpriteNinePatch;const aPosition,aSize:TpvVector2):TpvCanvas; overload; public function TextWidth(const aText:TpvUTF8String):TpvFloat; function TextHeight(const aText:TpvUTF8String):TpvFloat; function TextSize(const aText:TpvUTF8String):TpvVector2; function TextRowHeight(const aPercent:TpvFloat):TpvFloat; procedure TextGlyphRects(const aText:TpvUTF8String;const aPosition:TpvVector2;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); overload; procedure TextGlyphRects(const aText:TpvUTF8String;const aX,aY:TpvFloat;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); overload; procedure TextGlyphRects(const aText:TpvUTF8String;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); overload; function TextGlyphRects(const aText:TpvUTF8String;const aPosition:TpvVector2):TpvCanvasTextGlyphRects; overload; function TextGlyphRects(const aText:TpvUTF8String;const aX,aY:TpvFloat):TpvCanvasTextGlyphRects; overload; {$ifdef CAN_INLINE}inline;{$endif} function TextGlyphRects(const aText:TpvUTF8String):TpvCanvasTextGlyphRects; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawTextCodePoint(const aTextCodePoint:TpvUInt32;const aPosition:TpvVector2):TpvCanvas; overload; function DrawTextCodePoint(const aTextCodePoint:TpvUInt32;const aX,aY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawTextCodePoint(const aTextCodePoint:TpvUInt32):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawText(const aText:TpvUTF8String;const aPosition:TpvVector2):TpvCanvas; overload; function DrawText(const aText:TpvUTF8String;const aX,aY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawText(const aText:TpvUTF8String):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} public function DrawFilledEllipse(const aCenter,aRadius:TpvVector2):TpvCanvas; overload; function DrawFilledEllipse(const aCenterX,aCenterY,aRadiusX,aRadiusY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawFilledCircle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvas; overload; function DrawFilledCircle(const aCenterX,aCenterY,aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawFilledRectangle(const aCenter,aBounds:TpvVector2):TpvCanvas; overload; function DrawFilledRectangle(const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawFilledRectangle(const aRect:TpvRect):TpvCanvas; overload; public function DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aCenter,aBounds:TpvVector2;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; overload; function DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aRect:TpvRect;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; overload; public function DrawGUIElement(const aGUIElement:TVkInt32;const aFocused:boolean;const aMin,aMax,aMetaMin,aMetaMax:TpvVector2;const aMeta:TpvFloat=0.0):TpvCanvas; overload; function DrawGUIElement(const aGUIElement:TVkInt32;const aFocused:boolean;const aMinX,aMinY,aMaxX,aMaxY,aMetaMinX,aMetaMinY,aMetaMaxX,aMetaMaxY:TpvFloat;const aMeta:TpvFloat=0.0):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} public function DrawShape(const aShape:TpvCanvasShape):TpvCanvas; public function BeginPath:TpvCanvas; {$ifdef CAN_INLINE}inline;{$endif} function EndPath:TpvCanvas; {$ifdef CAN_INLINE}inline;{$endif} function ClosePath:TpvCanvas; {$ifdef CAN_INLINE}inline;{$endif} public function MoveTo(const aP0:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function MoveTo(const aX,aY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function LineTo(const aP0:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function LineTo(const aX,aY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function QuadraticCurveTo(const aC0,aA0:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function QuadraticCurveTo(const aCX,aCY,aAX,aAY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function CubicCurveTo(const aC0,aC1,aA0:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function CubicCurveTo(const aC0X,aC0Y,aC1X,aC1Y,aAX,aAY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function ArcTo(const aP0,aP1:TpvVector2;const aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function ArcTo(const aP0X,aP0Y,aP1X,aP1Y,aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Arc(const aCenter:TpvVector2;const aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Arc(const aCenterX,aCenterY,aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Ellipse(const aCenter,aRadius:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Ellipse(const aCenterX,aCenterY,aRadiusX,aRadiusY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Circle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Circle(const aCenterX,aCenterY,aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Rectangle(const aCenter,aBounds:TpvVector2):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Rectangle(const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function Rectangle(const aRect:TpvRect):TpvCanvas; overload; function RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function RoundedRectangle(const aCenterX,aCenterY,aBoundX,aBoundY,aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function RoundedRectangle(const aRect:TpvRect;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; overload; function RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function RoundedRectangle(const aCenterX,aCenterY,aBoundX,aBoundY,aRadius:TpvFloat):TpvCanvas; overload; {$ifdef CAN_INLINE}inline;{$endif} function RoundedRectangle(const aRect:TpvRect;const aRadius:TpvFloat):TpvCanvas; overload; public function Stroke:TpvCanvas; function Fill:TpvCanvas; public function GetStrokeShape:TpvCanvasShape; function GetFillShape:TpvCanvasShape; public property Viewport:PVkViewport read fPointerToViewport; property ClipRect:TpvRect read GetClipRect write SetClipRect; property Color:TpvVector4 read GetColor write SetColor; property StartColor:TpvVector4 read GetStartColor write SetStartColor; property StopColor:TpvVector4 read GetStopColor write SetStopColor; property ProjectionMatrix:TpvMatrix4x4 read GetProjectionMatrix write SetProjectionMatrix; property ViewMatrix:TpvMatrix4x4 read GetViewMatrix write SetViewMatrix; property ModelMatrix:TpvMatrix4x4 read GetModelMatrix write SetModelMatrix; property FillMatrix:TpvMatrix4x4 read GetFillMatrix write SetFillMatrix; property StrokePattern:TpvCanvasStrokePattern read GetStrokePattern write SetStrokePattern; property Font:TpvFont read GetFont write SetFont; property FontSize:TpvFloat read GetFontSize write SetFontSize; property TextHorizontalAlignment:TpvCanvasTextHorizontalAlignment read GetTextHorizontalAlignment write SetTextHorizontalAlignment; property TextVerticalAlignment:TpvCanvasTextVerticalAlignment read GetTextVerticalAlignment write SetTextVerticalAlignment; published property Device:TpvVulkanDevice read fDevice; property VulkanRenderPass:TpvVulkanRenderPass read fVulkanRenderPass write SetVulkanRenderPass; property CountBuffers:TpvInt32 read fCountBuffers write SetCountBuffers; property Width:TpvInt32 read fWidth write fWidth; property Height:TpvInt32 read fHeight write fHeight; property BlendingMode:TpvCanvasBlendingMode read GetBlendingMode write SetBlendingMode; property ZPosition:TpvFloat read GetZPosition write SetZPosition; property LineWidth:TpvFloat read GetLineWidth write SetLineWidth; property MiterLimit:TpvFloat read GetMiterLimit write SetMiterLimit; property LineJoin:TpvCanvasLineJoin read GetLineJoin write SetLineJoin; property LineCap:TpvCanvasLineCap read GetLineCap write SetLineCap; property FillRule:TpvCanvasFillRule read GetFillRule write SetFillRule; property FillStyle:TpvCanvasFillStyle read GetFillStyle write SetFillStyle; property FillWrapMode:TpvCanvasFillWrapMode read GetFillWrapMode write SetFillWrapMode; property Texture:TObject read GetTexture write SetTexture; property State:TpvCanvasState read fState; end; implementation uses PasVulkan.Assets, PasVulkan.Streams, PasDblStrUtils; const pcvvaomSolid=0; pcvvaomLineEdge=1; pcvvaomRoundLineCapCircle=2; pcvvaomRoundLine=3; pcvvaomCircle=4; pcvvaomEllipse=5; pcvvaomRectangle=6; CurveRecursionLimit=16; {$if defined(fpc) and (defined(cpu386) or defined(cpux64) or defined(cpuamd64))} // For to avoid "Fatal: Internal error 200604201" at the FreePascal compiler, when >= -O2 is used function Sign(const aValue:TpvDouble):TpvInt32; begin if aValue<0.0 then begin result:=-1; end else if aValue>0.0 then begin result:=1; end else begin result:=0; end; end; {$ifend} constructor TpvCanvasStrokePattern.Create(const aPattern:string;const aDashSize,aStart:TpvDouble); var CountSteps,Position,Len,StartPosition,Count,Index:TpvInt32; Value:TpvDouble; OK:TPasDblStrUtilsBoolean; c:AnsiChar; begin fDashSize:=aDashSize; fStart:=aStart; fDashes:=nil; CountSteps:=0; try Len:=length(aPattern); if Len>0 then begin Position:=1; if AnsiChar(aPattern[Position]) in ['0'..'9','x','X','o','O','a'..'f','A'..'F'] then begin while Position<=Len do begin if AnsiChar(aPattern[Position]) in ['0'..'9','x','X','o','O','-','+','a'..'f','A'..'F'] then begin StartPosition:=Position; repeat inc(Position); until (Position>Len) or not (AnsiChar(aPattern[Position]) in ['0'..'9','x','X','o','O','-','+','a'..'f','A'..'F']); OK:=false; Value:=ConvertStringToDouble(TPasDblStrUtilsRawByteString(Copy(aPattern,StartPosition,Position-StartPosition)),rmNearest,@OK,-1); if OK and not SameValue(Value,0) then begin if length(fDashes)<(CountSteps+1) then begin SetLength(fDashes,(CountSteps+1)*2); end; fDashes[CountSteps]:=Value; inc(CountSteps); end; end else begin break; end; if (Position<=Len) and (AnsiChar(aPattern[Position]) in [#0..#32,',']) then begin repeat inc(Position); until (Position>Len) or not (AnsiChar(aPattern[Position]) in [#0..#32,',']); end else begin break; end; end; end else begin while Position<=Len do begin c:=AnsiChar(AnsiChar(aPattern[Position])); Count:=0; repeat inc(Count); inc(Position); until (Position>Len) or (AnsiChar(aPattern[Position])<>c); if Count>0 then begin if length(fDashes)<(CountSteps+1) then begin SetLength(fDashes,(CountSteps+1)*2); end; if c in [#0..#32] then begin fDashes[CountSteps]:=-Count; end else begin fDashes[CountSteps]:=Count; end; inc(CountSteps); end; end; end; if CountSteps>0 then begin if (CountSteps and 1)=1 then begin SetLength(fDashes,CountSteps*2); for Index:=0 to CountSteps-1 do begin fDashes[CountSteps+Index]:=fDashes[Index]*(-Sign(fDashes[(CountSteps+Index)-1])); end; inc(CountSteps,CountSteps); end; end; end; finally SetLength(fDashes,CountSteps); end; end; constructor TpvCanvasStrokePattern.Create(const aPattern:string;const aDashSize:TpvDouble); begin self:=TpvCanvasStrokePattern.Create(aPattern,aDashSize,0.0); end; constructor TpvCanvasStrokePattern.Create(const aPattern:string); begin self:=TpvCanvasStrokePattern.Create(aPattern,1.0,0.0); end; constructor TpvCanvasStrokePattern.Create(const aDashes:array of TpvDouble;const aDashSize,aStart:TpvDouble); begin SetLength(fDashes,length(aDashes)); if length(aDashes)>0 then begin Move(aDashes[0],fDashes[0],length(aDashes)*SizeOf(TpvDouble)); end; fDashSize:=aDashSize; fStart:=aStart; end; constructor TpvCanvasStrokePattern.Create(const aDashes:array of TpvDouble;const aDashSize:TpvDouble); begin self:=TpvCanvasStrokePattern.Create(aDashes,aDashSize,0.0); end; constructor TpvCanvasStrokePattern.Create(const aDashes:array of TpvDouble); begin self:=TpvCanvasStrokePattern.Create(aDashes,1.0,0.0); end; class operator TpvCanvasStrokePattern.Implicit(const aPattern:string):TpvCanvasStrokePattern; begin result:=TpvCanvasStrokePattern.Create(aPattern,1.0,0.0); end; class operator TpvCanvasStrokePattern.Explicit(const aPattern:string):TpvCanvasStrokePattern; begin result:=TpvCanvasStrokePattern.Create(aPattern,1.0,0.0); end; class operator TpvCanvasStrokePattern.Implicit(const aDashes:TpvCanvasStrokePatternDashes):TpvCanvasStrokePattern; begin result:=TpvCanvasStrokePattern.Create(aDashes,1.0,0.0); end; class operator TpvCanvasStrokePattern.Explicit(const aDashes:TpvCanvasStrokePatternDashes):TpvCanvasStrokePattern; begin result:=TpvCanvasStrokePattern.Create(aDashes,1.0,0.0); end; class function TpvCanvasStrokePattern.Empty:TpvCanvasStrokePattern; begin result.fDashes:=nil; result.fDashSize:=1.0; result.fStart:=0.0; end; constructor TpvCanvasPath.Create; begin inherited Create; fCommands:=nil; fCountCommands:=0; end; destructor TpvCanvasPath.Destroy; begin fCommands:=nil; inherited Destroy; end; procedure TpvCanvasPath.Assign(aSource:TPersistent); begin if assigned(aSource) and (aSource is TpvCanvasPath) then begin fCountCommands:=TpvCanvasPath(aSource).fCountCommands; if length(fCommands)<fCountCommands then begin SetLength(fCommands,fCountCommands*2); end; if fCountCommands>0 then begin Move(TpvCanvasPath(aSource).fCommands[0],fCommands[0],fCountCommands*SizeOf(TpvCanvasPathCommand)); end; end; end; function TpvCanvasPath.NewCommand:PpvCanvasPathCommand; var Index:TpvInt32; begin Index:=fCountCommands; inc(fCountCommands); if length(fCommands)<fCountCommands then begin SetLength(fCommands,fCountCommands*2); end; result:=@fCommands[Index]; end; function TpvCanvasPath.BeginPath:TpvCanvasPath; begin fCountCommands:=0; result:=self; end; function TpvCanvasPath.EndPath:TpvCanvasPath; begin fCountCommands:=0; result:=self; end; function TpvCanvasPath.ClosePath:TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.Close; result:=self; end; function TpvCanvasPath.MoveTo(const aP0:TpvVector2):TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.MoveTo; Command^.Points[0]:=aP0; result:=self; end; function TpvCanvasPath.LineTo(const aP0:TpvVector2):TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.LineTo; Command^.Points[0]:=aP0; result:=self; end; function TpvCanvasPath.QuadraticCurveTo(const aC0,aA0:TpvVector2):TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.QuadraticCurveTo; Command^.Points[0]:=aC0; Command^.Points[1]:=aA0; result:=self; end; function TpvCanvasPath.CubicCurveTo(const aC0,aC1,aA0:TpvVector2):TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.CubicCurveTo; Command^.Points[0]:=aC0; Command^.Points[1]:=aC1; Command^.Points[2]:=aA0; result:=self; end; function TpvCanvasPath.ArcTo(const aP0,aP1:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; var Command:PpvCanvasPathCommand; begin Command:=NewCommand; Command^.CommandType:=TpvCanvasPathCommandType.ArcTo; Command^.Points[0]:=aP0; Command^.Points[1]:=aP1; Command^.Points[2]:=TpvVector2.InlineableCreate(aRadius,aRadius); result:=self; end; function TpvCanvasPath.Arc(const aCenter:TpvVector2;const aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvasPath; var Direction,CountSubdivisions,SubdivisionIndex:TpvInt32; p0,d01,d21,Normal,Tangent,Current,Previous,PreviousTangent:TpvVector2; d,AngleDifference,PartAngleDifference,Kappa:TpvFloat; begin AngleDifference:=aAngle1-aAngle0; if aClockwise then begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=TwoPI; end else begin while AngleDifference<0.0 do begin AngleDifference:=AngleDifference+TwoPI; end; end; end else begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=-TwoPI; end else begin while AngleDifference>0.0 do begin AngleDifference:=AngleDifference-TwoPI; end; end; end; CountSubdivisions:=Min(Max(round(abs(AngleDifference)/HalfPI),1),5); PartAngleDifference:=AngleDifference/CountSubdivisions; Kappa:=abs((4.0/3.0)*(1.0-cos(PartAngleDifference))/sin(PartAngleDifference))*IfThen(not aClockwise,-1,1); Previous:=TpvVector2.Null; PreviousTangent:=TpvVector2.Null; for SubdivisionIndex:=0 to CountSubdivisions-1 do begin SinCos(Mix(aAngle0,aAngle1,SubdivisionIndex/CountSubdivisions),Normal.y,Normal.x); Current:=aCenter+(Normal*aRadius); Tangent:=TpvVector2.InlineableCreate(-Normal.y,Normal.x)*aRadius*Kappa; if SubdivisionIndex=0 then begin MoveTo(Current); end else begin CubicCurveTo(Previous+PreviousTangent,Current-Tangent,Current); end; Previous:=Current; PreviousTangent:=Tangent; end; result:=self; end; function TpvCanvasPath.Ellipse(const aCenter,aRadius:TpvVector2):TpvCanvasPath; const ARC_MAGIC=0.5522847498; // 4/3 * (1-cos 45°)/sin 45° = 4/3 * (sqrt(2) - 1) begin MoveTo(TpvVector2.InlineableCreate(aCenter.x+aRadius.x,aCenter.y)); CubicCurveTo(TpvVector2.InlineableCreate(aCenter.x+aRadius.x,aCenter.y-(aRadius.y*ARC_MAGIC)), TpvVector2.InlineableCreate(aCenter.x+(aRadius.x*ARC_MAGIC),aCenter.y-aRadius.y), TpvVector2.InlineableCreate(aCenter.x,aCenter.y-aRadius.y)); CubicCurveTo(TpvVector2.InlineableCreate(aCenter.x-(aRadius.x*ARC_MAGIC),aCenter.y-aRadius.y), TpvVector2.InlineableCreate(aCenter.x-aRadius.x,aCenter.y-(aRadius.y*ARC_MAGIC)), TpvVector2.InlineableCreate(aCenter.x-aRadius.x,aCenter.y)); CubicCurveTo(TpvVector2.InlineableCreate(aCenter.x-aRadius.x,aCenter.y+(aRadius.y*ARC_MAGIC)), TpvVector2.InlineableCreate(aCenter.x-(aRadius.x*ARC_MAGIC),aCenter.y+aRadius.y), TpvVector2.InlineableCreate(aCenter.x,aCenter.y+aRadius.y)); CubicCurveTo(TpvVector2.InlineableCreate(aCenter.x+(aRadius.x*ARC_MAGIC),aCenter.y+aRadius.y), TpvVector2.InlineableCreate(aCenter.x+aRadius.x,aCenter.y+(aRadius.y*ARC_MAGIC)), TpvVector2.InlineableCreate(aCenter.x+aRadius.x,aCenter.y)); ClosePath; result:=self; end; function TpvCanvasPath.Circle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; begin result:=Ellipse(aCenter,TpvVector2.InlineableCreate(aRadius,aRadius)); end; function TpvCanvasPath.Rectangle(const aCenter,aBounds:TpvVector2):TpvCanvasPath; begin MoveTo(TpvVector2.InlineableCreate(aCenter.x-aBounds.x,aCenter.y-aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x+aBounds.x,aCenter.y-aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x+aBounds.x,aCenter.y+aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x-aBounds.x,aCenter.y+aBounds.y)); ClosePath; result:=self; end; function TpvCanvasPath.RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvasPath; const ARC_MAGIC=0.5522847498; // 4/3 * (1-cos 45°)/sin 45° = 4/3 * (sqrt(2) - 1) var Offset,Size,TopLeft,TopRight,BottomLeft,BottomRight:TpvVector2; begin if IsZero(aRadiusTopLeft) and IsZero(aRadiusTopRight) and IsZero(aRadiusBottomLeft) and IsZero(aRadiusBottomRight) then begin MoveTo(TpvVector2.InlineableCreate(aCenter.x-aBounds.x,aCenter.y-aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x+aBounds.x,aCenter.y-aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x+aBounds.x,aCenter.y+aBounds.y)); LineTo(TpvVector2.InlineableCreate(aCenter.x-aBounds.x,aCenter.y+aBounds.y)); ClosePath; end else begin Offset:=aCenter-aBounds; Size:=aBounds*2.0; TopLeft:=TpvVector2.InlineableCreate(Min(ABounds.x,aRadiusTopLeft)*Sign(Size.x), Min(ABounds.y,aRadiusTopLeft)*Sign(Size.y)); TopRight:=TpvVector2.InlineableCreate(Min(ABounds.x,aRadiusTopRight)*Sign(Size.x), Min(ABounds.y,aRadiusTopRight)*Sign(Size.y)); BottomLeft:=TpvVector2.InlineableCreate(Min(ABounds.x,aRadiusBottomLeft)*Sign(Size.x), Min(ABounds.y,aRadiusBottomLeft)*Sign(Size.y)); BottomRight:=TpvVector2.InlineableCreate(Min(ABounds.x,aRadiusBottomRight)*Sign(Size.x), Min(ABounds.y,aRadiusBottomRight)*Sign(Size.y)); MoveTo(Offset+TpvVector2.InlineableCreate(0.0,TopLeft.y)); LineTo(Offset+TpvVector2.InlineableCreate(0.0,Size.y-BottomLeft.y)); CubicCurveTo(Offset+TpvVector2.InlineableCreate(0.0,Size.y-(BottomLeft.y*(1.0-ARC_MAGIC))), Offset+TpvVector2.InlineableCreate(BottomLeft.x*(1.0-ARC_MAGIC),Size.y), Offset+TpvVector2.InlineableCreate(BottomLeft.x,Size.y)); LineTo(Offset+TpvVector2.InlineableCreate(Size.x-BottomRight.x,Size.y)); CubicCurveTo(Offset+TpvVector2.InlineableCreate(Size.x-(BottomRight.x*(1.0-ARC_MAGIC)),Size.y), Offset+TpvVector2.InlineableCreate(Size.x,Size.y-(BottomRight.y*(1.0-ARC_MAGIC))), Offset+TpvVector2.InlineableCreate(Size.x,Size.y-BottomRight.y)); LineTo(Offset+TpvVector2.InlineableCreate(Size.x,TopRight.y)); CubicCurveTo(Offset+TpvVector2.InlineableCreate(Size.x,TopRight.y*(1.0-ARC_MAGIC)), Offset+TpvVector2.InlineableCreate(Size.x-(TopRight.x*(1.0-ARC_MAGIC)),0.0), Offset+TpvVector2.InlineableCreate(Size.x-TopRight.x,0.0)); LineTo(Offset+TpvVector2.InlineableCreate(TopLeft.y,0.0)); CubicCurveTo(Offset+TpvVector2.InlineableCreate(TopLeft.x*(1.0-ARC_MAGIC),0.0), Offset+TpvVector2.InlineableCreate(0.0,TopLeft.y*(1.0-ARC_MAGIC)), Offset+TpvVector2.InlineableCreate(0.0,TopLeft.y)); ClosePath; end; result:=self; end; function TpvCanvasPath.RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadius:TpvFloat):TpvCanvasPath; begin result:=RoundedRectangle(aCenter,aBounds,aRadius,aRadius,aRadius,aRadius); end; constructor TpvCanvasState.Create; begin inherited Create; fClipRect:=TpvRect.CreateAbsolute(-MaxSingle,-MaxSingle,MaxSingle,MaxSingle); fClipSpaceClipRect:=TpvRect.CreateAbsolute(-MaxSingle,-MaxSingle,MaxSingle,MaxSingle); fScissor:=TVkRect2D.Create(TVkOffset2D.Create(0,0),TVkExtent2D.Create($7fffffff,$7fffffff)); fProjectionMatrix:=TpvMatrix4x4.Identity; fPath:=TpvCanvasPath.Create; Reset; end; destructor TpvCanvasState.Destroy; begin FreeAndNil(fPath); inherited Destroy; end; procedure TpvCanvasState.UpdateClipSpaceClipRect(const aCanvas:TpvCanvas); const Add:TpvVector2=(x:-1.0;y:-1.0); var Mul:TpvVector2; begin Mul:=TpvVector2.InlineableCreate(2.0/aCanvas.fWidth,2.0/aCanvas.fHeight); fClipSpaceClipRect.Min:=(fClipRect.Min*Mul)+Add; fClipSpaceClipRect.Max:=(fClipRect.Max*Mul)+Add; end; function TpvCanvasState.GetColor:TpvVector4; begin result:=fColor; end; procedure TpvCanvasState.SetColor(const aColor:TpvVector4); begin fColor:=aColor; end; function TpvCanvasState.GetStartColor:TpvVector4; begin result:=fFillMatrix.Columns[2]; end; procedure TpvCanvasState.SetStartColor(const aColor:TpvVector4); begin fFillMatrix.Columns[2]:=aColor; end; function TpvCanvasState.GetStopColor:TpvVector4; begin result:=fFillMatrix.Columns[3]; end; procedure TpvCanvasState.SetStopColor(const aColor:TpvVector4); begin fFillMatrix.Columns[3]:=aColor; end; function TpvCanvasState.GetFillMatrix:TpvMatrix4x4; begin result.RawComponents[0,0]:=fFillMatrix.RawComponents[0,0]; result.RawComponents[0,1]:=fFillMatrix.RawComponents[0,1]; result.RawComponents[0,2]:=0.0; result.RawComponents[0,3]:=0.0; result.RawComponents[1,0]:=fFillMatrix.RawComponents[1,0]; result.RawComponents[1,1]:=fFillMatrix.RawComponents[1,1]; result.RawComponents[1,2]:=0.0; result.RawComponents[1,3]:=0.0; result.RawComponents[2,0]:=0.0; result.RawComponents[2,1]:=0-0; result.RawComponents[2,2]:=1.0; result.RawComponents[2,3]:=0.0; result.RawComponents[3,0]:=fFillMatrix.RawComponents[0,2]; result.RawComponents[3,1]:=fFillMatrix.RawComponents[1,2]; result.RawComponents[3,2]:=0.0; result.RawComponents[3,3]:=1.0; end; procedure TpvCanvasState.SetFillMatrix(const aMatrix:TpvMatrix4x4); begin fFillMatrix.RawComponents[0,0]:=aMatrix.RawComponents[0,0]; fFillMatrix.RawComponents[0,1]:=aMatrix.RawComponents[0,1]; fFillMatrix.RawComponents[1,0]:=aMatrix.RawComponents[1,0]; fFillMatrix.RawComponents[1,1]:=aMatrix.RawComponents[1,1]; fFillMatrix.RawComponents[0,2]:=aMatrix.RawComponents[3,0]; fFillMatrix.RawComponents[1,2]:=aMatrix.RawComponents[3,1]; end; procedure TpvCanvasState.Reset; begin fBlendingMode:=TpvCanvasBlendingMode.AlphaBlending; fZPosition:=0.0; fLineWidth:=1.0; fMiterLimit:=3.0; fLineJoin:=TpvCanvasLineJoin.Round; fLineCap:=TpvCanvasLineCap.Round; fFillRule:=TpvCanvasFillRule.EvenOdd; fFillStyle:=TpvCanvasFillStyle.Color; fFillWrapMode:=TpvCanvasFillWrapMode.None; fColor:=TpvVector4.InlineableCreate(1.0,1.0,1.0,1.0); fFont:=nil; fFontSize:=-12; fTextHorizontalAlignment:=TpvCanvasTextHorizontalAlignment.Leading; fTextVerticalAlignment:=TpvCanvasTextVerticalAlignment.Leading; fViewMatrix:=TpvMatrix4x4.Identity; fModelMatrix:=TpvMatrix4x4.Identity; fFillMatrix:=TpvMatrix4x4.Identity; fFillMatrix.Columns[2]:=fColor; fFillMatrix.Columns[3]:=fColor; fPath.fCountCommands:=0; fTexture:=nil; fAtlasTexture:=nil; fGUIElementMode:=false; fStrokePattern:=TpvCanvasStrokePattern.Empty; end; procedure TpvCanvasState.Assign(aSource:TPersistent); begin if assigned(aSource) and (aSource is TpvCanvasState) then begin fBlendingMode:=TpvCanvasState(aSource).fBlendingMode; fZPosition:=TpvCanvasState(aSource).fZPosition; fLineWidth:=TpvCanvasState(aSource).fLineWidth; fMiterLimit:=TpvCanvasState(aSource).fMiterLimit; fLineJoin:=TpvCanvasState(aSource).fLineJoin; fLineCap:=TpvCanvasState(aSource).fLineCap; fFillRule:=TpvCanvasState(aSource).fFillRule; fFillStyle:=TpvCanvasState(aSource).fFillStyle; fColor:=TpvCanvasState(aSource).fColor; fClipRect:=TpvCanvasState(aSource).fClipRect; fClipSpaceClipRect:=TpvCanvasState(aSource).fClipSpaceClipRect; fScissor:=TpvCanvasState(aSource).fScissor; fProjectionMatrix:=TpvCanvasState(aSource).fProjectionMatrix; fViewMatrix:=TpvCanvasState(aSource).fViewMatrix; fModelMatrix:=TpvCanvasState(aSource).fModelMatrix; fFillMatrix:=TpvCanvasState(aSource).fFillMatrix; fFont:=TpvCanvasState(aSource).fFont; fFontSize:=TpvCanvasState(aSource).fFontSize; fTextHorizontalAlignment:=TpvCanvasState(aSource).fTextHorizontalAlignment; fTextVerticalAlignment:=TpvCanvasState(aSource).fTextVerticalAlignment; fPath.Assign(TpvCanvasState(aSource).fPath); fTexture:=TpvCanvasState(aSource).fTexture; fAtlasTexture:=TpvCanvasState(aSource).fAtlasTexture; fGUIElementMode:=TpvCanvasState(aSource).fGUIElementMode; fStrokePattern:=TpvCanvasState(aSource).fStrokePattern; end; end; constructor TpvCanvasShape.Create; begin inherited Create; fCacheTemporaryLinePoints:=nil; fCacheLinePoints:=nil; fCacheSegments:=nil; fCacheSegmentUniquePoints:=nil; fCacheSegmentUniquePointHashTable:=nil; fCacheVertices:=nil; fCacheIndices:=nil; fCacheParts:=nil; fCacheYCoordinates:=nil; fCacheTemporaryYCoordinates:=nil; fCountCacheTemporaryLinePoints:=0; fCountCacheLinePoints:=0; fCountCacheSegments:=0; fCountCacheSegmentUniquePoints:=0; fCountCacheVertices:=0; fCountCacheIndices:=0; fCountCacheParts:=0; fCountCacheYCoordinates:=0; fForcedCurveTessellationTolerance:=-1.0; end; destructor TpvCanvasShape.Destroy; begin fCacheTemporaryLinePoints:=nil; fCacheLinePoints:=nil; fCacheSegments:=nil; fCacheSegmentUniquePoints:=nil; fCacheSegmentUniquePointHashTable:=nil; fCacheVertices:=nil; fCacheIndices:=nil; fCacheParts:=nil; fCacheYCoordinates:=nil; fCacheTemporaryYCoordinates:=nil; inherited Destroy; end; procedure TpvCanvasShape.BeginPart(const aCountVertices:TpvInt32=0;const aCountIndices:TpvInt32=0); var CachePart:PpvCanvasShapeCachePart; begin inc(fCountCacheParts); if length(fCacheParts)<fCountCacheParts then begin SetLength(fCacheParts,fCountCacheParts*2); end; CachePart:=@fCacheParts[fCountCacheParts-1]; CachePart^.BaseVertexIndex:=fCountCacheVertices; CachePart^.BaseIndexIndex:=fCountCacheIndices; CachePart^.CountVertices:=aCountVertices; CachePart^.CountIndices:=aCountIndices; end; procedure TpvCanvasShape.EndPart; var CachePart:PpvCanvasShapeCachePart; begin if fCountCacheParts>0 then begin CachePart:=@fCacheParts[fCountCacheParts-1]; CachePart^.CountVertices:=Max(0,fCountCacheVertices-CachePart^.BaseVertexIndex); CachePart^.CountIndices:=Max(0,fCountCacheIndices-CachePart^.BaseIndexIndex); if (CachePart^.CountVertices=0) and (CachePart^.CountIndices=0) then begin dec(fCountCacheParts); end; end; end; function TpvCanvasShape.AddVertex(const Position:TpvVector2;const ObjectMode:TpvUInt8;const MetaInfo:TpvVector4;const Offset:TpvVector2):TpvInt32; var CacheVertex:PpvCanvasShapeCacheVertex; begin result:=fCountCacheVertices; inc(fCountCacheVertices); if length(fCacheVertices)<fCountCacheVertices then begin SetLength(fCacheVertices,fCountCacheVertices*2); end; CacheVertex:=@fCacheVertices[result]; CacheVertex^.Position:=Position; CacheVertex^.ObjectMode:=ObjectMode; CacheVertex^.MetaInfo:=MetaInfo; CacheVertex^.Offset:=Offset; end; function TpvCanvasShape.AddIndex(const VertexIndex:TpvInt32):TpvInt32; begin result:=fCountCacheIndices; inc(fCountCacheIndices); if length(fCacheIndices)<fCountCacheIndices then begin SetLength(fCacheIndices,fCountCacheIndices*2); end; fCacheIndices[result]:=VertexIndex; end; function TpvCanvasShape.GetWindingNumberAtPointInPolygon(const Point:TpvVector2):TpvInt32; var Index,CaseIndex:TpvInt32; ShapeCacheSegment:PpvCanvasShapeCacheSegment; x0,y0,x1,y1:TpvFloat; begin result:=0; for Index:=0 to fCountCacheSegments-1 do begin ShapeCacheSegment:=@fCacheSegments[Index]; y0:=fCacheSegmentUniquePoints[ShapeCacheSegment^.Points[0]].Point.y-Point.y; y1:=fCacheSegmentUniquePoints[ShapeCacheSegment^.Points[1]].Point.y-Point.y; if y0<0.0 then begin CaseIndex:=0; end else if y0>0.0 then begin CaseIndex:=2; end else begin CaseIndex:=1; end; if y1<0.0 then begin inc(CaseIndex,0); end else if y1>0.0 then begin inc(CaseIndex,6); end else begin inc(CaseIndex,3); end; if CaseIndex in [1,2,3,6] then begin x0:=fCacheSegmentUniquePoints[ShapeCacheSegment^.Points[0]].Point.x-Point.x; x1:=fCacheSegmentUniquePoints[ShapeCacheSegment^.Points[1]].Point.x-Point.x; if not (((x0>0.0) and (x1>0.0)) or ((not ((x0<=0.0) and (x1<=0.0))) and ((x0-(y0*((x1-x0)/(y1-y0))))>0.0))) then begin if CaseIndex in [1,2] then begin inc(result); end else begin dec(result); end; end; end; end; end; procedure TpvCanvasShape.InitializeCurveTessellationTolerance(const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); var Scale,PixelRatio:TpvFloat; begin if fForcedCurveTessellationTolerance>0.0 then begin fCurveTessellationTolerance:=fForcedCurveTessellationTolerance; end else begin Scale:=((sqrt(sqr(aState.fModelMatrix.RawComponents[0,0])+sqr(aState.fModelMatrix.RawComponents[0,1]))+ sqrt(sqr(aState.fModelMatrix.RawComponents[1,0])+sqr(aState.fModelMatrix.RawComponents[1,1])))*0.5)* ((aState.fViewMatrix.Right.xyz.Length+aState.fViewMatrix.Up.xyz.Length)*0.5); if assigned(aCanvas) then begin Scale:=Scale* (((aState.fProjectionMatrix.Right.xyz.Length+aState.fProjectionMatrix.Up.xyz.Length)*0.5)/ ((1.0/aCanvas.fWidth)+(1.0/aCanvas.fHeight))); PixelRatio:=aCanvas.fWidth/aCanvas.fHeight; end else begin PixelRatio:=1.0; end; fCurveTessellationTolerance:=(0.5*Scale)/PixelRatio; end; fCurveTessellationToleranceSquared:=sqr(fCurveTessellationTolerance); end; procedure TpvCanvasShape.Reset; begin fCountCacheTemporaryLinePoints:=0; fCountCacheLinePoints:=0; fCountCacheSegments:=0; fCountCacheSegmentUniquePoints:=0; fCountCacheVertices:=0; fCountCacheIndices:=0; fCountCacheParts:=0; fCountCacheYCoordinates:=0; end; procedure TpvCanvasShape.StrokeFromPath(const aPath:TpvCanvasPath;const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); var StartPoint,LastPoint:TpvVector2; procedure StrokeAddPoint(const aP0:TpvVector2); var Index:TpvInt32; ShapeCacheLinePoint:PpvCanvasShapeCacheLinePoint; begin if (fCountCacheLinePoints=0) or (fCacheLinePoints[fCountCacheLinePoints-1].Position<>aP0) then begin Index:=fCountCacheLinePoints; inc(fCountCacheLinePoints); if length(fCacheLinePoints)<fCountCacheLinePoints then begin SetLength(fCacheLinePoints,fCountCacheLinePoints*2); end; ShapeCacheLinePoint:=@fCacheLinePoints[Index]; ShapeCacheLinePoint^.Position:=aP0; end; end; procedure ConvertStroke(var aLinePoints:TpvCanvasShapeCacheLinePoints;var aCountLinePoints:TpvInt32); var Closed:boolean; Width:TpvFloat; v0,v1,v2,v3:TpvVector2; First:boolean; procedure TriangulateSegment(const p0,p1,p2:TpvVector2;const LineJoin:TpvCanvasLineJoin;MiterLimit:TpvFloat;const IsFirst,IsLast:boolean); function LineIntersection(out p:TpvVector2;const v0,v1,v2,v3:TpvVector2):boolean; const EPSILON=1e-8; var a0,a1,b0,b1,c0,c1,Determinant:TpvFloat; begin a0:=v1.y-v0.y; b0:=v0.x-v1.x; a1:=v3.y-v2.y; b1:=v2.x-v3.x; Determinant:=(a0*b1)-(a1*b0); result:=abs(Determinant)>EPSILON; if result then begin c0:=(a0*v0.x)+(b0*v0.y); c1:=(a1*v2.x)+(b1*v2.y); p.x:=((b1*c0)-(b0*c1))/Determinant; p.y:=((a0*c1)-(a1*c0))/Determinant; end; end; function SignedArea(const v1,v2,v3:TpvVector2):TpvFloat; begin result:=((v2.x-v1.x)*(v3.y-v1.y))-((v3.x-v1.x)*(v2.y-v1.y)); end; procedure AddRoundJoin(const Center,p0,p1,NextPointInLine:TpvVector2); var iP0,iP1,iCenter,iP0Normal,iP1Normal:TPvInt32; Radius:TpvFloat; MetaInfo:TpvVector4; Normal:TpvVector2; begin // An arc inside three triangles Radius:=p0.DistanceTo(Center); MetaInfo:=TpvVector4.InlineableCreate(Center.x,Center.y,Radius,-1.0); Radius:=Radius+1.0; // Add some headroom to the radius Normal:=(Center-NextPointInLine).Normalize*Radius; BeginPart(5,9); iP0:=AddVertex(p0,pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null); iP1:=AddVertex(p1,pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null); iP0Normal:=AddVertex(p0+Normal,pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null); iP1Normal:=AddVertex(p1+Normal,pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null); iCenter:=AddVertex(Center,pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null); AddIndex(iP0Normal); AddIndex(iP0); AddIndex(iCenter); AddIndex(iCenter); AddIndex(iP1); AddIndex(iP1Normal); AddIndex(iP0Normal); AddIndex(iCenter); AddIndex(iP1Normal); EndPart; end; var CountVerticesToAdd,CountIndicesToAdd,LineJoinCase, ip0at0,ip0st0,ip1sAnchor,ip1at0,ip1st0,ip2at2,ip1st2,ip1at2,ip2st2,ip1,iIntersectionPoint,iCenter:TpvInt32; t0,t2,IntersectionPoint,Anchor,p0p1,p1p2:TpvVector2; AnchorLength,dd,p0p1Length,p1p2Length,l0,l2,s0,s2:TpvFloat; DoIntersect:boolean; begin t0:=(p1-p0).Perpendicular.Normalize*Width; t2:=(p2-p1).Perpendicular.Normalize*Width; if SignedArea(p0,p1,p2)>0.0 then begin t0:=-t0; t2:=-t2; end; DoIntersect:=LineIntersection(IntersectionPoint,p0+t0,p1+t0,p2+t2,p1+t2); if DoIntersect and not (IsFirst and IsLast) then begin Anchor:=IntersectionPoint-p1; AnchorLength:=Anchor.Length; dd:=AnchorLength/Width; end else begin Anchor:=TpvVector2.Null; AnchorLength:=3.4e+28; dd:=0.0; end; p0p1:=p0-p1; p1p2:=p1-p2; p0p1Length:=p0p1.Length; p1p2Length:=p1p2.Length; if First then begin v0:=p0+t0; v1:=p0-t0; end; v2:=p2-t2; v3:=p2+t2; if Closed or (aState.fLineCap<>TpvCanvasLineCap.Butt) then begin l0:=0.0; l2:=0.0; s0:=Width; s2:=Width; end else begin if IsFirst then begin l0:=p0.DistanceTo(p1); s0:=l0; end else begin l0:=0.0; s0:=Width; end; if IsLast then begin l2:=p1.DistanceTo(p2); s2:=l2; end else begin l2:=0.0; s2:=Width; end; end; if (AnchorLength>p0p1Length) or (AnchorLength>p1p2Length) then begin // The cross point exceeds any of the segments dimension. // Do not use cross point as reference. // This case deserves more attention to avoid redraw, currently works by overdrawing large parts. CountVerticesToAdd:=8; CountIndicesToAdd:=12; if LineJoin=TpvCanvasLineJoin.Round then begin LineJoinCase:=0; end else if (LineJoin=TpvCanvasLineJoin.Bevel) or ((LineJoin=TpvCanvasLineJoin.Miter) and (dd>=MiterLimit)) then begin LineJoinCase:=1; inc(CountVerticesToAdd,3); inc(CountIndicesToAdd,3); end else if (LineJoin=TpvCanvasLineJoin.Miter) and (dd<MiterLimit) and DoIntersect then begin LineJoinCase:=2; inc(CountVerticesToAdd,4); inc(CountIndicesToAdd,6); end else begin LineJoinCase:=3; end; BeginPart(CountVerticesToAdd,CountIndicesToAdd); begin ip0at0:=AddVertex(p0+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,l0,Width,s0),TpvVector2.Null); ip0st0:=AddVertex(p0-t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,l0,Width,s0),TpvVector2.Null); ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,s0),TpvVector2.Null); ip1st0:=AddVertex(p1-t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,s0),TpvVector2.Null); AddIndex(ip0at0); AddIndex(ip0st0); AddIndex(ip1at0); AddIndex(ip0st0); AddIndex(ip1at0); AddIndex(ip1st0); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,s2),TpvVector2.Null); ip2at2:=AddVertex(p2+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,l2,Width,s2),TpvVector2.Null); ip1st2:=AddVertex(p1-t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,s2),TpvVector2.Null); ip2st2:=AddVertex(p2-t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,l2,Width,s2),TpvVector2.Null); AddIndex(ip2at2); AddIndex(ip1st2); AddIndex(ip1at2); AddIndex(ip2at2); AddIndex(ip1st2); AddIndex(ip2st2); case LineJoinCase of 0:begin // Round join end; 1:begin // Bevel join ip1:=AddVertex(p1,pcvvaomLineEdge,TpvVector4.InlineableCreate(0.0,0.0,Width,Width),TpvVector2.Null); ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,Width,Width,Width),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,Width,Width,Width),TpvVector2.Null); AddIndex(ip1); AddIndex(ip1at0); AddIndex(ip1at2); end; 2:begin // Miter join ip1:=AddVertex(p1,pcvvaomLineEdge,TpvVector4.InlineableCreate(0.0,0.0,Width,Width),TpvVector2.Null); iIntersectionPoint:=AddVertex(IntersectionPoint,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); AddIndex(ip1at0); AddIndex(ip1); AddIndex(iIntersectionPoint); AddIndex(ip1at2); AddIndex(ip1); AddIndex(iIntersectionPoint); end; else begin // Nothing end; end; end; EndPart; if LineJoinCase=0 then begin // Round join AddRoundJoin(p1,p1+t0,p1+t2,p2); end; end else begin CountVerticesToAdd:=8; CountIndicesToAdd:=12; if LineJoin=TpvCanvasLineJoin.Round then begin LineJoinCase:=0; inc(CountVerticesToAdd,4); inc(CountIndicesToAdd,6); end else if (LineJoin=TpvCanvasLineJoin.Bevel) or ((LineJoin=TpvCanvasLineJoin.Miter) and (dd>=MiterLimit)) then begin LineJoinCase:=1; inc(CountVerticesToAdd,3); inc(CountIndicesToAdd,3); end else if (LineJoin=TpvCanvasLineJoin.Miter) and (dd<MiterLimit) and DoIntersect then begin LineJoinCase:=2; inc(CountVerticesToAdd,4); inc(CountIndicesToAdd,6); end else begin LineJoinCase:=3; end; BeginPart(CountVerticesToAdd,CountIndicesToAdd); begin ip0at0:=AddVertex(p0+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,l0,Width,s0),TpvVector2.Null); ip0st0:=AddVertex(p0-t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,l0,Width,s0),TpvVector2.Null); ip1sAnchor:=AddVertex(p1-Anchor,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,s0),TpvVector2.Null); ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,s0),TpvVector2.Null); AddIndex(ip0at0); AddIndex(ip0st0); AddIndex(ip1sAnchor); AddIndex(ip0at0); AddIndex(ip1sAnchor); AddIndex(ip1at0); ip1sAnchor:=AddVertex(p1-Anchor,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,s2),TpvVector2.Null); ip2at2:=AddVertex(p2+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,l2,Width,s2),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,s2),TpvVector2.Null); ip2st2:=AddVertex(p2-t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,l2,Width,s2),TpvVector2.Null); AddIndex(ip2at2); AddIndex(ip1sAnchor); AddIndex(ip1at2); AddIndex(ip2at2); AddIndex(ip1sAnchor); AddIndex(ip2st2); case LineJoinCase of 0:begin // Round join ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); ip1:=AddVertex(p1,pcvvaomLineEdge,TpvVector4.InlineableCreate(0.0,0.0,Width,Width),TpvVector2.Null); ip1sAnchor:=AddVertex(p1-Anchor,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,Width),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); AddIndex(ip1at0); AddIndex(ip1); AddIndex(ip1sAnchor); AddIndex(ip1); AddIndex(ip1at2); AddIndex(ip1sAnchor); end; 1:begin // Bevel join ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,Width,Width,Width),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,Width,Width,Width),TpvVector2.Null); ip1sAnchor:=AddVertex(p1-Anchor,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,Width),TpvVector2.Null); AddIndex(ip1at0); AddIndex(ip1at2); AddIndex(ip1sAnchor); end; 2:begin // Miter join ip1at0:=AddVertex(p1+t0,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); ip1at2:=AddVertex(p1+t2,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); iCenter:=AddVertex(p1-Anchor,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,Width),TpvVector2.Null); iIntersectionPoint:=AddVertex(IntersectionPoint,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); AddIndex(ip1at0); AddIndex(iCenter); AddIndex(iIntersectionPoint); AddIndex(iCenter); AddIndex(ip1at2); AddIndex(iIntersectionPoint); end; end; end; EndPart; if LineJoinCase=0 then begin // Round join AddRoundJoin(p1,p1+t0,p1+t2,p1-Anchor); end; end; First:=false; end; procedure AddSquareCap(const p0,p1,d:TpvVector2); var ip0,ip0d,ip1d,ip1:TpvInt32; begin BeginPart(4,6); ip0:=AddVertex(p0,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,0.0,Width,Width),TpvVector2.Null); ip0d:=AddVertex(p0+d,pcvvaomLineEdge,TpvVector4.InlineableCreate(-Width,Width,Width,Width),TpvVector2.Null); ip1d:=AddVertex(p1+d,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,Width,Width,Width),TpvVector2.Null); ip1:=AddVertex(p1,pcvvaomLineEdge,TpvVector4.InlineableCreate(Width,0.0,Width,Width),TpvVector2.Null); AddIndex(ip0); AddIndex(ip0d); AddIndex(ip1d); AddIndex(ip1); AddIndex(ip1d); AddIndex(ip0); EndPart; end; procedure AddRoundCap(const Center,p0,p1,NextPointInLine:TpvVector2); const Sqrt2=1.414213562373095; var Radius:TpvFloat; MetaInfo:TpvVector4; begin // An "inhalfcircle" inside an one single triangle Radius:=p0.DistanceTo(Center); MetaInfo:=TpvVector4.InlineableCreate(Center.x,Center.y,Radius,-1.0); Radius:=Radius+1.0; // Add some headroom to the radius BeginPart(3,3); AddIndex(AddVertex(Center+((p0-Center).Normalize*Radius*Sqrt2),pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null)); AddIndex(AddVertex(Center+((p1-Center).Normalize*Radius*Sqrt2),pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null)); AddIndex(AddVertex(Center+((Center-NextPointInLine).Normalize*Radius*Sqrt2),pcvvaomRoundLineCapCircle,MetaInfo,TpvVector2.Null)); EndPart; end; var i:TpvInt32; begin if aCountLinePoints>1 then begin for i:=aCountLinePoints-2 downto 0 do begin if aLinePoints[i].Position=aLinePoints[i+1].Position then begin dec(aCountLinePoints); Move(aLinePoints[i-1],aLinePoints[i],aCountLinePoints*SizeOf(TpvCanvasShapeCacheLinePoint)); end; end; if aCountLinePoints>1 then begin Width:=abs(aState.fLineWidth)*0.5; First:=true; if aCountLinePoints=2 then begin Closed:=false; TriangulateSegment(aLinePoints[0].Position, aLinePoints[0].Position.Lerp(aLinePoints[1].Position,0.5), aLinePoints[1].Position, TpvCanvasLineJoin.Bevel, aState.fMiterLimit, true, true); end else if aCountLinePoints>2 then begin Closed:=aLinePoints[0].Position.DistanceTo(aLinePoints[aCountLinePoints-1].Position)<EPSILON; if Closed then begin aLinePoints[0].Position:=(aLinePoints[0].Position+aLinePoints[1].Position)*0.5; inc(aCountLinePoints); if aCountLinePoints>length(aLinePoints) then begin SetLength(aLinePoints,aCountLinePoints*2); end; aLinePoints[aCountLinePoints-1]:=aLinePoints[0]; end; aLinePoints[0].Middle:=aLinePoints[0].Position; for i:=1 to aCountLinePoints-3 do begin aLinePoints[i].Middle:=(aLinePoints[i].Position+aLinePoints[i+1].Position)*0.5; end; aLinePoints[aCountLinePoints-2].Middle:=aLinePoints[aCountLinePoints-1].Position; for i:=1 to aCountLinePoints-2 do begin TriangulateSegment(aLinePoints[i-1].Middle, aLinePoints[i].Position, aLinePoints[i].Middle, aState.fLineJoin, aState.fMiterLimit, i=1, i=(aCountLinePoints-2)); end; end; if not Closed then begin case aState.fLineCap of TpvCanvasLineCap.Round:begin AddRoundCap(aLinePoints[0].Position,v0,v1,aLinePoints[1].Position); AddRoundCap(aLinePoints[aCountLinePoints-1].Position,v2,v3,aLinePoints[aCountLinePoints-2].Position); end; TpvCanvasLineCap.Square:begin AddSquareCap(v0, v1, (aLinePoints[0].Position-aLinePoints[1].Position).Normalize*aLinePoints[0].Position.DistanceTo(v0)); AddSquareCap(v2, v3, (aLinePoints[aCountLinePoints-1].Position-aLinePoints[aCountLinePoints-2].Position).Normalize*aLinePoints[aCountLinePoints-1].Position.DistanceTo(v3)); end; end; end; end; end; aCountLinePoints:=0; end; procedure StrokeFlush; procedure ConvertStrokeWithPattern; procedure AddLinePoint(const aP0:TpvVector2); var Index:TpvInt32; ShapeCacheTemporaryLinePoint:PpvCanvasShapeCacheLinePoint; begin if (fCountCacheTemporaryLinePoints=0) or (fCacheTemporaryLinePoints[fCountCacheTemporaryLinePoints-1].Position<>aP0) then begin Index:=fCountCacheTemporaryLinePoints; inc(fCountCacheTemporaryLinePoints); if length(fCacheTemporaryLinePoints)<fCountCacheTemporaryLinePoints then begin SetLength(fCacheTemporaryLinePoints,fCountCacheTemporaryLinePoints*2); end; ShapeCacheTemporaryLinePoint:=@fCacheTemporaryLinePoints[Index]; ShapeCacheTemporaryLinePoint^.Position:=aP0; end; end; var DashIndex,PointIndex:TpvInt32; IsInLine:boolean; LineRemain,LineLen,DashRemain,StartRemain,StepLength,Distance:TpvDouble; p0,p1,CurrentPosition:TpvVector2; begin IsInLine:=false; fCountCacheTemporaryLinePoints:=0; LineRemain:=0; LineLen:=0; p0:=TpvVector2.Null; p1:=TpvVector2.Null; DashIndex:=0; DashRemain:=abs(aState.fStrokePattern.fDashes[DashIndex]*aState.fStrokePattern.fDashSize); StartRemain:=aState.fStrokePattern.fStart; while StartRemain>0.0 do begin StepLength:=Min(DashRemain,StartRemain); if IsZero(StepLength) then begin break; end else begin StartRemain:=StartRemain-StepLength; DashRemain:=DashRemain-StepLength; if DashRemain<=0 then begin inc(DashIndex); if DashIndex>=length(aState.fStrokePattern.fDashes) then begin DashIndex:=0; end; DashRemain:=abs(aState.fStrokePattern.fDashes[DashIndex]*aState.fStrokePattern.fDashSize); end; end; end; for PointIndex:=0 to fCountCacheLinePoints-2 do begin p0:=fCacheLinePoints[PointIndex].Position; p1:=fCacheLinePoints[PointIndex+1].Position; LineLen:=p0.DistanceTo(p1); LineRemain:=LineLen; while LineRemain>0 do begin StepLength:=Min(DashRemain,LineRemain); if IsZero(StepLength) then begin break; end else begin Distance:=(LineLen-LineRemain)/LineLen; CurrentPosition:=p0.Lerp(p1,Distance); if (aState.fStrokePattern.fDashes[DashIndex]*aState.fStrokePattern.fDashSize)>0.0 then begin IsInLine:=true; AddLinePoint(CurrentPosition); end else begin if IsInLine then begin IsInLine:=false; AddLinePoint(CurrentPosition); ConvertStroke(fCacheTemporaryLinePoints,fCountCacheTemporaryLinePoints); fCountCacheTemporaryLinePoints:=0; end; end; LineRemain:=LineRemain-StepLength; DashRemain:=DashRemain-StepLength; if DashRemain<=0 then begin inc(DashIndex); if DashIndex>=length(aState.fStrokePattern.fDashes) then begin DashIndex:=0; end; DashRemain:=abs(aState.fStrokePattern.fDashes[DashIndex]*aState.fStrokePattern.fDashSize); end; end; end; end; if IsInLine and not IsZero(LineLen) then begin AddLinePoint(p0.Lerp(p1,(LineLen-LineRemain)/LineLen)); ConvertStroke(fCacheTemporaryLinePoints,fCountCacheTemporaryLinePoints); fCountCacheTemporaryLinePoints:=0; end; end; begin if fCountCacheLinePoints>0 then begin if (length(aState.fStrokePattern.fDashes)>0) and (aState.fStrokePattern.fDashSize>0.0) then begin ConvertStrokeWithPattern; end else begin ConvertStroke(fCacheLinePoints,fCountCacheLinePoints); end; end; fCountCacheLinePoints:=0; end; procedure StrokeMoveTo(const aP0:TpvVector2); begin StrokeFlush; StrokeAddPoint(aP0); StartPoint:=aP0; LastPoint:=aP0; end; procedure StrokeLineTo(const aP0:TpvVector2); begin StrokeAddPoint(aP0); LastPoint:=aP0; end; procedure StrokeQuadraticCurveTo(const aC0,aA0:TpvVector2); procedure Recursive(const x1,y1,x2,y2,x3,y3:TpvFloat;const Level:TpvInt32); var x12,y12,x23,y23,x123,y123,dx,dy:TpvFloat; Point:TpvVector2; begin x12:=(x1+x2)*0.5; y12:=(y1+y2)*0.5; x23:=(x2+x3)*0.5; y23:=(y2+y3)*0.5; x123:=(x12+x23)*0.5; y123:=(y12+y23)*0.5; dx:=x3-x1; dy:=y3-y1; if (Level>CurveRecursionLimit) or ((Level>0) and (sqr(((x2-x3)*dy)-((y2-y3)*dx))<((sqr(dx)+sqr(dy))*fCurveTessellationToleranceSquared))) then begin Point.x:=x3; Point.y:=y3; StrokeLineTo(Point); end else begin Recursive(x1,y1,x12,y12,x123,y123,level+1); Recursive(x123,y123,x23,y23,x3,y3,level+1); end; end; begin Recursive(LastPoint.x,LastPoint.y,aC0.x,aC0.y,aA0.x,aA0.y,0); StrokeLineTo(aA0); end; procedure StrokeCubicCurveTo(const aC0,aC1,aA0:TpvVector2); procedure Recursive(const x1,y1,x2,y2,x3,y3,x4,y4:TpvDouble;const Level:TpvInt32); var x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234,dx,dy:TpvDouble; Point:TpvVector2; begin x12:=(x1+x2)*0.5; y12:=(y1+y2)*0.5; x23:=(x2+x3)*0.5; y23:=(y2+y3)*0.5; x34:=(x3+x4)*0.5; y34:=(y3+y4)*0.5; x123:=(x12+x23)*0.5; y123:=(y12+y23)*0.5; x234:=(x23+x34)*0.5; y234:=(y23+y34)*0.5; x1234:=(x123+x234)*0.5; y1234:=(y123+y234)*0.5; dx:=x4-x1; dy:=y4-y1; if (Level>CurveRecursionLimit) or ((Level>0) and (sqr(abs(((x2-x4)*dy)-((y2-y4)*dx))+ abs(((x3-x4)*dy)-((y3-y4)*dx)))<((sqr(dx)+sqr(dy))*fCurveTessellationToleranceSquared))) then begin Point.x:=x4; Point.y:=y4; StrokeLineTo(Point); end else begin Recursive(x1,y1,x12,y12,x123,y123,x1234,y1234,Level+1); Recursive(x1234,y1234,x234,y234,x34,y34,x4,y4,Level+1); end; end; begin Recursive(LastPoint.x,LastPoint.y,aC0.x,aC0.y,aC1.x,aC1.y,aA0.x,aA0.y,0); StrokeLineTo(aA0); end; procedure StrokeArcTo(const aP1,aP2:TpvVector2;const aRadius:TpvFloat); const CCW=0; CW=1; var Direction,CountSubdivisions,SubdivisionIndex:TpvInt32; p0,d01,d21,Center,Normal,Tangent,Current,Previous,PreviousTangent:TpvVector2; d,Angle0,Angle1,AngleDifference,PartAngleDifference,Kappa:TpvFloat; begin if (aP1=aP2) or IsZero(aRadius) then begin StrokeLineTo(aP1); end else begin p0:=LastPoint; d01:=(p0-aP1).Normalize; d21:=(aP2-aP1).Normalize; d:=aRadius/tan(ArcCos(d01.Dot(d21))*0.5); if d>1e+4 then begin StrokeLineTo(aP1); end else begin if ((d01.y*d21.x)-(d01.x*d21.y))>0.0 then begin Center:=aP1+TpvVector2.InlineableCreate((d01.x*d)+(d01.y*aRadius),(d01.y*d)-(d01.x*aRadius)); Angle0:=ArcTan2(d01.x,-d01.y); Angle1:=ArcTan2(-d21.x,d21.y); Direction:=CW; end else begin Center:=aP1+TpvVector2.InlineableCreate((d01.x*d)-(d01.y*aRadius),(d01.y*d)+(d01.x*aRadius)); Angle0:=ArcTan2(-d01.x,d01.y); Angle1:=ArcTan2(d21.x,-d21.y); Direction:=CCW; end; AngleDifference:=Angle1-Angle0; if Direction=CW then begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=TwoPI; end else begin while AngleDifference<0.0 do begin AngleDifference:=AngleDifference+TwoPI; end; end; end else begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=-TwoPI; end else begin while AngleDifference>0.0 do begin AngleDifference:=AngleDifference-TwoPI; end; end; end; CountSubdivisions:=Min(Max(round(abs(AngleDifference)/HalfPI),1),5); PartAngleDifference:=AngleDifference/CountSubdivisions; Kappa:=abs((4.0/3.0)*(1.0-cos(PartAngleDifference))/sin(PartAngleDifference))*IfThen(Direction=CCW,-1,1); Previous:=TpvVector2.Null; PreviousTangent:=TpvVector2.Null; for SubdivisionIndex:=0 to CountSubdivisions-1 do begin SinCos(Mix(Angle0,Angle1,SubdivisionIndex/CountSubdivisions),Normal.y,Normal.x); Current:=Center+(Normal*aRadius); Tangent:=TpvVector2.InlineableCreate(-Normal.y,Normal.x)*aRadius*Kappa; if SubdivisionIndex=0 then begin StrokeLineTo(Current); end else begin StrokeCubicCurveTo(Previous+PreviousTangent,Current-Tangent,Current); end; Previous:=Current; PreviousTangent:=Tangent; end; end; end; end; procedure StrokeClose; begin if fCountCacheLinePoints>0 then begin StrokeLineTo(StartPoint); StrokeFlush; end; end; var CommandIndex:TpvInt32; Command:PpvCanvasPathCommand; begin Reset; InitializeCurveTessellationTolerance(aState,aCanvas); for CommandIndex:=0 to aPath.fCountCommands-1 do begin Command:=@aPath.fCommands[CommandIndex]; case Command^.CommandType of TpvCanvasPathCommandType.MoveTo:begin StrokeMoveTo(Command.Points[0]); end; TpvCanvasPathCommandType.LineTo:begin StrokeLineTo(Command.Points[0]); end; TpvCanvasPathCommandType.QuadraticCurveTo:begin StrokeQuadraticCurveTo(Command.Points[0],Command.Points[1]); end; TpvCanvasPathCommandType.CubicCurveTo:begin StrokeCubicCurveTo(Command.Points[0],Command.Points[1],Command.Points[2]); end; TpvCanvasPathCommandType.ArcTo:begin StrokeArcTo(Command.Points[0],Command.Points[1],Command.Points[2].x); end; TpvCanvasPathCommandType.Close:begin StrokeClose; end; end; end; StrokeFlush; end; function TpvCanvasShapeCacheYCoordinateCompare(const a,b:TpvCanvasShapeCacheSegmentScalar):TpvInt32; begin result:=Sign(a-b); end; procedure TpvCanvasShape.FillFromPath(const aPath:TpvCanvasPath;const aState:TpvCanvasState;const aCanvas:TpvCanvas=nil); var CommandIndex,LastLinePoint:TpvInt32; Command:PpvCanvasPathCommand; StartPoint,LastPoint:TpvVector2; procedure InitializeSegmentUniquePointHashTable; begin if length(fCacheSegmentUniquePointHashTable)<pvCanvasShapeCacheSegmentUniquePointHashSize then begin SetLength(fCacheSegmentUniquePointHashTable,pvCanvasShapeCacheSegmentUniquePointHashSize); end; FillChar(fCacheSegmentUniquePointHashTable[0],pvCanvasShapeCacheSegmentUniquePointHashSize*SizeOf(TpvInt32),$ff); fCountCacheSegmentUniquePoints:=0; end; function GetSegmentPointHash(const aPoint:TpvCanvasShapeCacheSegmentPoint):TpvUInt32; begin result:=trunc(floor((aPoint.x*256)+0.5)*73856093) xor trunc(floor((aPoint.y*256)+0.5)*19349653); end; function AddSegmentPoint(const aPoint:TpvCanvasShapeCacheSegmentPoint):TpvInt32; overload; var Hash,HashBucket:TpvUInt32; UniquePoint:PpvCanvasShapeCacheSegmentUniquePoint; begin Hash:=GetSegmentPointHash(aPoint); HashBucket:=Hash and pvCanvasShapeCacheSegmentUniquePointHashMask; result:=fCacheSegmentUniquePointHashTable[HashBucket]; while result>=0 do begin UniquePoint:=@fCacheSegmentUniquePoints[result]; if (UniquePoint^.Hash=Hash) and SameValue(UniquePoint^.Point.x,aPoint.x) and SameValue(UniquePoint^.Point.y,aPoint.y) then begin break; end else begin result:=UniquePoint^.HashNext; end; end; if result<0 then begin result:=fCountCacheSegmentUniquePoints; inc(fCountCacheSegmentUniquePoints); if length(fCacheSegmentUniquePoints)<fCountCacheSegmentUniquePoints then begin SetLength(fCacheSegmentUniquePoints,fCountCacheSegmentUniquePoints*2); end; UniquePoint:=@fCacheSegmentUniquePoints[result]; UniquePoint^.HashNext:=fCacheSegmentUniquePointHashTable[HashBucket]; fCacheSegmentUniquePointHashTable[HashBucket]:=result; UniquePoint^.Hash:=Hash; UniquePoint^.Point:=aPoint; end; end; function AddSegmentPoint(const aPoint:TpvVector2):TpvInt32; overload; var p:TpvCanvasShapeCacheSegmentPoint; begin p.x:=aPoint.x; p.y:=aPoint.y; result:=AddSegmentPoint(p); end; procedure UpdateSegmentBoundingBox(var Segment:TpvCanvasShapeCacheSegment); var p0,p1:PpvCanvasShapeCacheSegmentPoint; begin p0:=@fCacheSegmentUniquePoints[Segment.Points[0]].Point; p1:=@fCacheSegmentUniquePoints[Segment.Points[1]].Point; Segment.AABBMin.x:=Min(p0^.x,p1^.x); Segment.AABBMin.y:=Min(p0^.y,p1^.y); Segment.AABBMax.x:=Max(p0^.x,p1^.x); Segment.AABBMax.y:=Max(p0^.y,p1^.y); end; procedure AddSegment(const aP0,aP1:TpvInt32); overload; var Index:TpvInt32; ShapeCacheSegment:PpvCanvasShapeCacheSegment; begin if aP0<>aP1 then begin Index:=fCountCacheSegments; inc(fCountCacheSegments); if length(fCacheSegments)<fCountCacheSegments then begin SetLength(fCacheSegments,fCountCacheSegments*2); end; ShapeCacheSegment:=@fCacheSegments[Index]; ShapeCacheSegment^.Points[0]:=aP0; ShapeCacheSegment^.Points[1]:=aP1; UpdateSegmentBoundingBox(ShapeCacheSegment^); if fCacheFirstSegment<0 then begin fCacheFirstSegment:=Index; ShapeCacheSegment^.Previous:=-1; end else begin fCacheSegments[fCacheLastSegment].Next:=Index; ShapeCacheSegment^.Previous:=fCacheLastSegment; end; ShapeCacheSegment^.Next:=-1; fCacheLastSegment:=Index; end; end; procedure AddSegment(const aP0,aP1:TpvCanvasShapeCacheSegmentPoint); overload; begin if (aP0.x<>aP1.x) or (aP0.y<>aP1.y) then begin AddSegment(AddSegmentPoint(aP0),AddSegmentPoint(aP1)); end; end; procedure RemoveSegment(const aSegmentIndex:TpvInt32); var PreviousSegmentIndex,NextSegmentIndex:TpvInt32; begin PreviousSegmentIndex:=fCacheSegments[aSegmentIndex].Previous; NextSegmentIndex:=fCacheSegments[aSegmentIndex].Next; if PreviousSegmentIndex>=0 then begin fCacheSegments[PreviousSegmentIndex].Next:=NextSegmentIndex; end else if fCacheFirstSegment=aSegmentIndex then begin fCacheFirstSegment:=NextSegmentIndex; end; if NextSegmentIndex>=0 then begin fCacheSegments[NextSegmentIndex].Previous:=PreviousSegmentIndex; end else if fCacheLastSegment=aSegmentIndex then begin fCacheLastSegment:=PreviousSegmentIndex; end; fCacheSegments[aSegmentIndex].Previous:=-1; fCacheSegments[aSegmentIndex].Next:=-1; end; procedure FillMoveTo(const aP0:TpvVector2); var Index:TpvInt32; LinePoint:PpvCanvasShapeCacheLinePoint; begin Index:=fCountCacheLinePoints; inc(fCountCacheLinePoints); if length(fCacheLinePoints)<fCountCacheLinePoints then begin SetLength(fCacheLinePoints,fCountCacheLinePoints*2); end; LinePoint:=@fCacheLinePoints[Index]; LinePoint^.Last:=-1; LinePoint^.Position:=aP0; LastLinePoint:=Index; StartPoint:=aP0; LastPoint:=aP0; end; procedure FillLineTo(const aP0:TpvVector2); var Index:TpvInt32; LinePoint:PpvCanvasShapeCacheLinePoint; begin if LastPoint<>aP0 then begin Index:=fCountCacheLinePoints; inc(fCountCacheLinePoints); if length(fCacheLinePoints)<fCountCacheLinePoints then begin SetLength(fCacheLinePoints,fCountCacheLinePoints*2); end; LinePoint:=@fCacheLinePoints[Index]; LinePoint^.Last:=LastLinePoint; LinePoint^.Position:=aP0; LastLinePoint:=Index; AddSegment(AddSegmentPoint(LastPoint),AddSegmentPoint(aP0)); end; LastPoint:=aP0; end; procedure FillQuadraticCurveTo(const aC0,aA0:TpvVector2); procedure Recursive(const x1,y1,x2,y2,x3,y3:TpvFloat;const Level:TpvInt32); var x12,y12,x23,y23,x123,y123,dx,dy:TpvFloat; Point:TpvVector2; begin x12:=(x1+x2)*0.5; y12:=(y1+y2)*0.5; x23:=(x2+x3)*0.5; y23:=(y2+y3)*0.5; x123:=(x12+x23)*0.5; y123:=(y12+y23)*0.5; dx:=x3-x1; dy:=y3-y1; if (Level>CurveRecursionLimit) or ((Level>0) and (sqr(((x2-x3)*dy)-((y2-y3)*dx))<((sqr(dx)+sqr(dy))*fCurveTessellationToleranceSquared))) then begin Point.x:=x123; Point.y:=y123; FillLineTo(Point); end else begin Recursive(x1,y1,x12,y12,x123,y123,level+1); Recursive(x123,y123,x23,y23,x3,y3,level+1); end; end; begin Recursive(LastPoint.x,LastPoint.y,aC0.x,aC0.y,aA0.x,aA0.y,0); FillLineTo(aA0); end; procedure FillCubicCurveTo(const aC0,aC1,aA0:TpvVector2); procedure Recursive(const x1,y1,x2,y2,x3,y3,x4,y4:TpvDouble;const Level:TpvInt32); var x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234,dx,dy:TpvDouble; Point:TpvVector2; begin x12:=(x1+x2)*0.5; y12:=(y1+y2)*0.5; x23:=(x2+x3)*0.5; y23:=(y2+y3)*0.5; x34:=(x3+x4)*0.5; y34:=(y3+y4)*0.5; x123:=(x12+x23)*0.5; y123:=(y12+y23)*0.5; x234:=(x23+x34)*0.5; y234:=(y23+y34)*0.5; x1234:=(x123+x234)*0.5; y1234:=(y123+y234)*0.5; dx:=x4-x1; dy:=y4-y1; if (Level>CurveRecursionLimit) or ((Level>0) and (sqr(abs(((x2-x4)*dy)-((y2-y4)*dx))+ abs(((x3-x4)*dy)-((y3-y4)*dx)))<((sqr(dx)+sqr(dy))*fCurveTessellationToleranceSquared))) then begin Point.x:=x4; Point.y:=y4; FillLineTo(Point); end else begin Recursive(x1,y1,x12,y12,x123,y123,x1234,y1234,Level+1); Recursive(x1234,y1234,x234,y234,x34,y34,x4,y4,Level+1); end; end; begin Recursive(LastPoint.x,LastPoint.y,aC0.x,aC0.y,aC1.x,aC1.y,aA0.x,aA0.y,0); FillLineTo(aA0); end; procedure FillArcTo(const aP1,aP2:TpvVector2;const aRadius:TpvFloat); const CCW=0; CW=1; var Direction,CountSubdivisions,SubdivisionIndex:TpvInt32; p0,d01,d21,Center,Normal,Tangent,Current,Previous,PreviousTangent:TpvVector2; d,Angle0,Angle1,AngleDifference,PartAngleDifference,Kappa:TpvFloat; begin if (aP1=aP2) or IsZero(aRadius) then begin FillLineTo(aP1); end else begin p0:=LastPoint; d01:=(p0-aP1).Normalize; d21:=(aP2-aP1).Normalize; d:=aRadius/tan(ArcCos(d01.Dot(d21))*0.5); if d>1e+4 then begin FillLineTo(aP1); end else begin if ((d01.y*d21.x)-(d01.x*d21.y))>0.0 then begin Center:=aP1+TpvVector2.InlineableCreate((d01.x*d)+(d01.y*aRadius),(d01.y*d)-(d01.x*aRadius)); Angle0:=ArcTan2(d01.x,-d01.y); Angle1:=ArcTan2(-d21.x,d21.y); Direction:=CW; end else begin Center:=aP1+TpvVector2.InlineableCreate((d01.x*d)-(d01.y*aRadius),(d01.y*d)+(d01.x*aRadius)); Angle0:=ArcTan2(-d01.x,d01.y); Angle1:=ArcTan2(d21.x,-d21.y); Direction:=CCW; end; AngleDifference:=Angle1-Angle0; if Direction=CW then begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=TwoPI; end else begin while AngleDifference<0.0 do begin AngleDifference:=AngleDifference+TwoPI; end; end; end else begin if abs(AngleDifference)>=TwoPI then begin AngleDifference:=-TwoPI; end else begin while AngleDifference>0.0 do begin AngleDifference:=AngleDifference-TwoPI; end; end; end; CountSubdivisions:=Min(Max(round(abs(AngleDifference)/HalfPI),1),5); PartAngleDifference:=AngleDifference/CountSubdivisions; Kappa:=abs((4.0/3.0)*(1.0-cos(PartAngleDifference))/sin(PartAngleDifference))*IfThen(Direction=CCW,-1,1); Previous:=TpvVector2.Null; PreviousTangent:=TpvVector2.Null; for SubdivisionIndex:=0 to CountSubdivisions-1 do begin SinCos(Mix(Angle0,Angle1,SubdivisionIndex/CountSubdivisions),Normal.y,Normal.x); Current:=Center+(Normal*aRadius); Tangent:=TpvVector2.InlineableCreate(-Normal.y,Normal.x)*aRadius*Kappa; if SubdivisionIndex=0 then begin FillLineTo(Current); end else begin FillCubicCurveTo(Previous+PreviousTangent,Current-Tangent,Current); end; Previous:=Current; PreviousTangent:=Tangent; end; end; end; end; procedure FillClose; begin if (fCountCacheLinePoints>0) or (fCountCacheSegments>0) then begin FillLineTo(StartPoint); end; end; procedure FillFlush; procedure SortLinkedListSegments; function CompareSegments(const a,b:TpvCanvasShapeCacheSegment):TpvInt32; begin result:=Sign(a.AABBMin.y-b.AABBMin.y); if result=0 then begin result:=Sign(a.AABBMin.x-b.AABBMin.x); if result=0 then begin result:=Sign(a.AABBMax.x-b.AABBMax.x); if result=0 then begin result:=Sign(a.AABBMax.y-b.AABBMax.y); end; end; end; end; var PartA,PartB,CurrentSegment,InSize,PartASize,PartBSize,Merges:TpvInt32; begin // Sort for from top to bottom and from left to right if fCacheFirstSegment>=0 then begin InSize:=1; repeat PartA:=fCacheFirstSegment; fCacheFirstSegment:=-1; fCacheLastSegment:=-1; Merges:=0; while PartA>=0 do begin inc(Merges); PartB:=PartA; PartASize:=0; while PartASize<InSize do begin inc(PartASize); PartB:=fCacheSegments[PartB].Next; if PartB<0 then begin break; end; end; PartBSize:=InSize; while (PartASize>0) or ((PartBSize>0) and (PartB>=0)) do begin if (PartASize<>0) and ((PartBSize=0) or (PartB<0) or (CompareSegments(fCacheSegments[PartA],fCacheSegments[PartB])<=0)) then begin CurrentSegment:=PartA; PartA:=fCacheSegments[PartA].Next; dec(PartASize); end else begin CurrentSegment:=PartB; PartB:=fCacheSegments[PartB].Next; dec(PartBSize); end; if fCacheLastSegment>=0 then begin fCacheSegments[fCacheLastSegment].Next:=CurrentSegment; end else begin fCacheFirstSegment:=CurrentSegment; end; fCacheSegments[CurrentSegment].Previous:=fCacheLastSegment; fCacheLastSegment:=CurrentSegment; end; PartA:=PartB; end; fCacheSegments[fCacheLastSegment].Next:=-1; if Merges<=1 then begin break; end; inc(InSize,InSize); until false; end; end; procedure SweepAndSplitSegmentsAtIntersections; const EPSILON=1e-8; InvEPSILON=1.0-EPSILON; Threshold=1e-4; var UntilIncludingSegmentIndex,SegmentAIndex,SegmentBIndex,TryIndex,Intersections, IntersectionPointIndex:TpvInt32; SegmentA,SegmentB:PpvCanvasShapeCacheSegment; IntersectionPoint:TpvCanvasShapeCacheSegmentPoint; TryAgain:boolean; a0,a1,b0,b1:PpvCanvasShapeCacheSegmentPoint; a10x,a10y,b10x,b10y,ab0x,ab0y,Determinant,ai,bi,aiInv:TpvCanvasShapeCacheSegmentScalar; begin repeat TryAgain:=false; UntilIncludingSegmentIndex:=fCacheLastSegment; SegmentAIndex:=fCacheFirstSegment; while SegmentAIndex>=0 do begin SegmentBIndex:=fCacheSegments[SegmentAIndex].Next; while SegmentBIndex>=0 do begin SegmentA:=@fCacheSegments[SegmentAIndex]; SegmentB:=@fCacheSegments[SegmentBIndex]; if SegmentB^.AABBMin.y<=SegmentA^.AABBMax.y then begin if (SegmentA^.AABBMin.x<=SegmentB^.AABBMax.x) and (SegmentB^.AABBMin.x<=SegmentA^.AABBMax.x) then begin Intersections:=0; a0:=@fCacheSegmentUniquePoints[SegmentA^.Points[0]].Point; a1:=@fCacheSegmentUniquePoints[SegmentA^.Points[1]].Point; b0:=@fCacheSegmentUniquePoints[SegmentB^.Points[0]].Point; b1:=@fCacheSegmentUniquePoints[SegmentB^.Points[1]].Point; a10x:=a1^.x-a0^.x; a10y:=a1^.y-a0^.y; b10x:=b1^.x-b0^.x; b10y:=b1^.y-b0^.y; Determinant:=(a10x*b10y)-(b10x*a10y); if not IsZero(Determinant) then begin ab0x:=a0^.x-b0^.x; ab0y:=a0^.y-b0^.y; ai:=((b10x*ab0y)-(b10y*ab0x))/Determinant; if (ai>=0.0) and (ai<=1.0) then begin bi:=((a10x*ab0y)-(a10y*ab0x))/Determinant; if (bi>=0.0) and (bi<=1.0) then begin aiInv:=1.0-ai; IntersectionPoint.x:=(a0^.x*aiInv)+(a1^.x*ai); IntersectionPoint.y:=(a0^.y*aiInv)+(a1^.y*ai); if ((ai>EPSILON) and (ai<InvEPSILON)) and not ((SameValue(ai,0.0) or SameValue(ai,1.0)) or (SameValue(IntersectionPoint.x,a0^.x) and SameValue(IntersectionPoint.y,a0^.y)) or (SameValue(IntersectionPoint.x,a1^.x) and SameValue(IntersectionPoint.y,a1^.y))) then begin Intersections:=Intersections or 1; end; if ((bi>EPSILON) and (bi<InvEPSILON)) and not ((SameValue(bi,0.0) or SameValue(bi,1.0)) or (SameValue(IntersectionPoint.x,b0^.x) and SameValue(IntersectionPoint.y,b0^.y)) or (SameValue(IntersectionPoint.x,b1^.x) and SameValue(IntersectionPoint.y,b1^.y))) then begin Intersections:=Intersections or 2; end; end; end; end; if (Intersections and (1 or 2))<>0 then begin IntersectionPointIndex:=AddSegmentPoint(IntersectionPoint); if (Intersections and 1)<>0 then begin AddSegment(IntersectionPointIndex,fCacheSegments[SegmentAIndex].Points[1]); fCacheSegments[SegmentAIndex].Points[1]:=IntersectionPointIndex; UpdateSegmentBoundingBox(fCacheSegments[SegmentAIndex]); end; if (Intersections and 2)<>0 then begin AddSegment(IntersectionPointIndex,fCacheSegments[SegmentBIndex].Points[1]); fCacheSegments[SegmentBIndex].Points[1]:=IntersectionPointIndex; UpdateSegmentBoundingBox(fCacheSegments[SegmentBIndex]); end; TryAgain:=true; end; end; end else begin break; end; if SegmentBIndex=UntilIncludingSegmentIndex then begin break; end else begin SegmentBIndex:=fCacheSegments[SegmentBIndex].Next; end; end; if SegmentAIndex=UntilIncludingSegmentIndex then begin break; end else begin SegmentAIndex:=fCacheSegments[SegmentAIndex].Next; end; end; if TryAgain then begin SortLinkedListSegments; end else begin break; end; until false; end; procedure CollectYCoordinates; var YCoordinateIndex,LocalCountCacheYCoordinates,PointIndex:TpvInt32; CurrentY:TpvCanvasShapeCacheSegmentScalar; Points:array[0..1] of PpvCanvasShapeCacheSegmentPoint; begin LocalCountCacheYCoordinates:=fCountCacheSegmentUniquePoints; if length(fCacheYCoordinates)<LocalCountCacheYCoordinates then begin SetLength(fCacheYCoordinates,LocalCountCacheYCoordinates*2); SetLength(fCacheTemporaryYCoordinates,LocalCountCacheYCoordinates*2); end; for PointIndex:=0 to fCountCacheSegmentUniquePoints-1 do begin fCacheTemporaryYCoordinates[PointIndex]:=fCacheSegmentUniquePoints[PointIndex].Point.y; end; if LocalCountCacheYCoordinates>1 then begin TpvTypedSort<TpvCanvasShapeCacheSegmentScalar>.IntroSort(@fCacheTemporaryYCoordinates[0],0,LocalCountCacheYCoordinates-1,TpvCanvasShapeCacheYCoordinateCompare); end; fCountCacheYCoordinates:=0; YCoordinateIndex:=0; while YCoordinateIndex<LocalCountCacheYCoordinates do begin CurrentY:=fCacheTemporaryYCoordinates[YCoordinateIndex]; inc(YCoordinateIndex); while (YCoordinateIndex<LocalCountCacheYCoordinates) and SameValue(fCacheTemporaryYCoordinates[YCoordinateIndex],CurrentY) do begin inc(YCoordinateIndex); end; fCacheYCoordinates[fCountCacheYCoordinates]:=CurrentY; inc(fCountCacheYCoordinates); end; end; procedure SweepAndSplitSegmentsAtYCoordinates; var UntilIncludingSegmentIndex,CurrentSegmentIndex,NextSegmentIndex, StartYCoordinateIndex,CurrentYCoordinateIndex, TopPointIndex,BottomPointIndex,LastPointIndex,NewPointIndex:TpvInt32; TopPoint,BottomPoint,LastPoint,NewPoint:TpvCanvasShapeCacheSegmentPoint; CurrentYCoordinate,IntersectionTime:TpvCanvasShapeCacheSegmentScalar; Swapped,NeedSort:boolean; p0,p1:PpvCanvasShapeCacheSegmentPoint; begin NeedSort:=false; UntilIncludingSegmentIndex:=fCacheLastSegment; StartYCoordinateIndex:=0; CurrentSegmentIndex:=fCacheFirstSegment; while CurrentSegmentIndex>=0 do begin NextSegmentIndex:=fCacheSegments[CurrentSegmentIndex].Next; p0:=@fCacheSegmentUniquePoints[fCacheSegments[CurrentSegmentIndex].Points[0]].Point; p1:=@fCacheSegmentUniquePoints[fCacheSegments[CurrentSegmentIndex].Points[1]].Point; Swapped:=p0^.y>p1^.y; if Swapped then begin TopPoint:=p1^; BottomPoint:=p0^; TopPointIndex:=fCacheSegments[CurrentSegmentIndex].Points[1]; BottomPointIndex:=fCacheSegments[CurrentSegmentIndex].Points[0]; end else begin TopPoint:=p0^; BottomPoint:=p1^; TopPointIndex:=fCacheSegments[CurrentSegmentIndex].Points[0]; BottomPointIndex:=fCacheSegments[CurrentSegmentIndex].Points[1]; end; if TopPoint.y<BottomPoint.y then begin while ((StartYCoordinateIndex+1)<fCountCacheYCoordinates) and (TopPoint.y>fCacheYCoordinates[StartYCoordinateIndex]) do begin inc(StartYCoordinateIndex); end; LastPoint:=TopPoint; LastPointIndex:=TopPointIndex; for CurrentYCoordinateIndex:=StartYCoordinateIndex to fCountCacheYCoordinates-1 do begin CurrentYCoordinate:=fCacheYCoordinates[CurrentYCoordinateIndex]; if CurrentYCoordinate<BottomPoint.y then begin if (TopPoint.y<CurrentYCoordinate) and not (SameValue(TopPoint.y,CurrentYCoordinate) or SameValue(BottomPoint.y,CurrentYCoordinate) or SameValue(LastPoint.y,CurrentYCoordinate)) then begin IntersectionTime:=(CurrentYCoordinate-TopPoint.y)/(BottomPoint.y-TopPoint.y); if (IntersectionTime>0.0) and (IntersectionTime<1.0) then begin NewPoint.x:=(TopPoint.x*(1.0-IntersectionTime))+(BottomPoint.x*IntersectionTime); NewPoint.y:=CurrentYCoordinate; NewPointIndex:=AddSegmentPoint(NewPoint); if Swapped then begin AddSegment(NewPointIndex,LastPointIndex); end else begin AddSegment(LastPointIndex,NewPointIndex); end; LastPoint:=NewPoint; LastPointIndex:=NewPointIndex; NeedSort:=true; end; end; end else begin break; end; end; if LastPoint.y<BottomPoint.y then begin if LastPointIndex<>TopPointIndex then begin if Swapped then begin fCacheSegments[CurrentSegmentIndex].Points[0]:=BottomPointIndex; fCacheSegments[CurrentSegmentIndex].Points[1]:=LastPointIndex; end else begin fCacheSegments[CurrentSegmentIndex].Points[0]:=LastPointIndex; fCacheSegments[CurrentSegmentIndex].Points[1]:=BottomPointIndex; end; UpdateSegmentBoundingBox(fCacheSegments[CurrentSegmentIndex]); end; end else begin RemoveSegment(CurrentSegmentIndex); end; end else begin RemoveSegment(CurrentSegmentIndex); end; if CurrentSegmentIndex=UntilIncludingSegmentIndex then begin break; end else begin CurrentSegmentIndex:=NextSegmentIndex; end; end; if NeedSort then begin SortLinkedListSegments; end; end; procedure SweepAndGenerateTriangles; var CurrentYSegmentIndex,LastYCoordinateIndex,CurrentYCoordinateIndex, CurrentSegmentIndex,LastSegmentIndex,Winding,i0,i1,i2,i3:TpvInt32; CurrentSegment,LastSegment:PpvCanvasShapeCacheSegment; Visible:boolean; FromY,ToY:TpvCanvasShapeCacheSegmentScalar; a0,a1,b0,b1:PpvCanvasShapeCacheSegmentPoint; begin CurrentYSegmentIndex:=fCacheFirstSegment; LastYCoordinateIndex:=-1; CurrentYCoordinateIndex:=0; while CurrentYCoordinateIndex<fCountCacheYCoordinates do begin if LastYCoordinateIndex>=0 then begin while (CurrentYSegmentIndex>=0) and (fCacheSegments[CurrentYSegmentIndex].AABBMin.Y<fCacheYCoordinates[LastYCoordinateIndex]) do begin CurrentYSegmentIndex:=fCacheSegments[CurrentYSegmentIndex].Next; end; FromY:=fCacheYCoordinates[LastYCoordinateIndex]; ToY:=fCacheYCoordinates[CurrentYCoordinateIndex]; CurrentSegmentIndex:=CurrentYSegmentIndex; Winding:=0; LastSegmentIndex:=-1; while (CurrentSegmentIndex>=0) and (fCacheSegments[CurrentSegmentIndex].AABBMin.Y<ToY) do begin if (fCacheSegments[CurrentSegmentIndex].AABBMin.y<fCacheSegments[CurrentSegmentIndex].AABBMax.y) and ((fCacheSegments[CurrentSegmentIndex].AABBMin.y<ToY) and (FromY<fCacheSegments[CurrentSegmentIndex].AABBMax.y)) then begin if LastSegmentIndex>=0 then begin a0:=@fCacheSegmentUniquePoints[fCacheSegments[LastSegmentIndex].Points[0]].Point; a1:=@fCacheSegmentUniquePoints[fCacheSegments[LastSegmentIndex].Points[1]].Point; b0:=@fCacheSegmentUniquePoints[fCacheSegments[CurrentSegmentIndex].Points[0]].Point; b1:=@fCacheSegmentUniquePoints[fCacheSegments[CurrentSegmentIndex].Points[1]].Point; if a0^.y<=a1^.y then begin inc(Winding); end else begin dec(Winding); end; case aState.fFillRule of TpvCanvasFillRule.NonZero:begin Visible:=Winding<>0; end; else {TpvCanvasFillRule.EvenOdd:}begin Visible:=(Winding and 1)<>0; end; end; if Visible then begin LastSegment:=@fCacheSegments[LastSegmentIndex]; CurrentSegment:=@fCacheSegments[CurrentSegmentIndex]; BeginPart(4,6); if a0^.y<a1^.y then begin i0:=AddVertex(TpvVector2.InlineableCreate(a0^.x,a0^.y),0,TpvVector4.Null,TpvVector2.Null); i1:=AddVertex(TpvVector2.InlineableCreate(a1^.x,a1^.y),0,TpvVector4.Null,TpvVector2.Null); end else begin i0:=AddVertex(TpvVector2.InlineableCreate(a1^.x,a1^.y),0,TpvVector4.Null,TpvVector2.Null); i1:=AddVertex(TpvVector2.InlineableCreate(a0^.x,a0^.y),0,TpvVector4.Null,TpvVector2.Null); end; if b0^.y<b1^.y then begin i2:=AddVertex(TpvVector2.InlineableCreate(b1^.x,b1^.y),0,TpvVector4.Null,TpvVector2.Null); i3:=AddVertex(TpvVector2.InlineableCreate(b0^.x,b0^.y),0,TpvVector4.Null,TpvVector2.Null); end else begin i2:=AddVertex(TpvVector2.InlineableCreate(b0^.x,b0^.y),0,TpvVector4.Null,TpvVector2.Null); i3:=AddVertex(TpvVector2.InlineableCreate(b1^.x,b1^.y),0,TpvVector4.Null,TpvVector2.Null); end; AddIndex(i0); AddIndex(i1); AddIndex(i2); AddIndex(i2); AddIndex(i3); AddIndex(i0); EndPart; end; end; LastSegmentIndex:=CurrentSegmentIndex; end; CurrentSegmentIndex:=fCacheSegments[CurrentSegmentIndex].Next; end; end; LastYCoordinateIndex:=CurrentYCoordinateIndex; inc(CurrentYCoordinateIndex); end; end; procedure GenerateSegmentEdgeTriangles; var CurrentLinePointIndex,i0,i1,i2,i3:TpvInt32; LinePoint:PpvCanvasShapeCacheLinePoint; p0,p1,p10,n10,t10:TpvVector2; MetaInfo:TpvVector4; begin for CurrentLinePointIndex:=0 to fCountCacheLinePoints-1 do begin LinePoint:=@fCacheLinePoints[CurrentLinePointIndex]; if LinePoint^.Last>=0 then begin p0:=fCacheLinePoints[LinePoint^.Last].Position; p1:=LinePoint^.Position; p10:=p1-p0; n10:=p10.Normalize; t10:=n10.Perpendicular; MetaInfo.xy:=p0; MetaInfo.zw:=p1; BeginPart(4,6); p0:=p0-n10; p1:=p1+n10; i0:=AddVertex(p0-t10,pcvvaomRoundLine,MetaInfo,(-2.0)*(n10+t10)); i1:=AddVertex(p0+t10,pcvvaomRoundLine,MetaInfo,2.0*(t10-n10)); i2:=AddVertex(p1+t10,pcvvaomRoundLine,MetaInfo,2.0*(n10+t10)); i3:=AddVertex(p1-t10,pcvvaomRoundLine,MetaInfo,2.0*(n10-t10)); AddIndex(i0); AddIndex(i1); AddIndex(i2); AddIndex(i2); AddIndex(i3); AddIndex(i0); EndPart; end; end; end; begin try SortLinkedListSegments; SweepAndSplitSegmentsAtIntersections; CollectYCoordinates; SweepAndSplitSegmentsAtYCoordinates; SweepAndGenerateTriangles; GenerateSegmentEdgeTriangles; except on e:EpvCanvasShape do begin end; on e:Exception do begin raise; end; end; end; begin Reset; InitializeCurveTessellationTolerance(aState,aCanvas); InitializeSegmentUniquePointHashTable; LastLinePoint:=-1; fCacheFirstSegment:=-1; fCacheLastSegment:=-1; for CommandIndex:=0 to aPath.fCountCommands-1 do begin Command:=@aPath.fCommands[CommandIndex]; case Command^.CommandType of TpvCanvasPathCommandType.MoveTo:begin FillMoveTo(Command.Points[0]); end; TpvCanvasPathCommandType.LineTo:begin FillLineTo(Command.Points[0]); end; TpvCanvasPathCommandType.QuadraticCurveTo:begin FillQuadraticCurveTo(Command.Points[0],Command.Points[1]); end; TpvCanvasPathCommandType.CubicCurveTo:begin FillCubicCurveTo(Command.Points[0],Command.Points[1],Command.Points[2]); end; TpvCanvasPathCommandType.ArcTo:begin FillArcTo(Command.Points[0],Command.Points[1],Command.Points[2].x); end; TpvCanvasPathCommandType.Close:begin FillClose; end; end; end; FillFlush; end; constructor TpvCanvasVulkanDescriptor.Create(const aCanvas:TpvCanvas); begin inherited Create; Value:=self; fCanvas:=aCanvas; fDescriptorPool:=nil; fDescriptorSet:=nil; fDescriptorTexture:=nil; end; destructor TpvCanvasVulkanDescriptor.Destroy; begin FreeAndNil(fDescriptorSet); FreeAndNil(fDescriptorPool); fDescriptorTexture:=nil; inherited Destroy; end; constructor TpvCanvasCommon.Create(const aDevice:TpvVulkanDevice); var Stream:TStream; begin inherited Create; fDevice:=aDevice; fDevice.CanvasCommon:=self; fReferenceCounter:=0; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasVertexClipDistanceSPIRVData,CanvasVertexClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasVertexSPIRVData,CanvasVertexSPIRVDataSize); end; try fCanvasVertexShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasNoTextureVertexClipDistanceSPIRVData,CanvasNoTextureVertexClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasNoTextureVertexSPIRVData,CanvasNoTextureVertexSPIRVDataSize); end; try fCanvasVertexNoTextureShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureClipDistanceSPIRVData,CanvasFragmentGUINoTextureClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureSPIRVData,CanvasFragmentGUINoTextureSPIRVDataSize); end; try fCanvasFragmentGUINoTextureShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureClipDistanceSPIRVData,CanvasFragmentNoTextureClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureSPIRVData,CanvasFragmentNoTextureSPIRVDataSize); end; try fCanvasFragmentNoTextureShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureClipDistanceSPIRVData,CanvasFragmentTextureClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureSPIRVData,CanvasFragmentTextureSPIRVDataSize); end; try fCanvasFragmentTextureShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureClipDistanceSPIRVData,CanvasFragmentAtlasTextureClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureSPIRVData,CanvasFragmentAtlasTextureSPIRVDataSize); end; try fCanvasFragmentAtlasTextureShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathClipDistanceSPIRVData,CanvasFragmentVectorPathClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathSPIRVData,CanvasFragmentVectorPathSPIRVDataSize); end; try fCanvasFragmentVectorPathShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureNoBlendingClipDistanceSPIRVData,CanvasFragmentGUINoTextureNoBlendingClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureNoBlendingSPIRVData,CanvasFragmentGUINoTextureNoBlendingSPIRVDataSize); end; try fCanvasFragmentGUINoTextureNoBlendingShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureNoBlendingClipDistanceSPIRVData,CanvasFragmentNoTextureNoBlendingClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureNoBlendingSPIRVData,CanvasFragmentNoTextureNoBlendingSPIRVDataSize); end; try fCanvasFragmentNoTextureNoBlendingShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureNoBlendingClipDistanceSPIRVData,CanvasFragmentTextureNoBlendingClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureNoBlendingSPIRVData,CanvasFragmentTextureNoBlendingSPIRVDataSize); end; try fCanvasFragmentTextureNoBlendingShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureNoBlendingClipDistanceSPIRVData,CanvasFragmentAtlasTextureNoBlendingClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureNoBlendingSPIRVData,CanvasFragmentAtlasTextureNoBlendingSPIRVDataSize); end; try fCanvasFragmentAtlasTextureNoBlendingShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathNoBlendingClipDistanceSPIRVData,CanvasFragmentVectorPathNoBlendingClipDistanceSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathNoBlendingSPIRVData,CanvasFragmentVectorPathNoBlendingSPIRVDataSize); end; try fCanvasFragmentVectorPathNoBlendingShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureNoBlendingClipDistanceNoDiscardSPIRVData,CanvasFragmentGUINoTextureNoBlendingClipDistanceNoDiscardSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentGUINoTextureNoBlendingNoDiscardSPIRVData,CanvasFragmentGUINoTextureNoBlendingNoDiscardSPIRVDataSize); end; try fCanvasFragmentGUINoTextureNoBlendingNoDiscardShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureNoBlendingClipDistanceNoDiscardSPIRVData,CanvasFragmentNoTextureNoBlendingClipDistanceNoDiscardSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentNoTextureNoBlendingNoDiscardSPIRVData,CanvasFragmentNoTextureNoBlendingNoDiscardSPIRVDataSize); end; try fCanvasFragmentNoTextureNoBlendingNoDiscardShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureNoBlendingClipDistanceNoDiscardSPIRVData,CanvasFragmentTextureNoBlendingClipDistanceNoDiscardSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentTextureNoBlendingNoDiscardSPIRVData,CanvasFragmentTextureNoBlendingNoDiscardSPIRVDataSize); end; try fCanvasFragmentTextureNoBlendingNoDiscardShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureNoBlendingClipDistanceNoDiscardSPIRVData,CanvasFragmentAtlasTextureNoBlendingClipDistanceNoDiscardSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentAtlasTextureNoBlendingNoDiscardSPIRVData,CanvasFragmentAtlasTextureNoBlendingNoDiscardSPIRVDataSize); end; try fCanvasFragmentAtlasTextureNoBlendingNoDiscardShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; if aDevice.PhysicalDevice.Features.shaderClipDistance<>0 then begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathNoBlendingClipDistanceNoDiscardSPIRVData,CanvasFragmentVectorPathNoBlendingClipDistanceNoDiscardSPIRVDataSize); end else begin Stream:=TpvDataStream.Create(@CanvasFragmentVectorPathNoBlendingNoDiscardSPIRVData,CanvasFragmentVectorPathNoBlendingNoDiscardSPIRVDataSize); end; try fCanvasFragmentVectorPathNoBlendingNoDiscardShaderModule:=TpvVulkanShaderModule.Create(fDevice,Stream); finally Stream.Free; end; fVulkanPipelineCanvasShaderStageVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fCanvasVertexShaderModule,'main'); fVulkanPipelineCanvasShaderStageVertexNoTexture:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fCanvasVertexNoTextureShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentGUINoTexture:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentGUINoTextureShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentNoTexture:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentNoTextureShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentTexture:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentTextureShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentAtlasTexture:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentAtlasTextureShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentVectorPath:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentVectorPathShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlending:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentGUINoTextureNoBlendingShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlending:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentNoTextureNoBlendingShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentTextureNoBlending:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentTextureNoBlendingShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlending:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentAtlasTextureNoBlendingShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlending:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentVectorPathNoBlendingShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlendingNoDiscard:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentGUINoTextureNoBlendingNoDiscardShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlendingNoDiscard:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentNoTextureNoBlendingNoDiscardShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentTextureNoBlendingNoDiscard:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentTextureNoBlendingNoDiscardShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlendingNoDiscard:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentAtlasTextureNoBlendingNoDiscardShaderModule,'main'); fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlendingNoDiscard:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fCanvasFragmentVectorPathNoBlendingNoDiscardShaderModule,'main'); end; destructor TpvCanvasCommon.Destroy; begin fDevice.CanvasCommon:=nil; FreeAndNil(fVulkanPipelineCanvasShaderStageVertex); FreeAndNil(fVulkanPipelineCanvasShaderStageVertexNoTexture); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentGUINoTexture); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentNoTexture); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentTexture); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentAtlasTexture); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentVectorPath); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlending); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlending); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentTextureNoBlending); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlending); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlending); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlendingNoDiscard); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlendingNoDiscard); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentTextureNoBlendingNoDiscard); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlendingNoDiscard); FreeAndNil(fVulkanPipelineCanvasShaderStageFragmentVectorPathNoBlendingNoDiscard); FreeAndNil(fCanvasVertexShaderModule); FreeAndNil(fCanvasVertexNoTextureShaderModule); FreeAndNil(fCanvasFragmentGUINoTextureShaderModule); FreeAndNil(fCanvasFragmentNoTextureShaderModule); FreeAndNil(fCanvasFragmentTextureShaderModule); FreeAndNil(fCanvasFragmentAtlasTextureShaderModule); FreeAndNil(fCanvasFragmentVectorPathShaderModule); FreeAndNil(fCanvasFragmentGUINoTextureNoBlendingShaderModule); FreeAndNil(fCanvasFragmentNoTextureNoBlendingShaderModule); FreeAndNil(fCanvasFragmentTextureNoBlendingShaderModule); FreeAndNil(fCanvasFragmentAtlasTextureNoBlendingShaderModule); FreeAndNil(fCanvasFragmentVectorPathNoBlendingShaderModule); FreeAndNil(fCanvasFragmentGUINoTextureNoBlendingNoDiscardShaderModule); FreeAndNil(fCanvasFragmentNoTextureNoBlendingNoDiscardShaderModule); FreeAndNil(fCanvasFragmentTextureNoBlendingNoDiscardShaderModule); FreeAndNil(fCanvasFragmentAtlasTextureNoBlendingNoDiscardShaderModule); FreeAndNil(fCanvasFragmentVectorPathNoBlendingNoDiscardShaderModule); inherited Destroy; end; class function TpvCanvasCommon.Acquire(const aDevice:TpvVulkanDevice):TpvCanvasCommon; begin while TPasMPInterlocked.CompareExchange(fLock,-1,0)<>0 do begin TPasMP.Yield; end; try result:=TpvCanvasCommon(aDevice.CanvasCommon); if not assigned(result) then begin result:=TpvCanvasCommon.Create(aDevice); end; TPasMPInterlocked.Increment(result.fReferenceCounter); finally TPasMPInterlocked.Write(fLock,0); end; end; class procedure TpvCanvasCommon.Release(const aDevice:TpvVulkanDevice); var CanvasCommon:TpvCanvasCommon; begin while TPasMPInterlocked.CompareExchange(fLock,-1,0)<>0 do begin TPasMP.Yield; end; try if assigned(aDevice) then begin CanvasCommon:=TpvCanvasCommon(aDevice.CanvasCommon); if assigned(CanvasCommon) then begin if TPasMPInterlocked.Decrement(CanvasCommon.fReferenceCounter)=0 then begin CanvasCommon.Free; end; end; end; finally TPasMPInterlocked.Write(fLock,0); end; end; constructor TpvCanvas.Create(const aDevice:TpvVulkanDevice; const aPipelineCache:TpvVulkanPipelineCache; const aCountProcessingBuffers:TpvInt32); var Index,TextureModeIndex:TpvInt32; RenderingModeIndex:TpvCanvasRenderingMode; BlendingModeIndex:TpvCanvasBlendingMode; Stream:TStream; begin inherited Create; fDevice:=aDevice; fCanvasCommon:=TpvCanvasCommon.Acquire(fDevice); fPipelineCache:=aPipelineCache; fCountBuffers:=0; fVulkanCanvasBuffers:=nil; fCountProcessingBuffers:=aCountProcessingBuffers; fShape:=TpvCanvasShape.Create; fState:=TpvCanvasState.Create; fStateStack:=TpvCanvasStateStack.Create(true); fState.Reset; fWidth:=1280; fHeight:=720; fViewPort.x:=0.0; fViewPort.y:=0.0; fViewPort.Width:=1280.0; fViewPort.Height:=720.0; fViewPort.minDepth:=0.0; fViewPort.maxDepth:=1.0; fPointerToViewport:=@fViewport; fVulkanDescriptorSetGUINoTextureLayout:=TpvVulkanDescriptorSetLayout.Create(fDevice); fVulkanDescriptorSetGUINoTextureLayout.Initialize; fVulkanDescriptorSetNoTextureLayout:=TpvVulkanDescriptorSetLayout.Create(fDevice); fVulkanDescriptorSetNoTextureLayout.Initialize; fVulkanDescriptorSetTextureLayout:=TpvVulkanDescriptorSetLayout.Create(fDevice); fVulkanDescriptorSetTextureLayout.AddBinding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), []); fVulkanDescriptorSetTextureLayout.Initialize; fVulkanDescriptorSetVectorPathLayout:=TpvVulkanDescriptorSetLayout.Create(fDevice); fVulkanDescriptorSetVectorPathLayout.AddBinding(0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), []); fVulkanDescriptorSetVectorPathLayout.AddBinding(1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), []); fVulkanDescriptorSetVectorPathLayout.AddBinding(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), []); fVulkanDescriptorSetVectorPathLayout.AddBinding(3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), []); fVulkanDescriptorSetVectorPathLayout.Initialize; fVulkanDescriptors:=TpvCanvasVulkanDescriptorLinkedListNode.Create; fCountVulkanDescriptors:=0; fVulkanTextureDescriptorSetHashMap:=TpvCanvasTextureDescriptorSetHashMap.Create(nil); fVulkanRenderPass:=nil; for BlendingModeIndex:=Low(TpvCanvasBlendingMode) to High(TpvCanvasBlendingMode) do begin for TextureModeIndex:=0 to 3 do begin fVulkanPipelineLayouts[BlendingModeIndex,TextureModeIndex]:=nil; fVulkanGraphicsPipelines[BlendingModeIndex,TextureModeIndex]:=nil; end; end; SetCountBuffers(1); fCurrentFrameNumber:=0; end; destructor TpvCanvas.Destroy; var Index,SubIndex:TpvInt32; RenderingModeIndex:TpvCanvasRenderingMode; BlendingModeIndex:TpvCanvasBlendingMode; VulkanCanvasBuffer:PpvCanvasBuffer; begin FreeAndNil(fStateStack); FreeAndNil(fState); FreeAndNil(fShape); SetCountBuffers(0); SetVulkanRenderPass(nil); while not fVulkanDescriptors.IsEmpty do begin fVulkanDescriptors.Front.Free; end; FreeAndNil(fVulkanDescriptors); FreeAndNil(fVulkanDescriptorSetVectorPathLayout); FreeAndNil(fVulkanDescriptorSetTextureLayout); FreeAndNil(fVulkanDescriptorSetNoTextureLayout); FreeAndNil(fVulkanDescriptorSetGUINoTextureLayout); FreeAndNil(fVulkanTextureDescriptorSetHashMap); fCurrentDestinationVertexBufferPointer:=nil; fCurrentDestinationIndexBufferPointer:=nil; fCanvasCommon:=nil; TpvCanvasCommon.Release(fDevice); inherited Destroy; end; procedure TpvCanvas.SetVulkanRenderPass(const aVulkanRenderPass:TpvVulkanRenderPass); var TextureModeIndex:TpvInt32; BlendingModeIndex:TpvCanvasBlendingMode; VulkanPipelineLayout:TpvVulkanPipelineLayout; VulkanGraphicsPipeline:TpvVulkanGraphicsPipeline; begin if fVulkanRenderPass<>aVulkanRenderPass then begin for BlendingModeIndex:=Low(TpvCanvasBlendingMode) to High(TpvCanvasBlendingMode) do begin for TextureModeIndex:=0 to 3 do begin FreeAndNil(fVulkanGraphicsPipelines[BlendingModeIndex,TextureModeIndex]); FreeAndNil(fVulkanPipelineLayouts[BlendingModeIndex,TextureModeIndex]); end; end; fVulkanRenderPass:=aVulkanRenderPass; if assigned(fVulkanRenderPass) then begin for BlendingModeIndex:=Low(TpvCanvasBlendingMode) to High(TpvCanvasBlendingMode) do begin for TextureModeIndex:=0 to 3 do begin VulkanPipelineLayout:=TpvVulkanPipelineLayout.Create(fDevice); fVulkanPipelineLayouts[BlendingModeIndex,TextureModeIndex]:=VulkanPipelineLayout; case TextureModeIndex of 0:begin VulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetNoTextureLayout); end; 1..2:begin VulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetTextureLayout); end; 3:begin VulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetGUINoTextureLayout); end; else {4:}begin VulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetVectorPathLayout); end; end; VulkanPipelineLayout.AddPushConstantRange(TVkShaderStageFlags(VK_SHADER_STAGE_VERTEX_BIT) or TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), 0, SizeOf(TpvCanvasPushConstants)); VulkanPipelineLayout.Initialize; VulkanGraphicsPipeline:=TpvVulkanGraphicsPipeline.Create(fDevice, fPipelineCache, 0, [], VulkanPipelineLayout, fVulkanRenderPass, 0, nil, 0); fVulkanGraphicsPipelines[BlendingModeIndex,TextureModeIndex]:=VulkanGraphicsPipeline; case TextureModeIndex of 0:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageVertexNoTexture); end; else begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageVertex); end; end; case BlendingModeIndex of TpvCanvasBlendingMode.None:begin case TextureModeIndex of 1:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentTextureNoBlending); end; 2:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlending); end; 3:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlending); end; else begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlending); end; end; end; TpvCanvasBlendingMode.NoDiscard:begin case TextureModeIndex of 1:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentTextureNoBlendingNoDiscard); end; 2:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentAtlasTextureNoBlendingNoDiscard); end; 3:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentGUINoTextureNoBlendingNoDiscard); end; else begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentNoTextureNoBlendingNoDiscard); end; end; end; else begin case TextureModeIndex of 1:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentTexture); end; 2:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentAtlasTexture); end; 3:begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentGUINoTexture); end; else begin VulkanGraphicsPipeline.AddStage(fCanvasCommon.fVulkanPipelineCanvasShaderStageFragmentNoTexture); end; end; end; end; VulkanGraphicsPipeline.InputAssemblyState.Topology:=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; VulkanGraphicsPipeline.InputAssemblyState.PrimitiveRestartEnable:=false; VulkanGraphicsPipeline.VertexInputState.AddVertexInputBindingDescription(0,SizeOf(TpvCanvasVertex),VK_VERTEX_INPUT_RATE_VERTEX); VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(0,0,VK_FORMAT_R32G32B32_SFLOAT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.Position))); VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(1,0,VK_FORMAT_R16G16B16A16_SFLOAT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.Color))); if TextureModeIndex<>0 then begin VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(2,0,VK_FORMAT_R32G32B32_SFLOAT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.TextureCoord))); end; VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(3,0,VK_FORMAT_R32_UINT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.State))); VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(4,0,VK_FORMAT_R32G32B32A32_SFLOAT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.ClipRect))); VulkanGraphicsPipeline.VertexInputState.AddVertexInputAttributeDescription(5,0,VK_FORMAT_R32G32B32A32_SFLOAT,TpvPtrUInt(TpvPointer(@PpvCanvasVertex(nil)^.MetaInfo))); VulkanGraphicsPipeline.ViewPortState.AddViewPort(0.0,0.0,fWidth,fHeight,0.0,1.0); VulkanGraphicsPipeline.ViewPortState.DynamicViewPorts:=true; VulkanGraphicsPipeline.ViewPortState.AddScissor(0,0,fWidth,fHeight); VulkanGraphicsPipeline.ViewPortState.DynamicScissors:=true; VulkanGraphicsPipeline.RasterizationState.DepthClampEnable:=false; VulkanGraphicsPipeline.RasterizationState.RasterizerDiscardEnable:=false; VulkanGraphicsPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL; VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE); VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE; VulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=false; VulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.0; VulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0; VulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0; VulkanGraphicsPipeline.RasterizationState.LineWidth:=1.0; VulkanGraphicsPipeline.MultisampleState.RasterizationSamples:=VK_SAMPLE_COUNT_1_BIT; VulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=false; VulkanGraphicsPipeline.MultisampleState.MinSampleShading:=0.0; VulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0; VulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=false; VulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false; VulkanGraphicsPipeline.ColorBlendState.LogicOpEnable:=false; VulkanGraphicsPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[0]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[1]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[2]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[3]:=0.0; case BlendingModeIndex of TpvCanvasBlendingMode.None:begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT)); end; TpvCanvasBlendingMode.AlphaBlending:begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT)); end; TpvCanvasBlendingMode.OnlyDepth:begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, 0); end; else {TpvCanvasBlendingMode.AdditiveBlending:}begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT)); end; end; VulkanGraphicsPipeline.DepthStencilState.DepthTestEnable:=true; VulkanGraphicsPipeline.DepthStencilState.DepthWriteEnable:=true;//BlendingModeIndex in [TpvCanvasBlendingMode.None]; if BlendingModeIndex=TpvCanvasBlendingMode.OnlyDepth then begin VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_ALWAYS; end else begin VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_LESS_OR_EQUAL; end; VulkanGraphicsPipeline.DepthStencilState.DepthBoundsTestEnable:=false; VulkanGraphicsPipeline.DepthStencilState.StencilTestEnable:=false; VulkanGraphicsPipeline.DynamicState.AddDynamicStates([VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR]); VulkanGraphicsPipeline.Initialize; VulkanGraphicsPipeline.FreeMemory; end; end; end; end; end; procedure TpvCanvas.SetCountBuffers(const aCountBuffers:TpvInt32); var Index,SubIndex:TpvInt32; VulkanCanvasBuffer:PpvCanvasBuffer; begin if fCountBuffers<>aCountBuffers then begin for Index:=aCountBuffers to fCountBuffers-1 do begin VulkanCanvasBuffer:=@fVulkanCanvasBuffers[Index]; for SubIndex:=0 to VulkanCanvasBuffer^.fCountAllocatedBuffers-1 do begin FreeAndNil(VulkanCanvasBuffer^.fVulkanVertexBuffers[SubIndex]); FreeAndNil(VulkanCanvasBuffer^.fVulkanIndexBuffers[SubIndex]); end; VulkanCanvasBuffer^.fVulkanVertexBuffers:=nil; VulkanCanvasBuffer^.fVulkanIndexBuffers:=nil; VulkanCanvasBuffer^.fVertexBuffers:=nil; VulkanCanvasBuffer^.fVertexBufferSizes:=nil; VulkanCanvasBuffer^.fIndexBuffers:=nil; VulkanCanvasBuffer^.fIndexBufferSizes:=nil; VulkanCanvasBuffer^.fQueueItems:=nil; Finalize(VulkanCanvasBuffer^); end; if length(fVulkanCanvasBuffers)<aCountBuffers then begin SetLength(fVulkanCanvasBuffers,aCountBuffers*2); end; for Index:=fCountBuffers to aCountBuffers-1 do begin VulkanCanvasBuffer:=@fVulkanCanvasBuffers[Index]; Initialize(VulkanCanvasBuffer^); VulkanCanvasBuffer^.fSpinLock:=0; VulkanCanvasBuffer^.fVulkanVertexBuffers:=nil; VulkanCanvasBuffer^.fVulkanIndexBuffers:=nil; VulkanCanvasBuffer^.fVertexBuffers:=nil; VulkanCanvasBuffer^.fVertexBufferSizes:=nil; VulkanCanvasBuffer^.fIndexBuffers:=nil; VulkanCanvasBuffer^.fIndexBufferSizes:=nil; VulkanCanvasBuffer^.fCountAllocatedBuffers:=0; VulkanCanvasBuffer^.fCountUsedBuffers:=0; VulkanCanvasBuffer^.fQueueItems:=nil; VulkanCanvasBuffer^.fCountQueueItems:=0; end; fCountBuffers:=aCountBuffers; fCurrentVulkanBufferIndex:=0; fCurrentVulkanVertexBufferOffset:=0; fCurrentVulkanIndexBufferOffset:=0; fCurrentCountVertices:=0; fCurrentCountIndices:=0; fCurrentDestinationVertexBufferPointer:=nil; fCurrentDestinationIndexBufferPointer:=nil; fCurrentFillBuffer:=nil; end; end; function TpvCanvas.GetTexture:TObject; begin result:=fState.fTexture; end; procedure TpvCanvas.SetTexture(const aTexture:TObject); begin if fState.fTexture<>aTexture then begin Flush; fState.fTexture:=aTexture; end; end; function TpvCanvas.GetAtlasTexture:TObject; begin result:=fState.fAtlasTexture; end; procedure TpvCanvas.SetAtlasTexture(const aTexture:TObject); begin if fState.fAtlasTexture<>aTexture then begin Flush; fState.fAtlasTexture:=aTexture; end; end; function TpvCanvas.GetGUIElementMode:boolean; begin result:=fState.fGUIElementMode; end; procedure TpvCanvas.SetGUIElementMode(const aGUIElementMode:boolean); begin if fState.fGUIElementMode<>aGUIElementMode then begin Flush; fState.fGUIElementMode:=aGUIElementMode; end; end; procedure TpvCanvas.SetScissor(const aScissor:TVkRect2D); begin if (fState.fScissor.offset.x<>aScissor.offset.x) or (fState.fScissor.offset.y<>aScissor.offset.y) or (fState.fScissor.extent.Width<>aScissor.extent.Width) or (fState.fScissor.extent.Height<>aScissor.extent.Height) then begin Flush; fState.fScissor:=aScissor; end; end; procedure TpvCanvas.SetScissor(const aLeft,aTop,aWidth,aHeight:TpvInt32); var NewScissor:TVkRect2D; begin NewScissor.offset.x:=aLeft; NewScissor.offset.y:=aTop; NewScissor.extent.Width:=aWidth; NewScissor.extent.Height:=aHeight; SetScissor(NewScissor); end; function TpvCanvas.GetClipRect:TpvRect; begin result:=fState.fClipRect; end; procedure TpvCanvas.SetClipRect(const aClipRect:TVkRect2D); begin fState.fClipRect.LeftTop:=TpvVector2.InlineableCreate(aClipRect.offset.x,aClipRect.offset.y); fState.fClipRect.RightBottom:=TpvVector2.InlineableCreate(aClipRect.offset.x+(aClipRect.extent.width+0.0),aClipRect.offset.y+(aClipRect.extent.height+0.0)); fState.UpdateClipSpaceClipRect(self); end; procedure TpvCanvas.SetClipRect(const aClipRect:TpvRect); begin fState.fClipRect:=aClipRect; fState.UpdateClipSpaceClipRect(self); end; procedure TpvCanvas.SetClipRect(const aLeft,aTop,aWidth,aHeight:TpvInt32); begin fState.fClipRect.LeftTop:=TpvVector2.InlineableCreate(aLeft,aTop); fState.fClipRect.RightBottom:=TpvVector2.InlineableCreate(aLeft+aWidth,aTop+aHeight); fState.UpdateClipSpaceClipRect(self); end; function TpvCanvas.GetBlendingMode:TpvCanvasBlendingMode; begin result:=fState.fBlendingMode; end; procedure TpvCanvas.SetBlendingMode(const aBlendingMode:TpvCanvasBlendingMode); begin if fState.fBlendingMode<>aBlendingMode then begin Flush; fState.fBlendingMode:=aBlendingMode; end; end; function TpvCanvas.GetZPosition:TpvFloat; begin result:=fState.fZPosition; end; procedure TpvCanvas.SetZPosition(const aZPosition:TpvFloat); begin fState.fZPosition:=aZPosition; end; function TpvCanvas.GetLineWidth:TpvFloat; begin result:=fState.fLineWidth; end; procedure TpvCanvas.SetLineWidth(const aLineWidth:TpvFloat); begin fState.fLineWidth:=aLineWidth; end; function TpvCanvas.GetMiterLimit:TpvFloat; begin result:=fState.fMiterLimit; end; procedure TpvCanvas.SetMiterLimit(const aMiterLimit:TpvFloat); begin fState.fMiterLimit:=aMiterLimit; end; function TpvCanvas.GetLineJoin:TpvCanvasLineJoin; begin result:=fState.fLineJoin; end; procedure TpvCanvas.SetLineJoin(const aLineJoin:TpvCanvasLineJoin); begin fState.fLineJoin:=aLineJoin; end; function TpvCanvas.GetLineCap:TpvCanvasLineCap; begin result:=fState.fLineCap; end; procedure TpvCanvas.SetLineCap(const aLineCap:TpvCanvasLineCap); begin fState.fLineCap:=aLineCap; end; function TpvCanvas.GetFillRule:TpvCanvasFillRule; begin result:=fState.fFillRule; end; procedure TpvCanvas.SetFillRule(const aFillRule:TpvCanvasFillRule); begin fState.fFillRule:=aFillRule; end; function TpvCanvas.GetFillStyle:TpvCanvasFillStyle; begin result:=fState.fFillStyle; end; procedure TpvCanvas.SetFillStyle(const aFillStyle:TpvCanvasFillStyle); begin if fState.fFillStyle<>aFillStyle then begin //Flush; fState.fFillStyle:=aFillStyle; end; end; function TpvCanvas.GetFillWrapMode:TpvCanvasFillWrapMode; begin result:=fState.fFillWrapMode; end; procedure TpvCanvas.SetFillWrapMode(const aFillWrapMode:TpvCanvasFillWrapMode); begin if fState.fFillWrapMode<>aFillWrapMode then begin //Flush; fState.fFillWrapMode:=aFillWrapMode; end; end; function TpvCanvas.GetColor:TpvVector4; begin result:=fState.GetColor; end; procedure TpvCanvas.SetColor(const aColor:TpvVector4); begin fState.SetColor(aColor); end; function TpvCanvas.GetStartColor:TpvVector4; begin result:=fState.StartColor; end; procedure TpvCanvas.SetStartColor(const aColor:TpvVector4); begin if fState.StartColor<>aColor then begin Flush; fState.StartColor:=aColor; end; end; function TpvCanvas.GetStopColor:TpvVector4; begin result:=fState.StopColor; end; procedure TpvCanvas.SetStopColor(const aColor:TpvVector4); begin if fState.StopColor<>aColor then begin Flush; fState.StopColor:=aColor; end; end; function TpvCanvas.GetProjectionMatrix:TpvMatrix4x4; begin result:=fState.fProjectionMatrix; end; procedure TpvCanvas.SetProjectionMatrix(const aProjectionMatrix:TpvMatrix4x4); begin if fState.fProjectionMatrix<>aProjectionMatrix then begin Flush; fState.fProjectionMatrix:=aProjectionMatrix; end; end; function TpvCanvas.GetViewMatrix:TpvMatrix4x4; begin result:=fState.fViewMatrix; end; procedure TpvCanvas.SetViewMatrix(const aViewMatrix:TpvMatrix4x4); begin if fState.fViewMatrix<>aViewMatrix then begin Flush; fState.fViewMatrix:=aViewMatrix; end; end; function TpvCanvas.GetModelMatrix:TpvMatrix4x4; begin result:=fState.fModelMatrix; end; procedure TpvCanvas.SetModelMatrix(const aModelMatrix:TpvMatrix4x4); begin fState.fModelMatrix:=aModelMatrix; end; function TpvCanvas.GetFillMatrix:TpvMatrix4x4; begin result:=fState.FillMatrix; end; procedure TpvCanvas.SetFillMatrix(const aMatrix:TpvMatrix4x4); begin if fState.FillMatrix<>aMatrix then begin Flush; fState.FillMatrix:=aMatrix; end; end; function TpvCanvas.GetStrokePattern:TpvCanvasStrokePattern; begin result:=fState.fStrokePattern; end; procedure TpvCanvas.SetStrokePattern(const aStrokePattern:TpvCanvasStrokePattern); begin fState.fStrokePattern:=aStrokePattern; end; function TpvCanvas.GetFont:TpvFont; begin result:=fState.fFont; end; procedure TpvCanvas.SetFont(const aFont:TpvFont); begin fState.fFont:=aFont; end; function TpvCanvas.GetFontSize:TpvFloat; begin result:=fState.fFontSize; end; procedure TpvCanvas.SetFontSize(const aFontSize:TpvFloat); begin fState.fFontSize:=aFontSize; end; function TpvCanvas.GetTextHorizontalAlignment:TpvCanvasTextHorizontalAlignment; begin result:=fState.fTextHorizontalAlignment; end; procedure TpvCanvas.SetTextHorizontalAlignment(aTextHorizontalAlignment:TpvCanvasTextHorizontalAlignment); begin fState.fTextHorizontalAlignment:=aTextHorizontalAlignment; end; function TpvCanvas.GetTextVerticalAlignment:TpvCanvasTextVerticalAlignment; begin result:=fState.fTextVerticalAlignment; end; procedure TpvCanvas.SetTextVerticalAlignment(aTextVerticalAlignment:TpvCanvasTextVerticalAlignment); begin fState.fTextVerticalAlignment:=aTextVerticalAlignment; end; function TpvCanvas.GetVertexState:TpvUInt32; begin result:=(TpvUInt32(fInternalRenderingMode) shl pvcvsRenderingModeShift) or (TpvUInt32(fState.fFillStyle) shl pvcvsFillStyleShift) or (TpvUInt32(fState.fFillWrapMode) shl pvcvsFillWrapModeShift) or (TpvUInt32(fSignedDistanceFieldVariant) shl pvcvsSignedDistanceFieldVariantShift); end; procedure TpvCanvas.GarbageCollectDescriptors; var DescriptorLinkedListNode,PreviousDescriptorLinkedListNode:TpvCanvasVulkanDescriptorLinkedListNode; Descriptor:TpvCanvasVulkanDescriptor; CountProcessingBuffers:TpvNativeInt; begin CountProcessingBuffers:=Max(2,fCountProcessingBuffers)+1; DescriptorLinkedListNode:=fVulkanDescriptors.Back; while DescriptorLinkedListNode<>fVulkanDescriptors do begin PreviousDescriptorLinkedListNode:=DescriptorLinkedListNode.Previous; Descriptor:=DescriptorLinkedListNode.Value; if assigned(Descriptor) and (TpvNativeInt(TpvNativeUInt(fCurrentFrameNumber-Descriptor.fLastUsedFrameNumber))>CountProcessingBuffers) then begin try fVulkanTextureDescriptorSetHashMap.Delete(Descriptor.fDescriptorTexture); finally Descriptor.Free; end; end else begin break; end; DescriptorLinkedListNode:=PreviousDescriptorLinkedListNode; end; end; procedure TpvCanvas.Start(const aBufferIndex:TpvInt32); begin fCurrentCountVertices:=0; fCurrentCountIndices:=0; fCurrentFillBuffer:=@fVulkanCanvasBuffers[aBufferIndex]; fCurrentFillBuffer^.fCountQueueItems:=0; fCurrentFillBuffer^.fCountUsedBuffers:=0; fState.Reset; fState.fScissor.offset.x:=trunc(floor(fViewport.x)); fState.fScissor.offset.y:=trunc(floor(fViewport.y)); fState.fScissor.extent.Width:=trunc(ceil(fViewport.Width)); fState.fScissor.extent.Height:=trunc(ceil(fViewport.Height)); fState.fClipRect:=TpvRect.CreateAbsolute(0.0,0.0,fWidth,fHeight); fState.UpdateClipSpaceClipRect(self); fState.fProjectionMatrix:=TpvMatrix4x4.CreateOrtho(0.0,fWidth,0.0,fHeight,-100.0,100.0); fCurrentVulkanBufferIndex:=-1; fCurrentVulkanVertexBufferOffset:=0; fCurrentVulkanIndexBufferOffset:=0; GetNextDestinationVertexBuffer; end; procedure TpvCanvas.Stop; begin Flush; fCurrentFillBuffer:=nil; while fStateStack.Count>0 do begin Pop; end; GarbageCollectDescriptors; inc(fCurrentFrameNumber); end; procedure TpvCanvas.DeleteTextureFromCachedDescriptors(const aTexture:TObject); var Descriptor:TpvCanvasVulkanDescriptor; begin if fVulkanTextureDescriptorSetHashMap.TryGet(aTexture,Descriptor) then begin try Descriptor.Free; finally fVulkanTextureDescriptorSetHashMap.Delete(aTexture); end; end; end; procedure TpvCanvas.Flush; var CurrentVulkanBufferIndex,OldCount,NewCount,QueueItemIndex:TpvInt32; QueueItem:PpvCanvasQueueItem; Descriptor:TpvCanvasVulkanDescriptor; CurrentTexture:TObject; begin if assigned(fCurrentFillBuffer) and (fCurrentCountVertices>0) then begin while TPasMPInterlocked.CompareExchange(fCurrentFillBuffer^.fSpinLock,-1,0)<>0 do begin end; try CurrentVulkanBufferIndex:=fCurrentVulkanBufferIndex; fCurrentFillBuffer^.fCountUsedBuffers:=Max(fCurrentFillBuffer^.fCountUsedBuffers,CurrentVulkanBufferIndex+1); OldCount:=fCurrentFillBuffer^.fCountAllocatedBuffers; if OldCount<=CurrentVulkanBufferIndex then begin NewCount:=(CurrentVulkanBufferIndex+1)*2; SetLength(fCurrentFillBuffer^.fVulkanVertexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVulkanIndexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVertexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVertexBufferSizes,NewCount); SetLength(fCurrentFillBuffer^.fIndexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fIndexBufferSizes,NewCount); FillChar(fCurrentFillBuffer^.fVulkanVertexBuffers[OldCount],(NewCount-OldCount)*SizeOf(TpvVulkanBuffer),#0); FillChar(fCurrentFillBuffer^.fVulkanIndexBuffers[OldCount],(NewCount-OldCount)*SizeOf(TpvVulkanBuffer),#0); FillChar(fCurrentFillBuffer^.fVertexBufferSizes[OldCount],(NewCount-OldCount)*SizeOf(TVkSizeInt),#0); FillChar(fCurrentFillBuffer^.fIndexBufferSizes[OldCount],(NewCount-OldCount)*SizeOf(TVkSizeInt),#0); fCurrentFillBuffer^.fCountAllocatedBuffers:=NewCount; end; inc(fCurrentFillBuffer^.fVertexBufferSizes[CurrentVulkanBufferIndex],fCurrentCountVertices*SizeOf(TpvCanvasVertex)); inc(fCurrentFillBuffer^.fIndexBufferSizes[CurrentVulkanBufferIndex],fCurrentCountIndices*SizeOf(TpvUInt32)); if fState.fGUIElementMode then begin CurrentTexture:=nil; end else begin if assigned(fState.fAtlasTexture) then begin CurrentTexture:=fState.fAtlasTexture; end else begin CurrentTexture:=fState.fTexture; end; end; if fVulkanTextureDescriptorSetHashMap.TryGet(CurrentTexture,Descriptor) then begin // Move existent descriptor to front Descriptor.Remove; fVulkanDescriptors.Front.Insert(Descriptor); end else begin // Allocate new descriptor Descriptor:=TpvCanvasVulkanDescriptor.Create(self); try if assigned(CurrentTexture) then begin Descriptor.fDescriptorPool:=TpvVulkanDescriptorPool.Create(fDevice, TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT), 1); Descriptor.fDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,1); Descriptor.fDescriptorPool.Initialize; Descriptor.fDescriptorSet:=TpvVulkanDescriptorSet.Create(Descriptor.fDescriptorPool, fVulkanDescriptorSetTextureLayout); if CurrentTexture is TpvSpriteAtlasArrayTexture then begin Descriptor.fDescriptorSet.WriteToDescriptorSet(0, 0, 1, TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER), [TpvSpriteAtlasArrayTexture(CurrentTexture).Texture.DescriptorImageInfo], [], [], false ); end else begin Descriptor.fDescriptorSet.WriteToDescriptorSet(0, 0, 1, TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER), [TpvVulkanTexture(CurrentTexture).DescriptorImageInfo], [], [], false ); end; Descriptor.fDescriptorSet.Flush; end else begin Descriptor.fDescriptorPool:=TpvVulkanDescriptorPool.Create(fDevice, TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT), 1); Descriptor.fDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,1); Descriptor.fDescriptorPool.Initialize; Descriptor.fDescriptorSet:=TpvVulkanDescriptorSet.Create(Descriptor.fDescriptorPool, fVulkanDescriptorSetNoTextureLayout); Descriptor.fDescriptorSet.Flush; end; finally Descriptor.fDescriptorTexture:=CurrentTexture; fVulkanDescriptors.Front.Insert(Descriptor); fVulkanTextureDescriptorSetHashMap.Add(CurrentTexture,Descriptor); end; end; Descriptor.fLastUsedFrameNumber:=fCurrentFrameNumber; QueueItemIndex:=fCurrentFillBuffer^.fCountQueueItems; inc(fCurrentFillBuffer^.fCountQueueItems); if length(fCurrentFillBuffer^.fQueueItems)<fCurrentFillBuffer^.fCountQueueItems then begin SetLength(fCurrentFillBuffer^.fQueueItems,fCurrentFillBuffer^.fCountQueueItems*2); end; QueueItem:=@fCurrentFillBuffer^.fQueueItems[QueueItemIndex]; QueueItem^.Kind:=TpvCanvasQueueItemKind.Normal; QueueItem^.BufferIndex:=CurrentVulkanBufferIndex; QueueItem^.Descriptor:=Descriptor; QueueItem^.BlendingMode:=fState.fBlendingMode; if fState.fGUIElementMode then begin QueueItem^.TextureMode:=3; end else begin if assigned(CurrentTexture) then begin if (CurrentTexture is TpvSpriteAtlasArrayTexture) or ((CurrentTexture is TpvVulkanTexture) and (TpvVulkanTexture(CurrentTexture).ImageViewType=VK_IMAGE_VIEW_TYPE_2D_ARRAY)) then begin QueueItem^.TextureMode:=2; end else begin QueueItem^.TextureMode:=1; end; end else begin QueueItem^.TextureMode:=0; end; end; QueueItem^.StartVertexIndex:=fCurrentVulkanVertexBufferOffset; QueueItem^.StartIndexIndex:=fCurrentVulkanIndexBufferOffset; QueueItem^.CountVertices:=fCurrentCountVertices; QueueItem^.CountIndices:=fCurrentCountIndices; QueueItem^.Scissor:=fState.fScissor; QueueItem^.PushConstants.TransformMatrix:=fState.fViewMatrix*fState.fProjectionMatrix; QueueItem^.PushConstants.FillMatrix:=fState.fFillMatrix; finally TPasMPInterlocked.Exchange(fCurrentFillBuffer^.fSpinLock,0); end; inc(fCurrentVulkanVertexBufferOffset,fCurrentCountVertices); inc(fCurrentVulkanIndexBufferOffset,fCurrentCountIndices); fCurrentCountVertices:=0; fCurrentCountIndices:=0; fCurrentDestinationVertexBufferPointer:=@fCurrentFillBuffer^.fVertexBuffers[fCurrentVulkanBufferIndex][fCurrentVulkanVertexBufferOffset]; fCurrentDestinationIndexBufferPointer:=@fCurrentFillBuffer^.fIndexBuffers[fCurrentVulkanBufferIndex][fCurrentVulkanIndexBufferOffset]; end; end; procedure TpvCanvas.GetNextDestinationVertexBuffer; var OldCount,NewCount:TpvInt32; begin inc(fCurrentVulkanBufferIndex); fCurrentVulkanVertexBufferOffset:=0; fCurrentVulkanIndexBufferOffset:=0; OldCount:=fCurrentFillBuffer^.fCountAllocatedBuffers; if OldCount<=fCurrentVulkanBufferIndex then begin NewCount:=RoundUpToPowerOfTwo(fCurrentVulkanBufferIndex+1); SetLength(fCurrentFillBuffer^.fVulkanVertexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVulkanIndexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVertexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fVertexBufferSizes,NewCount); SetLength(fCurrentFillBuffer^.fIndexBuffers,NewCount); SetLength(fCurrentFillBuffer^.fIndexBufferSizes,NewCount); FillChar(fCurrentFillBuffer^.fVulkanVertexBuffers[OldCount],(NewCount-OldCount)*SizeOf(TpvVulkanBuffer),#0); FillChar(fCurrentFillBuffer^.fVulkanIndexBuffers[OldCount],(NewCount-OldCount)*SizeOf(TpvVulkanBuffer),#0); FillChar(fCurrentFillBuffer^.fVertexBufferSizes[OldCount],(NewCount-OldCount)*SizeOf(TVkSizeInt),#0); FillChar(fCurrentFillBuffer^.fIndexBufferSizes[OldCount],(NewCount-OldCount)*SizeOf(TVkSizeInt),#0); fCurrentFillBuffer^.fCountAllocatedBuffers:=NewCount; end; fCurrentDestinationVertexBufferPointer:=@fCurrentFillBuffer^.fVertexBuffers[fCurrentVulkanBufferIndex][0]; fCurrentDestinationIndexBufferPointer:=@fCurrentFillBuffer^.fIndexBuffers[fCurrentVulkanBufferIndex][0]; fCurrentFillBuffer^.fVertexBufferSizes[fCurrentVulkanBufferIndex]:=0; fCurrentFillBuffer^.fIndexBufferSizes[fCurrentVulkanBufferIndex]:=0; end; procedure TpvCanvas.EnsureSufficientReserveUsableSpace(const aCountVertices,aCountIndices:TpvInt32); const UntilCountVertices=SizeOf(TpvCanvasVertexBuffer) div SizeOf(TpvCanvasVertex); UntilCountIndices=SizeOf(TpvCanvasIndexBuffer) div SizeOf(TpvUInt32); begin if ((fCurrentVulkanVertexBufferOffset+fCurrentCountVertices+aCountVertices)>=UntilCountVertices) or ((fCurrentVulkanIndexBufferOffset+fCurrentCountIndices+aCountIndices)>=UntilCountIndices) then begin Flush; GetNextDestinationVertexBuffer; end; end; function TpvCanvas.AddVertex(const aPosition:TpvVector2;const aTexCoord:TpvVector3;const aColor:TpvVector4):TpvInt32; var Vertex:PpvCanvasVertex; begin result:=fCurrentCountVertices; Vertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices]; inc(fCurrentCountVertices); Vertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*aPosition,fState.fZPosition); Vertex^.TextureCoord:=aTexCoord; Vertex^.Color.r:=aColor.r; Vertex^.Color.g:=aColor.g; Vertex^.Color.b:=aColor.b; Vertex^.Color.a:=aColor.a; Vertex^.State:=GetVertexState; Vertex^.ClipRect:=fState.fClipRect; end; function TpvCanvas.AddIndex(const aVertexIndex:TpvInt32):TpvInt32; begin result:=fCurrentCountIndices; fCurrentDestinationIndexBufferPointer^[result]:=aVertexIndex; inc(fCurrentCountIndices); end; function TpvCanvas.ClipCheck(const aX0,aY0,aX1,aY1:TpvFloat):boolean; const Threshold=1e-6; begin result:=(fState.fClipRect.LeftTop.x<=(aX1+Threshold)) and (aX0<=(fState.fClipRect.RightBottom.x+Threshold)) and (fState.fClipRect.LeftTop.y<=(aY1+Threshold)) and (aY0<=(fState.fClipRect.RightBottom.y+Threshold)); end; procedure TpvCanvas.ExecuteUpload(const aVulkanTransferQueue:TpvVulkanQueue;const aVulkanTransferCommandBuffer:TpvVulkanCommandBuffer;const aVulkanTransferCommandBufferFence:TpvVulkanFence;const aBufferIndex:TpvInt32); var Index:TpvInt32; CurrentBuffer:PpvCanvasBuffer; VulkanBuffer:TpvVulkanBuffer; begin if (aBufferIndex>=0) and (aBufferIndex<fCountBuffers) then begin CurrentBuffer:=@fVulkanCanvasBuffers[aBufferIndex]; if assigned(CurrentBuffer) and (CurrentBuffer^.fCountUsedBuffers>0) then begin while TPasMPInterlocked.CompareExchange(CurrentBuffer^.fSpinLock,-1,0)<>0 do begin end; try for Index:=0 to CurrentBuffer^.fCountUsedBuffers-1 do begin if CurrentBuffer^.fVertexBufferSizes[Index]>0 then begin VulkanBuffer:=CurrentBuffer^.fVulkanVertexBuffers[Index]; if not assigned(VulkanBuffer) then begin if fDevice.MemoryManager.CompleteTotalMemoryMappable then begin VulkanBuffer:=TpvVulkanBuffer.Create(fDevice, SizeOf(TpvCanvasVertexBuffer), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT), TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), 0, 0, 0, 0, 0, 0, [TpvVulkanBufferFlag.PersistentMapped] ); end else begin VulkanBuffer:=TpvVulkanBuffer.Create(fDevice, SizeOf(TpvCanvasVertexBuffer), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), 0, 0, TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT), 0, 0, 0, 0, [] ); end; CurrentBuffer^.fVulkanVertexBuffers[Index]:=VulkanBuffer; end; if assigned(VulkanBuffer) then begin if fDevice.MemoryManager.CompleteTotalMemoryMappable then begin VulkanBuffer.UploadData(aVulkanTransferQueue, aVulkanTransferCommandBuffer, aVulkanTransferCommandBufferFence, CurrentBuffer^.fVertexBuffers[Index,0], 0, CurrentBuffer^.fVertexBufferSizes[Index], TpvVulkanBufferUseTemporaryStagingBufferMode.No); end else begin fDevice.MemoryStaging.Upload(aVulkanTransferQueue, aVulkanTransferCommandBuffer, aVulkanTransferCommandBufferFence, CurrentBuffer^.fVertexBuffers[Index,0], VulkanBuffer, 0, CurrentBuffer^.fVertexBufferSizes[Index]); end; end; end; if CurrentBuffer^.fIndexBufferSizes[Index]>0 then begin VulkanBuffer:=CurrentBuffer^.fVulkanIndexBuffers[Index]; if not assigned(VulkanBuffer) then begin if fDevice.MemoryManager.CompleteTotalMemoryMappable then begin VulkanBuffer:=TpvVulkanBuffer.Create(fDevice, SizeOf(TpvCanvasIndexBuffer), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_INDEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT), TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), 0, 0, 0, 0, 0, 0, [TpvVulkanBufferFlag.PersistentMapped] ); end else begin VulkanBuffer:=TpvVulkanBuffer.Create(fDevice, SizeOf(TpvCanvasIndexBuffer), TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_INDEX_BUFFER_BIT), TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE), [], TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), 0, 0, TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT), 0, 0, 0, 0, [] ); end; CurrentBuffer^.fVulkanIndexBuffers[Index]:=VulkanBuffer; end; if assigned(VulkanBuffer) then begin if fDevice.MemoryManager.CompleteTotalMemoryMappable then begin VulkanBuffer.UploadData(aVulkanTransferQueue, aVulkanTransferCommandBuffer, aVulkanTransferCommandBufferFence, CurrentBuffer^.fIndexBuffers[Index,0], 0, CurrentBuffer^.fIndexBufferSizes[Index], TpvVulkanBufferUseTemporaryStagingBufferMode.No); end else begin fDevice.MemoryStaging.Upload(aVulkanTransferQueue, aVulkanTransferCommandBuffer, aVulkanTransferCommandBufferFence, CurrentBuffer^.fIndexBuffers[Index,0], VulkanBuffer, 0, CurrentBuffer^.fIndexBufferSizes[Index]); end; end; end; end; finally TPasMPInterlocked.Exchange(CurrentBuffer^.fSpinLock,0); end; { aVulkanCommandBuffer.MetaCmdMemoryBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_HOST_BIT), TVkPipelineStageFlags(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), TVkAccessFlags(VK_ACCESS_HOST_WRITE_BIT), TVkAccessFlags(VK_ACCESS_UNIFORM_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT));//} end; end; end; procedure TpvCanvas.ExecuteDraw(const aVulkanCommandBuffer:TpvVulkanCommandBuffer;const aBufferIndex:TpvInt32); {$undef PasVulkanCanvasDoNotTrustGPUDriverAtDynamicStates} const Offsets:array[0..0] of TVkDeviceSize=(0); var Index,StartVertexIndex,TextureMode:TpvInt32; Descriptor:TpvCanvasVulkanDescriptor; BlendingMode:TpvCanvasBlendingMode; QueueItem:PpvCanvasQueueItem; OldQueueItemKind:TpvCanvasQueueItemKind; CurrentBuffer:PpvCanvasBuffer; VulkanVertexBuffer,VulkanIndexBuffer,OldVulkanVertexBuffer,OldVulkanIndexBuffer:TpvVulkanBuffer; OldScissor:TVkRect2D; TransformMatrix,FillMatrix:TpvMatrix4x4; ForceUpdate,ForceUpdatePushConstants,h:boolean; // DynamicOffset:TVkDeviceSize; begin h:=true; if assigned(fVulkanRenderPass) and ((aBufferIndex>=0) and (aBufferIndex<fCountBuffers)) then begin CurrentBuffer:=@fVulkanCanvasBuffers[aBufferIndex]; if assigned(CurrentBuffer) and (CurrentBuffer^.fCountQueueItems>0) then begin OldScissor.offset.x:=-$7fffffff; OldScissor.offset.y:=-$7fffffff; OldScissor.extent.Width:=$7fffffff; OldScissor.extent.Height:=$7fffffff; Descriptor:=nil; TransformMatrix:=TpvMatrix4x4.Null; FillMatrix:=TpvMatrix4x4.Null; OldQueueItemKind:=TpvCanvasQueueItemKind.None; ForceUpdate:=true; ForceUpdatePushConstants:=true; BlendingMode:=TpvCanvasBlendingMode.AdditiveBlending; TextureMode:=-1; OldVulkanVertexBuffer:=nil; OldVulkanIndexBuffer:=nil; for Index:=0 to CurrentBuffer^.fCountQueueItems-1 do begin QueueItem:=@CurrentBuffer^.fQueueItems[Index]; if OldQueueItemKind<>QueueItem^.Kind then begin OldQueueItemKind:=QueueItem^.Kind; ForceUpdate:=true; end; case QueueItem^.Kind of TpvCanvasQueueItemKind.Normal:begin VulkanVertexBuffer:=CurrentBuffer^.fVulkanVertexBuffers[QueueItem^.BufferIndex]; VulkanIndexBuffer:=CurrentBuffer^.fVulkanIndexBuffers[QueueItem^.BufferIndex]; if ForceUpdate then begin aVulkanCommandBuffer.CmdSetViewport(0,1,fPointerToViewport); end; if ForceUpdate or (BlendingMode<>QueueItem^.BlendingMode) or (TextureMode<>QueueItem^.TextureMode) then begin BlendingMode:=QueueItem^.BlendingMode; TextureMode:=QueueItem^.TextureMode; aVulkanCommandBuffer.CmdBindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS,fVulkanGraphicsPipelines[QueueItem^.BlendingMode,QueueItem^.TextureMode].Handle); {$ifdef PasVulkanCanvasDoNotTrustGPUDriverAtDynamicStates} OldScissor.offset.x:=-$7fffffff; OldScissor.offset.y:=-$7fffffff; OldScissor.extent.Width:=$7fffffff; OldScissor.extent.Height:=$7fffffff; {$endif} Descriptor:=nil; {$ifdef PasVulkanCanvasDoNotTrustGPUDriverAtDynamicStates} ForceUpdatePushConstants:=true; {$endif} end; if ForceUpdate or (Descriptor<>QueueItem^.Descriptor) then begin Descriptor:=QueueItem^.Descriptor; aVulkanCommandBuffer.CmdBindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS,fVulkanPipelineLayouts[QueueItem^.BlendingMode,QueueItem^.TextureMode].Handle,0,1,@Descriptor.fDescriptorSet.Handle,0,nil); {$ifdef PasVulkanCanvasDoNotTrustGPUDriverAtDynamicStates} ForceUpdatePushConstants:=true; {$endif} end; if ForceUpdate or ForceUpdatePushConstants or (TransformMatrix<>QueueItem^.PushConstants.TransformMatrix) or (FillMatrix<>QueueItem^.PushConstants.FillMatrix) then begin TransformMatrix:=QueueItem^.PushConstants.TransformMatrix; FillMatrix:=QueueItem^.PushConstants.FillMatrix; aVulkanCommandBuffer.CmdPushConstants(fVulkanPipelineLayouts[BlendingMode,TextureMode].Handle, TVkShaderStageFlags(VK_SHADER_STAGE_VERTEX_BIT) or TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT), 0, SizeOf(TpvCanvasPushConstants), @QueueItem^.PushConstants); end; if ForceUpdate or (OldScissor.offset.x<>QueueItem^.Scissor.offset.x) or (OldScissor.offset.y<>QueueItem^.Scissor.offset.y) or (OldScissor.extent.Width<>QueueItem^.Scissor.extent.Width) or (OldScissor.extent.Height<>QueueItem^.Scissor.extent.Height) then begin OldScissor:=QueueItem^.Scissor; aVulkanCommandBuffer.CmdSetScissor(0,1,@QueueItem^.Scissor); end; if ForceUpdate or (OldVulkanVertexBuffer<>VulkanVertexBuffer) then begin OldVulkanVertexBuffer:=VulkanVertexBuffer; aVulkanCommandBuffer.CmdBindVertexBuffers(0,1,@VulkanVertexBuffer.Handle,@Offsets); end; if ForceUpdate or (OldVulkanIndexBuffer<>VulkanIndexBuffer) then begin OldVulkanIndexBuffer:=VulkanIndexBuffer; aVulkanCommandBuffer.CmdBindIndexBuffer(VulkanIndexBuffer.Handle,0,VK_INDEX_TYPE_UINT32); end; aVulkanCommandBuffer.CmdDrawIndexed(QueueItem^.CountIndices,1,QueueItem^.StartIndexIndex,QueueItem^.StartVertexIndex,0); { DynamicOffset:=QueueItem^.StartVertexIndex*SizeOf(TpvCanvasVertex); aVulkanCommandBuffer.CmdBindVertexBuffers(0,1,@VulkanVertexBuffer.Handle,@DynamicOffset); aVulkanCommandBuffer.CmdBindIndexBuffer(VulkanIndexBuffer.Handle,QueueItem^.StartIndexIndex*SizeOf(TpvUInt32),VK_INDEX_TYPE_UINT32); aVulkanCommandBuffer.CmdDrawIndexed(QueueItem^.CountIndices,1,0,0,0);} ForceUpdate:=false; ForceUpdatePushConstants:=false; end; TpvCanvasQueueItemKind.Hook:begin if assigned(QueueItem^.Hook) then begin QueueItem^.Hook(QueueItem^.HookData,aVulkanCommandBuffer,aBufferIndex); end; ForceUpdate:=true; end; else {TpvCanvasQueueItemKind.None:}begin ForceUpdate:=true; end; end; end; CurrentBuffer^.fCountQueueItems:=0; CurrentBuffer^.fCountUsedBuffers:=0; end; end; end; function TpvCanvas.Push:TpvCanvas; var NewState:TpvCanvasState; begin NewState:=TpvCanvasState.Create; NewState.Assign(fState); fStateStack.Push(TpvCanvasState(TObject(TPasMPInterlocked.Exchange(TObject(fState),TObject(NewState))))); result:=self; end; function TpvCanvas.Pop:TpvCanvas; var PeekState:TpvCanvasState; begin PeekState:=fStateStack.Peek; if assigned(PeekState) then begin if (assigned(fCurrentFillBuffer) and (fCurrentCountVertices>0)) and ({(fState.fFillStyle<>PeekState.fFillStyle) or (fState.fFillWrapMode<>PeekState.fFillWrapMode) or} (fState.fBlendingMode<>PeekState.fBlendingMode) or (fState.fScissor.offset.x<>PeekState.fScissor.offset.x) or (fState.fScissor.offset.y<>PeekState.fScissor.offset.y) or (fState.fScissor.extent.width<>PeekState.fScissor.extent.width) or (fState.fScissor.extent.height<>PeekState.fScissor.extent.height) or (fState.fProjectionMatrix<>PeekState.fProjectionMatrix) or (fState.fViewMatrix<>PeekState.fViewMatrix) or (fState.fFillMatrix<>PeekState.fFillMatrix) or (fState.fTexture<>PeekState.fTexture) or (fState.fAtlasTexture<>PeekState.fAtlasTexture) or (fState.fGUIElementMode<>PeekState.fGUIElementMode)) then begin Flush; end; TpvCanvasState(TObject(TPasMPInterlocked.Exchange(TObject(fState),TObject(fStateStack.Extract)))).Free; end else begin Assert(false); end; result:=self; end; function TpvCanvas.Hook(const aHook:TpvCanvasHook;const aData:TpvPointer):TpvCanvas; var QueueItemIndex:TpvInt32; QueueItem:PpvCanvasQueueItem; begin if assigned(aHook) then begin Flush; QueueItemIndex:=fCurrentFillBuffer^.fCountQueueItems; inc(fCurrentFillBuffer^.fCountQueueItems); if length(fCurrentFillBuffer^.fQueueItems)<fCurrentFillBuffer^.fCountQueueItems then begin SetLength(fCurrentFillBuffer^.fQueueItems,fCurrentFillBuffer^.fCountQueueItems*2); end; QueueItem:=@fCurrentFillBuffer^.fQueueItems[QueueItemIndex]; QueueItem^.Kind:=TpvCanvasQueueItemKind.Hook; QueueItem^.Hook:=aHook; QueueItem^.HookData:=aData; end; result:=self; end; function TpvCanvas.DrawSprite(const aSprite:TpvSprite;const aSrc,aDest:TpvRect):TpvCanvas; const MinA=1.0/65536.0; SrcRectPositionComponents:array[boolean,0..1,0..3] of TpvInt32=(((0,2,2,0), (1,1,3,3)), ((2,2,0,0), (1,3,3,1))); DestRectPositionComponents:array[0..1,0..3] of TpvInt32=((0,2,2,0), (1,1,3,3)); var IntersectedRect,DestRect,SrcRect:TpvRect; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; Index:TpvInt32; TemporaryVector:PpvVector2; ScaleTemporaryVector:TpvVector2; Vertex:PpvCanvasVertex; VertexIndex:PpvUInt32; SpriteAtlasArrayTexture:TpvSpriteAtlasArrayTexture; begin result:=self; if ((fState.fBlendingMode<>TpvCanvasBlendingMode.None) and (abs(fState.fColor.a)<MinA)) or (aSrc.Right<aSprite.TrimmedOffset.x) or (aSrc.Bottom<aSprite.TrimmedOffset.y) or (aSprite.TrimmedRect.Right<aSrc.Left) or (aSprite.TrimmedRect.Bottom<aSrc.Top) then begin exit; end; if aSprite.SignedDistanceField then begin fInternalRenderingMode:=TpvCanvasRenderingMode.SignedDistanceField; fSignedDistanceFieldVariant:=aSprite.SignedDistanceFieldVariant; end else begin fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; fSignedDistanceFieldVariant:=TpvSignedDistanceField2DVariant(TpvUInt8(0)); end; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; VertexState:=GetVertexState; SetGUIElementMode(false); SetAtlasTexture(aSprite.ArrayTexture); SpriteAtlasArrayTexture:=TpvSpriteAtlasArrayTexture(fState.fAtlasTexture); if (length(aSprite.TrimmedHullVectors)>2) and (not aSprite.Rotated) and SameValue(aSrc.Left,0.0) and SameValue(aSrc.Top,0.0) and SameValue(aSrc.Right,aSprite.Width) and SameValue(aSrc.Bottom,aSprite.Height) then begin EnsureSufficientReserveUsableSpace(length(aSprite.TrimmedHullVectors),(length(aSprite.TrimmedHullVectors)-2)*3); for Index:=2 to length(aSprite.TrimmedHullVectors)-1 do begin fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+(Index-1); fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+Index; inc(fCurrentCountIndices,3); end; ScaleTemporaryVector:=aDest.Size/aSrc.Size; for Index:=0 to length(aSprite.TrimmedHullVectors)-1 do begin TemporaryVector:=@aSprite.TrimmedHullVectors[Index]; fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*aDest.LeftTop+(((TemporaryVector^+aSprite.TrimmedOffset)-aSrc.LeftTop)*ScaleTemporaryVector),fState.fZPosition); fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].TextureCoord:=TpvVector3.InlineableCreate((TemporaryVector^+aSprite.Offset)*SpriteAtlasArrayTexture.InverseSize,aSprite.Layer); fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].MetaInfo:=TpvVector4.Null; fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].Color:=VertexColor; fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].State:=VertexState; fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices].ClipRect:=fState.fClipSpaceClipRect; inc(fCurrentCountVertices); end; exit; end; IntersectedRect:=aSprite.TrimmedRect.GetIntersection(aSrc); {$if true} DestRect.Vector4:=aDest.Vector4+((IntersectedRect.Vector4-aSrc.Vector4)*(aDest.Size/aSrc.Size).xyxy); {$else} ScaleTemporaryVector:=aDest.Size/aSrc.Size; DestRect.LeftTop:=aDest.LeftTop+((TempRect.LeftTop-aSrc.LeftTop)*ScaleTemporaryVector); DestRect.RightBottom:=aDest.RightBottom+((TempRect.RightBottom-aSrc.RightBottom)*ScaleTemporaryVector); {$ifend} SrcRect.LeftTop:=(IntersectedRect.LeftTop-aSprite.TrimmedOffset)+aSprite.Offset; SrcRect.RightBottom:=SrcRect.LeftTop+IntersectedRect.Size; EnsureSufficientReserveUsableSpace(4,6); VertexIndex:=@fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices]; inc(fCurrentCountIndices,6); VertexIndex^:=fCurrentCountVertices+0; inc(VertexIndex); VertexIndex^:=fCurrentCountVertices+1; inc(VertexIndex); VertexIndex^:=fCurrentCountVertices+2; inc(VertexIndex); VertexIndex^:=fCurrentCountVertices+0; inc(VertexIndex); VertexIndex^:=fCurrentCountVertices+2; inc(VertexIndex); VertexIndex^:=fCurrentCountVertices+3; inc(VertexIndex); Vertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices]; inc(fCurrentCountVertices,4); for Index:=0 to 3 do begin Vertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*TpvVector2.InlineableCreate(DestRect.Components[DestRectPositionComponents[0,Index]], DestRect.Components[DestRectPositionComponents[1,Index]]), fState.fZPosition); Vertex^.Color:=VertexColor; Vertex^.TextureCoord:=TpvVector3.InlineableCreate(TpvVector2.InlineableCreate(SrcRect.Components[SrcRectPositionComponents[aSprite.Rotated,0,Index]], SrcRect.Components[SrcRectPositionComponents[aSprite.Rotated,1,Index]])*SpriteAtlasArrayTexture.InverseSize, aSprite.Layer); Vertex^.State:=VertexState; Vertex^.ClipRect:=fState.fClipSpaceClipRect; { PpvInt64(pointer(@Vertex^.MetaInfo.x))^:=0; PpvInt64(pointer(@Vertex^.MetaInfo.z))^:=0;} inc(Vertex); end; end; function TpvCanvas.DrawSprite(const aSprite:TpvSprite;const aSrc,aDest:TpvRect;const aOrigin:TpvVector2;const aRotationAngle:TpvFloat):TpvCanvas; var OldMatrix:TpvMatrix4x4; AroundPoint:TpvVector2; begin OldMatrix:=fState.fModelMatrix; try AroundPoint:=aDest.LeftTop+aOrigin+TpvVector2.InlineableCreate(aSprite.OffsetX,aSprite.OffsetY); fState.fModelMatrix:=((TpvMatrix4x4.CreateTranslation(-AroundPoint)* TpvMatrix4x4.CreateRotateZ(aRotationAngle))* TpvMatrix4x4.CreateTranslation(AroundPoint))* fState.fModelMatrix; result:=DrawSprite(aSprite,aSrc,aDest); finally fState.fModelMatrix:=OldMatrix; end; end; function TpvCanvas.DrawSprite(const aSprite:TpvSprite;const aPosition:TpvVector2):TpvCanvas; begin DrawSprite(aSprite, TpvRect.CreateAbsolute(0.0,0.0,aSprite.Width,aSprite.Height), TpvRect.CreateAbsolute(aPosition.x-(aSprite.OffsetX*aSprite.ScaleX),aPosition.y-(aSprite.OffsetY*aSprite.ScaleY), (aPosition.x-(aSprite.OffsetX*aSprite.ScaleX))+(aSprite.Width*aSprite.ScaleX),(aPosition.y-(aSprite.OffsetY*aSprite.ScaleY))+(aSprite.Height*aSprite.ScaleY))); result:=self; end; function TpvCanvas.DrawSprite(const aSprite:TpvSprite):TpvCanvas; begin DrawSprite(aSprite, TpvVector2.InlineableCreate(0.0,0.0)); result:=self; end; procedure TpvCanvas.DrawSpriteProc(const aSprite:TpvSprite;const aSrc,aDest:TpvRect); begin DrawSprite(aSprite,aSrc,aDest); end; function TpvCanvas.DrawNinePatchSprite(const aSprite:TpvSprite;const aNinePatch:TpvSpriteNinePatch;const aPosition,aSize:TpvVector2):TpvCanvas; var RowIndex,ColumnIndex:TpvInt32; NinePatchRegion:PpvSpriteNinePatchRegion; SrcRect,DestRect:TpvRect; x,y,StepX,StepY:TpvDouble; begin for RowIndex:=0 to 2 do begin for ColumnIndex:=0 to 2 do begin NinePatchRegion:=@aNinePatch.Regions[RowIndex,ColumnIndex]; SrcRect.Left:=NinePatchRegion^.Left; SrcRect.Top:=NinePatchRegion^.Top; SrcRect.Right:=SrcRect.Left+NinePatchRegion^.Width; SrcRect.Bottom:=SrcRect.Top+NinePatchRegion^.Height; case ColumnIndex of 0:begin DestRect.Left:=aPosition.x; DestRect.Right:=aPosition.x+aNinePatch.Regions[RowIndex,0].Width; end; 1:begin DestRect.Left:=aPosition.x+aNinePatch.Regions[RowIndex,0].Width; DestRect.Right:=(aPosition.x+aSize.x)-aNinePatch.Regions[RowIndex,2].Width; end; else begin DestRect.Left:=(aPosition.x+aSize.x)-aNinePatch.Regions[RowIndex,2].Width; DestRect.Right:=aPosition.x+aSize.x; end; end; case RowIndex of 0:begin DestRect.Top:=aPosition.y; DestRect.Bottom:=aPosition.y+aNinePatch.Regions[0,ColumnIndex].Height; end; 1:begin DestRect.Top:=aPosition.y+aNinePatch.Regions[0,ColumnIndex].Height; DestRect.Bottom:=(aPosition.y+aSize.y)-aNinePatch.Regions[2,ColumnIndex].Height; end; else begin DestRect.Top:=(aPosition.y+aSize.y)-aNinePatch.Regions[2,ColumnIndex].Height; DestRect.Bottom:=aPosition.y+aSize.y; end; end; case NinePatchRegion^.Mode of TpvSpriteNinePatchRegionMode.Stretch:begin DrawSprite(aSprite,SrcRect,DestRect); end; TpvSpriteNinePatchRegionMode.StretchXTileY:begin y:=DestRect.Top; while y<DestRect.Bottom do begin StepY:=Max(1e-4,Min(DestRect.Bottom-y,NinePatchRegion^.Height)); DrawSprite(aSprite, TpvRect.CreateAbsolute(SrcRect.Left,SrcRect.Top,SrcRect.Right,SrcRect.Top+StepY), TpvRect.CreateAbsolute(DestRect.Left,y,DestRect.Right,y+StepY)); y:=y+StepY; end; end; TpvSpriteNinePatchRegionMode.TileXStretchY:begin x:=DestRect.Left; while x<DestRect.Right do begin StepX:=Max(1e-4,Min(DestRect.Right-x,NinePatchRegion^.Width)); DrawSprite(aSprite, TpvRect.CreateAbsolute(SrcRect.Left,SrcRect.Top,SrcRect.Left+StepX,SrcRect.Bottom), TpvRect.CreateAbsolute(x,DestRect.Top,x+StepX,DestRect.Bottom)); x:=x+StepX; end; end; else {TpvSpriteNinePatchRegionMode.Tile:}begin y:=DestRect.Top; while y<DestRect.Bottom do begin StepY:=Max(1e-4,Min(DestRect.Bottom-y,NinePatchRegion^.Height)); x:=DestRect.Left; while x<DestRect.Right do begin StepX:=Max(1e-4,Min(DestRect.Right-x,NinePatchRegion^.Width)); DrawSprite(aSprite, TpvRect.CreateAbsolute(SrcRect.Left,SrcRect.Top,SrcRect.Left+StepX,SrcRect.Top+StepY), TpvRect.CreateAbsolute(x,y,x+StepX,y+StepY)); x:=x+StepX; end; y:=y+StepY; end; end; end; end; end; result:=self; end; function TpvCanvas.TextWidth(const aText:TpvUTF8String):TpvFloat; begin if assigned(fState.fFont) then begin result:=fState.fFont.TextWidth(aText,fState.fFontSize); end else begin result:=0.0; end; end; function TpvCanvas.TextHeight(const aText:TpvUTF8String):TpvFloat; begin if assigned(fState.fFont) then begin result:=fState.fFont.TextHeight(aText,fState.fFontSize); end else begin result:=0.0; end; end; function TpvCanvas.TextSize(const aText:TpvUTF8String):TpvVector2; begin if assigned(fState.fFont) then begin result:=fState.fFont.TextSize(aText,fState.fFontSize); end else begin result:=TpvVector2.InlineableCreate(0.0,0.0); end; end; function TpvCanvas.TextRowHeight(const aPercent:TpvFloat):TpvFloat; begin if assigned(fState.fFont) then begin result:=fState.fFont.RowHeight(aPercent,fState.fFontSize); end else begin result:=0.0; end; end; procedure TpvCanvas.TextGlyphRects(const aText:TpvUTF8String;const aPosition:TpvVector2;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); var Position,Size:TpvVector2; begin if assigned(fState.fFont) then begin Position:=aPosition; if fState.fTextHorizontalAlignment<>TpvCanvasTextHorizontalAlignment.Leading then begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=TextSize(aText); end else begin Size:=TpvVector2.InlineableCreate(TextWidth(aText),0.0); end; end else begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=TpvVector2.InlineableCreate(0.0,TextHeight(aText)); end else begin Size:=TpvVector2.InlineableCreate(0.0,0.0); end; end; case fState.fTextHorizontalAlignment of TpvCanvasTextHorizontalAlignment.Leading:begin // Do nothing end; TpvCanvasTextHorizontalAlignment.Center:begin Position.x:=Position.x-(Size.x*0.5); end; TpvCanvasTextHorizontalAlignment.Tailing:begin Position.x:=Position.x-Size.x; end; end; case fState.fTextVerticalAlignment of TpvCanvasTextVerticalAlignment.Leading:begin // Do nothing end; TpvCanvasTextVerticalAlignment.Middle:begin Position.y:=Position.y-(Size.y*0.5); end; TpvCanvasTextVerticalAlignment.Tailing:begin Position.y:=Position.y-Size.y; end; end; fState.fFont.GetTextGlyphRects(aText,Position,fState.fFontSize,aTextGlyphRects,aCountTextGlyphRects); end; end; procedure TpvCanvas.TextGlyphRects(const aText:TpvUTF8String;const aX,aY:TpvFloat;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); begin TextGlyphRects(aText,TpvVector2.InlineableCreate(aX,aY),aTextGlyphRects,aCountTextGlyphRects); end; procedure TpvCanvas.TextGlyphRects(const aText:TpvUTF8String;var aTextGlyphRects:TpvCanvasTextGlyphRects;out aCountTextGlyphRects:TpvInt32); begin TextGlyphRects(aText,TpvVector2.Null,aTextGlyphRects,aCountTextGlyphRects); end; function TpvCanvas.TextGlyphRects(const aText:TpvUTF8String;const aPosition:TpvVector2):TpvCanvasTextGlyphRects; var CountTextGlyphRects:TpvInt32; begin result:=nil; CountTextGlyphRects:=0; try TextGlyphRects(aText,aPosition,result,CountTextGlyphRects); finally SetLength(result,CountTextGlyphRects); end; end; function TpvCanvas.TextGlyphRects(const aText:TpvUTF8String;const aX,aY:TpvFloat):TpvCanvasTextGlyphRects; begin result:=TextGlyphRects(aText,TpvVector2.InlineableCreate(aX,aY)); end; function TpvCanvas.TextGlyphRects(const aText:TpvUTF8String):TpvCanvasTextGlyphRects; begin result:=TextGlyphRects(aText,TpvVector2.Null); end; function TpvCanvas.DrawTextCodePoint(const aTextCodePoint:TpvUInt32;const aPosition:TpvVector2):TpvCanvas; var Position,Size:TpvVector2; begin if assigned(fState.fFont) then begin Position:=aPosition; if fState.fTextHorizontalAlignment<>TpvCanvasTextHorizontalAlignment.Leading then begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=fState.fFont.CodePointSize(aTextCodePoint,fState.fFontSize); end else begin Size:=TpvVector2.InlineableCreate(fState.fFont.CodePointWidth(aTextCodePoint,fState.fFontSize),0.0); end; end else begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=TpvVector2.InlineableCreate(0.0,fState.fFont.CodePointHeight(aTextCodePoint,fState.fFontSize)); end else begin Size:=TpvVector2.InlineableCreate(0.0,0.0); end; end; case fState.fTextHorizontalAlignment of TpvCanvasTextHorizontalAlignment.Leading:begin // Do nothing end; TpvCanvasTextHorizontalAlignment.Center:begin Position.x:=Position.x-(Size.x*0.5); end; TpvCanvasTextHorizontalAlignment.Tailing:begin Position.x:=Position.x-Size.x; end; end; case fState.fTextVerticalAlignment of TpvCanvasTextVerticalAlignment.Leading:begin // Do nothing end; TpvCanvasTextVerticalAlignment.Middle:begin Position.y:=Position.y-(Size.y*0.5); end; TpvCanvasTextVerticalAlignment.Tailing:begin Position.y:=Position.y-Size.y; end; end; fState.fFont.DrawCodePoint(self,aTextCodePoint,Position,fState.fFontSize); end; result:=self; end; function TpvCanvas.DrawTextCodePoint(const aTextCodePoint:TpvUInt32;const aX,aY:TpvFloat):TpvCanvas; begin result:=DrawTextCodePoint(aTextCodePoint,TpvVector2.InlineableCreate(aX,aY)); end; function TpvCanvas.DrawTextCodePoint(const aTextCodePoint:TpvUInt32):TpvCanvas; begin result:=DrawTextCodePoint(aTextCodePoint,TpvVector2.InlineableCreate(0.0,0.0)); end; function TpvCanvas.DrawText(const aText:TpvUTF8String;const aPosition:TpvVector2):TpvCanvas; var Position,Size:TpvVector2; begin if assigned(fState.fFont) then begin Position:=aPosition; if fState.fTextHorizontalAlignment<>TpvCanvasTextHorizontalAlignment.Leading then begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=TextSize(aText); end else begin Size:=TpvVector2.InlineableCreate(TextWidth(aText),0.0); end; end else begin if fState.fTextVerticalAlignment<>TpvCanvasTextVerticalAlignment.Leading then begin Size:=TpvVector2.InlineableCreate(0.0,TextHeight(aText)); end else begin Size:=TpvVector2.InlineableCreate(0.0,0.0); end; end; case fState.fTextHorizontalAlignment of TpvCanvasTextHorizontalAlignment.Leading:begin // Do nothing end; TpvCanvasTextHorizontalAlignment.Center:begin Position.x:=Position.x-(Size.x*0.5); end; TpvCanvasTextHorizontalAlignment.Tailing:begin Position.x:=Position.x-Size.x; end; end; case fState.fTextVerticalAlignment of TpvCanvasTextVerticalAlignment.Leading:begin // Do nothing end; TpvCanvasTextVerticalAlignment.Middle:begin Position.y:=Position.y-(Size.y*0.5); end; TpvCanvasTextVerticalAlignment.Tailing:begin Position.y:=Position.y-Size.y; end; end; fState.fFont.Draw(self,aText,Position,fState.fFontSize); end; result:=self; end; function TpvCanvas.DrawText(const aText:TpvUTF8String;const aX,aY:TpvFloat):TpvCanvas; begin result:=DrawText(aText,TpvVector2.InlineableCreate(aX,aY)); end; function TpvCanvas.DrawText(const aText:TpvUTF8String):TpvCanvas; begin result:=DrawText(aText,TpvVector2.InlineableCreate(0.0,0.0)); end; function TpvCanvas.DrawFilledEllipse(const aCenter,aRadius:TpvVector2):TpvCanvas; var MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; begin SetGUIElementMode(false); SetAtlasTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=fState.fModelMatrix*aCenter; MetaInfo.zw:=aRadius; VertexState:=GetVertexState; EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(State.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aRadius.x,-aRadius.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomEllipse and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aRadius.x,-aRadius.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomEllipse and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aRadius.x,aRadius.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomEllipse and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aRadius.x,aRadius.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomEllipse and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); result:=self; end; function TpvCanvas.DrawFilledEllipse(const aCenterX,aCenterY,aRadiusX,aRadiusY:TpvFloat):TpvCanvas; begin result:=DrawFilledEllipse(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aRadiusX,aRadiusY)); end; function TpvCanvas.DrawFilledCircle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvas; var MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; begin SetGUIElementMode(false); SetAtlasTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=fState.fModelMatrix*aCenter; MetaInfo.z:=aRadius; MetaInfo.w:=0.0; VertexState:=GetVertexState; EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aRadius,-aRadius)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomCircle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aRadius,-aRadius)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomCircle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aRadius,aRadius)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomCircle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aRadius,aRadius)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomCircle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); result:=self; end; function TpvCanvas.DrawFilledCircle(const aCenterX,aCenterY,aRadius:TpvFloat):TpvCanvas; begin result:=DrawFilledCircle(TpvVector2.InlineableCreate(aCenterX,aCenterY),aRadius); end; function TpvCanvas.DrawFilledRectangle(const aCenter,aBounds:TpvVector2):TpvCanvas; var MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; begin SetGUIElementMode(false); SetAtlasTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=fState.fModelMatrix*aCenter; MetaInfo.zw:=aBounds; VertexState:=GetVertexState; EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aBounds.x,-aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aBounds.x,-aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(aBounds.x,aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aBounds.x,aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); result:=self; end; function TpvCanvas.DrawFilledRectangle(const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat):TpvCanvas; begin result:=DrawFilledRectangle(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aBoundX,aBoundY)); end; function TpvCanvas.DrawFilledRectangle(const aRect:TpvRect):TpvCanvas; var MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; begin SetGUIElementMode(false); SetAtlasTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=fState.fModelMatrix*((aRect.LeftTop+aRect.RightBottom)*0.5); MetaInfo.zw:=aRect.RightBottom-aRect.LeftTop; VertexState:=GetVertexState; EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*TpvVector2.InlineableCreate(aRect.Left,aRect.Top),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*TpvVector2.InlineableCreate(aRect.Right,aRect.Top),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*TpvVector2.InlineableCreate(aRect.Right,aRect.Bottom),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*TpvVector2.InlineableCreate(aRect.Left,aRect.Bottom),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((pcvvaomRectangle and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); result:=self; end; function TpvCanvas.DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aCenter,aBounds:TpvVector2;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; var MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; OldTexture:TObject; LocalModelMatrix:TpvMatrix4x4; begin SetGUIElementMode(false); SetAtlasTexture(nil); OldTexture:=GetTexture; SetTexture(aTexture); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=aCenter; MetaInfo.zw:=aBounds; if aRotationAngle<>0.0 then begin LocalModelMatrix:=((TpvMatrix4x4.CreateTranslation(-aCenter)* TpvMatrix4x4.CreateRotateZ(aRotationAngle))* TpvMatrix4x4.CreateTranslation(aCenter))* fState.ModelMatrix; end else begin LocalModelMatrix:=fState.ModelMatrix; end; VertexState:=GetVertexState and not ($f shl pvcvsFillStyleShift); EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(LocalModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aBounds.x,-aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,0.0,aTextureArrayLayer); CanvasVertex^.State:=VertexState or ((pcvvaomSolid and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(LocalModelMatrix*(aCenter+TpvVector2.InlineableCreate(aBounds.x,-aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(1.0,0.0,aTextureArrayLayer); CanvasVertex^.State:=VertexState or ((pcvvaomSolid and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(LocalModelMatrix*(aCenter+TpvVector2.InlineableCreate(aBounds.x,aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(1.0,1.0,aTextureArrayLayer); CanvasVertex^.State:=VertexState or ((pcvvaomSolid and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(LocalModelMatrix*(aCenter+TpvVector2.InlineableCreate(-aBounds.x,aBounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,1.0,aTextureArrayLayer); CanvasVertex^.State:=VertexState or ((pcvvaomSolid and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); SetTexture(OldTexture); result:=self; end; function TpvCanvas.DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; begin result:=DrawTexturedRectangle(aTexture,TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aBoundX,aBoundY),aRotationAngle,aTextureArrayLayer); end; function TpvCanvas.DrawTexturedRectangle(const aTexture:TpvVulkanTexture;const aRect:TpvRect;const aRotationAngle:TpvFloat=0.0;const aTextureArrayLayer:TpvInt32=0):TpvCanvas; begin result:=DrawTexturedRectangle(aTexture,aRect.LeftTop+((aRect.RightBottom-aRect.LeftTop)*0.5),(aRect.RightBottom-aRect.LeftTop)*0.5,aRotationAngle,aTextureArrayLayer); end; function TpvCanvas.DrawGUIElement(const aGUIElement:TVkInt32;const aFocused:boolean;const aMin,aMax,aMetaMin,aMetaMax:TpvVector2;const aMeta:TpvFloat=0.0):TpvCanvas; var Center,Bounds:TpvVector2; MetaInfo:TpvVector4; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; CanvasVertex:PpvCanvasVertex; OldTexture:TObject; begin Center:=(aMin+aMax)*0.5; Bounds:=(aMax-aMin)*0.5; SetGUIElementMode(true); SetAtlasTexture(nil); OldTexture:=GetTexture; SetTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; MetaInfo.xy:=fState.fModelMatrix*aMetaMin; MetaInfo.zw:=fState.fModelMatrix*aMetaMax; VertexState:=(GetVertexState and not ($f shl pvcvsFillStyleShift)) or ((TpvUInt32(aGUIElement) or (TpvUInt32(ord(aFocused) and 1) shl 7)) shl pvcvsObjectModeShift); EnsureSufficientReserveUsableSpace(4,6); CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+0]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(Center+TpvVector2.InlineableCreate(-Bounds.x,-Bounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,0.0,aMeta); CanvasVertex^.State:=VertexState; CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+1]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(Center+TpvVector2.InlineableCreate(Bounds.x,-Bounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,0.0,aMeta); CanvasVertex^.State:=VertexState; CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+2]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(Center+TpvVector2.InlineableCreate(Bounds.x,Bounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,0.0,aMeta); CanvasVertex^.State:=VertexState; CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+3]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(fState.fModelMatrix*(Center+TpvVector2.InlineableCreate(-Bounds.x,Bounds.y)),fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.InlineableCreate(0.0,0.0,aMeta); CanvasVertex^.State:=VertexState; CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=MetaInfo; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+0]:=fCurrentCountVertices+0; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+1]:=fCurrentCountVertices+1; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+2]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+3]:=fCurrentCountVertices+2; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+4]:=fCurrentCountVertices+3; fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+5]:=fCurrentCountVertices+0; inc(fCurrentCountVertices,4); inc(fCurrentCountIndices,6); SetTexture(OldTexture); result:=self; end; function TpvCanvas.DrawGUIElement(const aGUIElement:TVkInt32;const aFocused:boolean;const aMinX,aMinY,aMaxX,aMaxY,aMetaMinX,aMetaMinY,aMetaMaxX,aMetaMaxY:TpvFloat;const aMeta:TpvFloat=0.0):TpvCanvas; begin result:=DrawGUIElement(aGUIElement,aFocused,TpvVector2.InlineableCreate(aMinX,aMinY),TpvVector2.InlineableCreate(aMaxX,aMaxY),TpvVector2.InlineableCreate(aMetaMinX,aMetaMinY),TpvVector2.InlineableCreate(aMetaMaxX,aMetaMaxY),aMeta); end; function TpvCanvas.DrawShape(const aShape:TpvCanvasShape):TpvCanvas; var CachePartIndex,VertexIndex,IndexIndex:TpvInt32; CachePart:PpvCanvasShapeCachePart; CacheVertex:PpvCanvasShapeCacheVertex; CanvasVertex:PpvCanvasVertex; VertexColor:TpvHalfFloatVector4; VertexState:TpvUInt32; ModelMatrixIsIdentity:boolean; OffsetMatrix:TpvMatrix3x3; begin SetGUIElementMode(false); SetAtlasTexture(nil); fInternalRenderingMode:=TpvCanvasRenderingMode.Normal; VertexColor.r:=fState.fColor.r; VertexColor.g:=fState.fColor.g; VertexColor.b:=fState.fColor.b; VertexColor.a:=fState.fColor.a; VertexState:=GetVertexState; ModelMatrixIsIdentity:=fState.fModelMatrix=TpvMatrix4x4.Identity; OffsetMatrix:=fState.fModelMatrix.ToMatrix3x3; for CachePartIndex:=0 to aShape.fCountCacheParts-1 do begin CachePart:=@aShape.fCacheParts[CachePartIndex]; EnsureSufficientReserveUsableSpace(CachePart^.CountVertices,CachePart^.CountIndices); if ModelMatrixIsIdentity then begin for VertexIndex:=0 to CachePart^.CountVertices-1 do begin CacheVertex:=@aShape.fCacheVertices[CachePart^.BaseVertexIndex+VertexIndex]; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+VertexIndex]; CanvasVertex^.Position:=TpvVector3.InlineableCreate(CacheVertex^.Position+CacheVertex^.Offset,fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((CacheVertex^.ObjectMode and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=CacheVertex^.MetaInfo; end; end else begin for VertexIndex:=0 to CachePart^.CountVertices-1 do begin CacheVertex:=@aShape.fCacheVertices[CachePart^.BaseVertexIndex+VertexIndex]; CanvasVertex:=@fCurrentDestinationVertexBufferPointer^[fCurrentCountVertices+VertexIndex]; CanvasVertex^.Position:=TpvVector3.InlineableCreate((fState.fModelMatrix*CacheVertex^.Position)+ (OffsetMatrix*CacheVertex^.Offset), fState.fZPosition); CanvasVertex^.Color:=VertexColor; CanvasVertex^.TextureCoord:=TpvVector3.Null; CanvasVertex^.State:=VertexState or ((CacheVertex^.ObjectMode and $ff) shl pvcvsObjectModeShift); CanvasVertex^.ClipRect:=fState.fClipSpaceClipRect; CanvasVertex^.MetaInfo:=CacheVertex^.MetaInfo; case CacheVertex^.ObjectMode of pcvvaomRoundLineCapCircle:begin CanvasVertex^.MetaInfo.xy:=fState.fModelMatrix*CanvasVertex^.MetaInfo.xy; end; pcvvaomRoundLine:begin CanvasVertex^.MetaInfo.xy:=fState.fModelMatrix*CanvasVertex^.MetaInfo.xy; CanvasVertex^.MetaInfo.zw:=fState.fModelMatrix*CanvasVertex^.MetaInfo.zw; end; end; end; end; for IndexIndex:=0 to CachePart^.CountIndices-1 do begin fCurrentDestinationIndexBufferPointer^[fCurrentCountIndices+IndexIndex]:=(aShape.fCacheIndices[CachePart^.BaseIndexIndex+IndexIndex]-CachePart^.BaseVertexIndex)+fCurrentCountVertices; end; inc(fCurrentCountVertices,CachePart^.CountVertices); inc(fCurrentCountIndices,CachePart^.CountIndices); end; result:=self; end; function TpvCanvas.BeginPath:TpvCanvas; begin fState.fPath.BeginPath; result:=self; end; function TpvCanvas.EndPath:TpvCanvas; begin fState.fPath.EndPath; result:=self; end; function TpvCanvas.ClosePath:TpvCanvas; begin fState.fPath.ClosePath; result:=self; end; function TpvCanvas.MoveTo(const aP0:TpvVector2):TpvCanvas; begin fState.fPath.MoveTo(aP0); result:=self; end; function TpvCanvas.MoveTo(const aX,aY:TpvFloat):TpvCanvas; begin fState.fPath.MoveTo(TpvVector2.InlineableCreate(aX,aY)); result:=self; end; function TpvCanvas.LineTo(const aP0:TpvVector2):TpvCanvas; begin fState.fPath.LineTo(aP0); result:=self; end; function TpvCanvas.LineTo(const aX,aY:TpvFloat):TpvCanvas; begin fState.fPath.LineTo(TpvVector2.InlineableCreate(aX,aY)); result:=self; end; function TpvCanvas.QuadraticCurveTo(const aC0,aA0:TpvVector2):TpvCanvas; begin fState.fPath.QuadraticCurveTo(aC0,aA0); result:=self; end; function TpvCanvas.QuadraticCurveTo(const aCX,aCY,aAX,aAY:TpvFloat):TpvCanvas; begin fState.fPath.QuadraticCurveTo(TpvVector2.InlineableCreate(aCX,aCY),TpvVector2.InlineableCreate(aAX,aAY)); result:=self; end; function TpvCanvas.CubicCurveTo(const aC0,aC1,aA0:TpvVector2):TpvCanvas; begin fState.fPath.CubicCurveTo(aC0,aC1,aA0); result:=self; end; function TpvCanvas.CubicCurveTo(const aC0X,aC0Y,aC1X,aC1Y,aAX,aAY:TpvFloat):TpvCanvas; begin fState.fPath.CubicCurveTo(TpvVector2.InlineableCreate(aC0X,aC0Y),TpvVector2.InlineableCreate(aC1X,aC1Y),TpvVector2.InlineableCreate(aAX,aAY)); result:=self; end; function TpvCanvas.ArcTo(const aP0,aP1:TpvVector2;const aRadius:TpvFloat):TpvCanvas; begin fState.fPath.ArcTo(aP0,aP1,aRadius); result:=self; end; function TpvCanvas.ArcTo(const aP0X,aP0Y,aP1X,aP1Y,aRadius:TpvFloat):TpvCanvas; begin fState.fPath.ArcTo(TpvVector2.InlineableCreate(aP0X,aP0Y),TpvVector2.InlineableCreate(aP1X,aP1Y),aRadius); result:=self; end; function TpvCanvas.Arc(const aCenter:TpvVector2;const aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvas; begin fState.fPath.Arc(aCenter,aRadius,aAngle0,aAngle1,aClockwise); result:=self; end; function TpvCanvas.Arc(const aCenterX,aCenterY,aRadius,aAngle0,aAngle1:TpvFloat;const aClockwise:boolean):TpvCanvas; begin fState.fPath.Arc(TpvVector2.InlineableCreate(aCenterX,aCenterY),aRadius,aAngle0,aAngle1,aClockwise); result:=self; end; function TpvCanvas.Ellipse(const aCenter,aRadius:TpvVector2):TpvCanvas; begin fState.fPath.Ellipse(aCenter,aRadius); result:=self; end; function TpvCanvas.Ellipse(const aCenterX,aCenterY,aRadiusX,aRadiusY:TpvFloat):TpvCanvas; begin fState.fPath.Ellipse(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aRadiusX,aRadiusY)); result:=self; end; function TpvCanvas.Circle(const aCenter:TpvVector2;const aRadius:TpvFloat):TpvCanvas; begin fState.fPath.Circle(aCenter,aRadius); result:=self; end; function TpvCanvas.Circle(const aCenterX,aCenterY,aRadius:TpvFloat):TpvCanvas; begin fState.fPath.Circle(TpvVector2.InlineableCreate(aCenterX,aCenterY),aRadius); result:=self; end; function TpvCanvas.Rectangle(const aCenter,aBounds:TpvVector2):TpvCanvas; begin fState.fPath.Rectangle(aCenter,aBounds); result:=self; end; function TpvCanvas.Rectangle(const aCenterX,aCenterY,aBoundX,aBoundY:TpvFloat):TpvCanvas; begin fState.fPath.Rectangle(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aBoundX,aBoundY)); result:=self; end; function TpvCanvas.Rectangle(const aRect:TpvRect):TpvCanvas; begin fState.fPath.Rectangle(aRect.LeftTop+((aRect.RightBottom-aRect.LeftTop)*0.5),(aRect.RightBottom-aRect.LeftTop)*0.5); result:=self; end; function TpvCanvas.RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(aCenter,aBounds,aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight); result:=self; end; function TpvCanvas.RoundedRectangle(const aCenterX,aCenterY,aBoundX,aBoundY,aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aBoundX,aBoundY),aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight); result:=self; end; function TpvCanvas.RoundedRectangle(const aRect:TpvRect;const aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(aRect.LeftTop+((aRect.RightBottom-aRect.LeftTop)*0.5),(aRect.RightBottom-aRect.LeftTop)*0.5,aRadiusTopLeft,aRadiusTopRight,aRadiusBottomLeft,aRadiusBottomRight); result:=self; end; function TpvCanvas.RoundedRectangle(const aCenter,aBounds:TpvVector2;const aRadius:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(aCenter,aBounds,aRadius); result:=self; end; function TpvCanvas.RoundedRectangle(const aCenterX,aCenterY,aBoundX,aBoundY,aRadius:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(TpvVector2.InlineableCreate(aCenterX,aCenterY),TpvVector2.InlineableCreate(aBoundX,aBoundY),aRadius); result:=self; end; function TpvCanvas.RoundedRectangle(const aRect:TpvRect;const aRadius:TpvFloat):TpvCanvas; begin fState.fPath.RoundedRectangle(aRect.LeftTop+((aRect.RightBottom-aRect.LeftTop)*0.5),(aRect.RightBottom-aRect.LeftTop)*0.5,aRadius,aRadius,aRadius,aRadius); result:=self; end; function TpvCanvas.Stroke:TpvCanvas; begin fShape.StrokeFromPath(fState.fPath,fState,self); result:=DrawShape(fShape); end; function TpvCanvas.Fill:TpvCanvas; begin fShape.FillFromPath(fState.fPath,fState,self); result:=DrawShape(fShape); end; function TpvCanvas.GetStrokeShape:TpvCanvasShape; begin result:=TpvCanvasShape.Create; result.StrokeFromPath(fState.fPath,fState,self); end; function TpvCanvas.GetFillShape:TpvCanvasShape; begin result:=TpvCanvasShape.Create; result.FillFromPath(fState.fPath,fState,self); end; end.
unit uBinarySearchTest; interface uses DUnitX.TestFramework; type [TestFixture] TBinarySearchTest = class(TObject) public [Test] // [Ignore('Comment the "[Ignore]" statement to run the test')] procedure Should_return_minus_one_when_an_empty_array_is_searched; [Test] [Ignore] procedure Should_be_able_to_find_a_value_in_a_single_element_array_with_one_access; [Test] [Ignore] procedure Should_return_minus_one_if_a_value_is_less_than_the_element_in_a_single_element_array; [Test] [Ignore] procedure Should_return_minus_one_if_a_value_is_greater_than_the_element_in_a_single_element_array; [Test] [Ignore] procedure Should_find_an_element_in_a_longer_array; [Test] [Ignore] procedure Should_find_elements_at_the_beginning_of_an_array; [Test] [Ignore] procedure Should_find_elements_at_the_end_of_an_array; [Test] [Ignore] procedure Should_return_minus_one_if_a_value_is_less_than_all_elements_in_a_long_array; [Test] [Ignore] procedure Should_return_minus_one_if_a_value_is_greater_than_all_elements_in_a_long_array; end; implementation uses System.Generics.Collections, uBinarySearch; procedure TBinarySearchTest.Should_return_minus_one_when_an_empty_array_is_searched; var input: TArray<Integer>; begin SetLength(input, 0); Assert.AreEqual(-1, BinarySearch.Search(input, 6)); end; procedure TBinarySearchTest.Should_be_able_to_find_a_value_in_a_single_element_array_with_one_access; var input: TArray<integer>; begin SetLength(input, 1); input[0] := 6; Assert.AreEqual(0, BinarySearch.Search(input, 6)); end; procedure TBinarySearchTest.Should_return_minus_one_if_a_value_is_less_than_the_element_in_a_single_element_array; var input: TArray<integer>; begin SetLength(input, 1); input[0] := 94; Assert.AreEqual(-1, BinarySearch.Search(input, 6)); end; procedure TBinarySearchTest.Should_return_minus_one_if_a_value_is_greater_than_the_element_in_a_single_element_array; var input: TArray<integer>; begin SetLength(input, 1); input[0] := 94; Assert.AreEqual(-1, BinarySearch.Search(input, 602)); end; procedure TBinarySearchTest.Should_find_an_element_in_a_longer_array; var inputList: TList<integer>; begin inputList := TList<integer>.Create; inputList.AddRange([6, 67, 123, 345, 456, 457, 490, 2002, 54321, 54322]); Assert.AreEqual(7, BinarySearch.Search(inputList.ToArray, 2002)); end; procedure TBinarySearchTest.Should_find_elements_at_the_beginning_of_an_array; var inputList: TList<integer>; begin inputList := TList<integer>.Create; inputList.AddRange([6, 67, 123, 345, 456, 457, 490, 2002, 54321, 54322]); Assert.AreEqual(0, BinarySearch.Search(inputList.ToArray, 6)); end; procedure TBinarySearchTest.Should_find_elements_at_the_end_of_an_array; var inputList: TList<integer>; begin inputList := TList<integer>.Create; inputList.AddRange([6, 67, 123, 345, 456, 457, 490, 2002, 54321, 54322]); Assert.AreEqual(9, BinarySearch.Search(inputList.ToArray, 54322)); end; procedure TBinarySearchTest.Should_return_minus_one_if_a_value_is_less_than_all_elements_in_a_long_array; var inputList: TList<integer>; begin inputList := TList<integer>.Create; inputList.AddRange([6, 67, 123, 345, 456, 457, 490, 2002, 54321, 54322]); Assert.AreEqual(-1, BinarySearch.Search(inputList.ToArray, 2)); end; procedure TBinarySearchTest.Should_return_minus_one_if_a_value_is_greater_than_all_elements_in_a_long_array; var inputList: TList<integer>; begin inputList := TList<integer>.Create; inputList.AddRange([6, 67, 123, 345, 456, 457, 490, 2002, 54321, 54322]); Assert.AreEqual(-1, BinarySearch.Search(inputList.ToArray, 54323)); end; initialization TDUnitX.RegisterTestFixture(TBinarySearchTest); end.
unit uTorrentThreads; interface uses Windows, Classes, SySUtils, Messages, Dialogs, MMSystem, Forms, uTasks, uObjects, Graphics, PluginManager, PluginApi; type TLoadTorrent = class(TThread) public constructor Create(CreateSuspended: Boolean; P: Pointer; CalculateThread: Boolean); private DataTask: TTask; procedure GetInGeted(GetedData: WideString); procedure AfterLoad; procedure UpdatePieces; protected procedure Execute; override; end; TSeedingThread = class(TThread) public constructor Create(CreateSuspended: Boolean; P: Pointer; CalculateThread: Boolean); private DataTask: TTask; procedure GetInGeted(GetedData: WideString); protected procedure Execute; override; end; implementation uses uMainForm; procedure GetDirSize(const aPath: string; var SizeDir: Int64); var SR: TSearchRec; tPath: string; begin tPath := IncludeTrailingBackSlash(aPath); if FindFirst(tPath + '*.*', faAnyFile, SR) = 0 then begin try repeat if (SR.Name = '.') or (SR.Name = '..') then Continue; if (SR.Attr and faDirectory) <> 0 then begin GetDirSize(tPath + SR.Name, SizeDir); Continue; end; SizeDir := SizeDir + (SR.FindData.nFileSizeHigh * 4294967296 { shl 32 } ) + SR.FindData.nFileSizeLow; until FindNext(SR) <> 0; finally SySUtils.FindClose(SR); end; end; end; function SizeFile(s: string): Int64; var SearchRec: _WIN32_FIND_DATAW; begin FindFirstFile(pchar(s), SearchRec); // result := (SearchRec.nFileSizeHigh shl 32) + (SearchRec.nFileSizeLow); // result := (SearchRec.nFileSizeHigh * (MAXDWORD+1)) + (SearchRec.nFileSizeLow); result := (SearchRec.nFileSizeHigh * 4294967296) + (SearchRec.nFileSizeLow); end; constructor TLoadTorrent.Create(CreateSuspended: Boolean; P: Pointer; CalculateThread: Boolean); begin FreeOnTerminate := false; DataTask := P; DataTask.StartedLoadTorrentThread := true; inherited Create(CreateSuspended); end; procedure TLoadTorrent.Execute; var X, X2: Integer; BTPlugin: IBTServicePlugin; BTPluginProgressive: IBTServicePluginProgressive; DataTorrentSL: TStringList; DataTorrent: WideString; GetedData: WideString; FindTorrent: Boolean; FindProgressiveInterface: Boolean; Load: Boolean; StateStr: String; State: Integer; SizeNow: Int64; OldSize: Int64; FilesSize: Int64; BTAddSeeding: IBTServiceAddSeeding; DataList: TStringList; begin FindTorrent := false; FindProgressiveInterface := false; Load := false; if terminated then exit; EnterCriticalSection(TorrentSection); try for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTServicePlugin, BTPlugin)) then begin if StrToBool(BTPlugin.FindTorrent(DataTask.HashValue)) then begin FindTorrent := true; break; end; end; end; finally LeaveCriticalSection(TorrentSection); end; EnterCriticalSection(TorrentSection); try if not terminated then for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTServicePluginProgressive, BTPluginProgressive)) then begin FindProgressiveInterface := true; break; end; end; finally LeaveCriticalSection(TorrentSection); end; if not terminated then if (DataTask.Status <> tsProcessing) and (DataTask.Status <> tsSeeding) and (DataTask.Status <> tsLoading) and (DataTask.Status <> tsBittorrentMagnetDiscovery) then if FindTorrent = false then begin EnterCriticalSection(TorrentSection); try if not terminated then for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTServicePlugin, BTPlugin)) then begin if (trim(DataTask.TorrentFileName) = '') and (trim(DataTask.LinkToFile) <> '') then begin if (DataTask.ProgressiveDownload) and (FindProgressiveInterface) then begin DataTorrentSL := TStringList.Create; try DataTorrentSL.Insert(0, IntToStr(DataTask.ID)); DataTorrentSL.Insert(1, DataTask.LinkToFile); DataTorrentSL.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); DataTorrent := DataTorrentSL.Text; finally DataTorrentSL.Free; end; if not terminated then begin BTPluginProgressive.StartMagnetTorrentProgressive (DataTorrent); end; end else begin DataTorrentSL := TStringList.Create; try DataTorrentSL.Insert(0, IntToStr(DataTask.ID)); DataTorrentSL.Insert(1, DataTask.LinkToFile); DataTorrentSL.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); DataTorrent := DataTorrentSL.Text; finally DataTorrentSL.Free; end; if not terminated then begin BTPlugin.StartMagnetTorrent(DataTorrent); end; end; end else begin if (DataTask.ProgressiveDownload) and (FindProgressiveInterface) then begin if not terminated then begin DataTorrentSL := TStringList.Create; try DataTorrentSL.Insert(0, IntToStr(DataTask.ID)); DataTorrentSL.Insert(1, DataTask.TorrentFileName); DataTorrentSL.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); DataTorrent := DataTorrentSL.Text; finally DataTorrentSL.Free; end; if not terminated then begin BTPluginProgressive.StartTorrentProgressive (DataTorrent); end; end; end else begin DataTorrentSL := TStringList.Create; try DataTorrentSL.Insert(0, IntToStr(DataTask.ID)); DataTorrentSL.Insert(1, DataTask.TorrentFileName); DataTorrentSL.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); DataTorrent := DataTorrentSL.Text; finally DataTorrentSL.Free; end; if not terminated then begin FilesSize := 0; if DirectoryExists(DataTask.Directory + '\' + DataTask.FileName) then begin GetDirSize(DataTask.Directory + '\' + DataTask.FileName, FilesSize); end else if FileExists(DataTask.Directory + '\' + DataTask.FileName) then begin FilesSize := SizeFile(DataTask.Directory + '\' + DataTask.FileName); end; if (FilesSize > 0) and (FilesSize = DataTask.TotalSize) then begin for X2 := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X2], IBTServiceAddSeeding, BTAddSeeding)) then begin DataList := TStringList.Create; EnterCriticalSection(TorrentSection); try try DataList.Insert(0, IntToStr(DataTask.ID)); DataList.Insert(1, DataTask.TorrentFileName); DataList.Insert(2, ExcludeTrailingBackSlash(DataTask.Directory)); BTAddSeeding.AddSeeding(DataList.Text); except end; finally LeaveCriticalSection(TorrentSection); DataList.Free; end; break; end; end; TSeedingThread.Create(false, DataTask, false); DataTask.Status := tsSeeding; exit; end else begin BTPlugin.StartTorrent(DataTorrent); end; end; end; end; DataTask.Status := tsLoading; break; end; end; finally LeaveCriticalSection(TorrentSection); end; end; if DataTask.Status = tsStartProcess then begin EnterCriticalSection(TorrentSection); try try if not terminated then begin BTPlugin.ResumeTorrent(DataTask.HashValue, DataTask.Directory); end; except end; finally LeaveCriticalSection(TorrentSection); end; end; repeat if DataTask.Status = tsStoping then begin repeat EnterCriticalSection(TorrentSection); try try if not terminated then BTPlugin.StopTorrent(DataTask.HashValue); except end; finally LeaveCriticalSection(TorrentSection); end; try EnterCriticalSection(TorrentSection); try if not terminated then StateStr := BTPlugin.GetStatusTorrent(DataTask.HashValue); except end; finally LeaveCriticalSection(TorrentSection); end; try State := StrToInt(StateStr); except end; if State <> 10 then begin sleep(1000); EnterCriticalSection(TorrentSection); try try if not terminated then StateStr := BTPlugin.GetStatusTorrent(DataTask.HashValue); except end; finally LeaveCriticalSection(TorrentSection); end; try State := StrToInt(StateStr); except end; end; until (State = 10) or (terminated); DataTask.Speed := 0; DataTask.UploadSpeed := 0; AfterLoad; end else begin if (DataTask.Status = tsSeeding) or (DataTask.Status = tsUploading) then begin AfterLoad; Load := true; end else begin EnterCriticalSection(TorrentSection); try try if not terminated then GetedData := BTPlugin.GetInfoTorrent(DataTask.HashValue); except end; if not terminated then GetInGeted(GetedData); if not terminated then if FindProgressiveInterface then begin try DataTask.SizeProgressiveDownloaded := StrToInt64(BTPluginProgressive.SizeProgressiveDownloaded (DataTask.HashValue)); SizeNow := DataTask.SizeProgressiveDownloaded; except end; if DataTask.SizeProgressiveDownloaded > 0 then if SizeNow <> OldSize then begin OldSize := SizeNow; end; end; finally LeaveCriticalSection(TorrentSection); end; if DataTask.UpdatePiecesInfo then begin if not terminated then UpdatePieces; end; end; end; sleep(1000); until (DataTask.Status = tsStoped) or (Load) or (DataTask.Status = tsDeleted) or (terminated); DataTask.StartedLoadTorrentThread := false; end; procedure TLoadTorrent.UpdatePieces; var IBTPiecesInfo: IBTServicePluginPiecesInfo; StatusStr: string; StatusInt: Integer; X: Integer; PiecesInfo: WideString; procedure PiecesInfoInGeted(GetedData: WideString; DataTask: TTask); var GetedList: TStringList; GetedPieceList: TStringList; i, k: Integer; PieceInfo: TPieces; begin GetedList := TStringList.Create; try GetedList.Delimiter := ' '; GetedList.QuoteChar := '^'; GetedList.DelimitedText := GetedData; if DataTask.UpdatePiecesInfo then if assigned(DataTask.Pieces) then begin for i := 0 to GetedList.Count - 1 do begin if GetedList[i] <> '' then begin try GetedPieceList := TStringList.Create; try GetedPieceList.Delimiter := ' '; GetedPieceList.QuoteChar := '|'; GetedPieceList.DelimitedText := GetedList[i]; except end; for k := 0 to DataTask.Pieces.Count - 1 do begin if i = k then begin try TPieces(DataTask.Pieces.Items[k]).foffset := StrToInt64(GetedPieceList[0]); except end; try TPieces(DataTask.Pieces.Items[k]).fsize := StrToInt64(GetedPieceList[1]); except end; try TPieces(DataTask.Pieces.Items[k]).findex := StrToInt64(GetedPieceList[2]); except end; try TPieces(DataTask.Pieces.Items[k]).fprogress := StrToInt64(GetedPieceList[3]); except end; try DataTask.MPBar.SetPosition (TPieces(DataTask.Pieces.Items[k]).findex, TPieces(DataTask.Pieces.Items[k]).foffset + TPieces(DataTask.Pieces.Items[k]).fprogress, GraphColor, ProgressBackColor); except end; end; end; finally GetedPieceList.Free; end; end end end else begin DataTask.Pieces := TList.Create; DataTask.LastAddedIndex := 0; DataTask.MPBar.Clear; DataTask.MPBar.Visible := false; for i := 0 to GetedList.Count - 1 do begin if GetedList[i] <> '' then begin try PieceInfo := TPieces.Create; GetedPieceList := TStringList.Create; try GetedPieceList.Delimiter := ' '; GetedPieceList.QuoteChar := '|'; GetedPieceList.DelimitedText := GetedList[i]; except end; try PieceInfo.foffset := StrToInt64(GetedPieceList[0]); except end; try PieceInfo.fsize := StrToInt64(GetedPieceList[1]); except end; try PieceInfo.findex := StrToInt64(GetedPieceList[2]); except end; try PieceInfo.fprogress := StrToInt64(GetedPieceList[3]); except end; // if PieceInfo.findex = 1 then // begin // showmessage('PieceInfo.findex: ' + IntToStr(PieceInfo.findex) // + sLineBreak + 'PieceInfo.foffset: ' + // IntToStr(PieceInfo.foffset) + sLineBreak + // 'PieceInfo.fsize: ' + IntToStr(PieceInfo.fsize) + sLineBreak // + 'PieceInfo.fprogress: ' + IntToStr(PieceInfo.fprogress)); // end; // // if PieceInfo.findex = 200 then // begin // showmessage('PieceInfo.findex: ' + IntToStr(PieceInfo.findex) // + sLineBreak + 'PieceInfo.foffset: ' + // IntToStr(PieceInfo.foffset) + sLineBreak + // 'PieceInfo.fsize: ' + IntToStr(PieceInfo.fsize) + sLineBreak // + 'PieceInfo.fprogress: ' + IntToStr(PieceInfo.fprogress)); // end; // // if PieceInfo.findex = 500 then // begin // showmessage('PieceInfo.findex: ' + IntToStr(PieceInfo.findex) // + sLineBreak + 'PieceInfo.foffset: ' + // IntToStr(PieceInfo.foffset) + sLineBreak + // 'PieceInfo.fsize: ' + IntToStr(PieceInfo.fsize) + sLineBreak // + 'PieceInfo.fprogress: ' + IntToStr(PieceInfo.fprogress)); // end; PieceInfo.AddedSegment := false; try DataTask.MPBar.AddSegment(PieceInfo.foffset, PieceInfo.fsize, PieceInfo.foffset + PieceInfo.fprogress, GraphColor, ProgressBackColor); { DataTask.MPBar.AddSegment(PieceInfo.foffset, PieceInfo.fsize, PieceInfo.foffset + PieceInfo.fprogress, $00FBA900, clWindow); } // $ffffff PieceInfo.IndexSegment := DataTask.LastAddedIndex; inc(DataTask.LastAddedIndex); except end; PieceInfo.AddedSegment := true; with TasksList.LockList do try if assigned(DataTask.Pieces) then DataTask.Pieces.Add(PieceInfo); finally TasksList.UnlockList; end; finally GetedPieceList.Free; end; end; end; DataTask.MPBar.Visible := true; // showmessage('DataTask.LastAddedIndex: '+inttostr(DataTask.LastAddedIndex)); end; finally GetedList.Free; end; end; begin if DataTask.UpdatePiecesInfo = true then begin for X := 0 to Plugins.Count - 1 do begin if (Supports(Plugins[X], IBTServicePluginPiecesInfo, IBTPiecesInfo)) then begin try StatusStr := IBTPiecesInfo.CheckPiecesStatus(DataTask.HashValue); except end; if trim(StatusStr) = '' then StatusInt := 0 else begin try StatusInt := StrToInt(StatusStr); except end; end; if StatusInt = 0 then begin try IBTPiecesInfo.GetPiecesInfo(DataTask.HashValue); except end; end else if StatusInt = 3 then begin try PiecesInfo := IBTPiecesInfo.GetDataPieces(DataTask.HashValue); IBTPiecesInfo.ReleasePiecesThread(DataTask.HashValue); except end; end; if trim(PiecesInfo) <> '' then PiecesInfoInGeted(PiecesInfo, DataTask); end; end; end; end; procedure TLoadTorrent.GetInGeted(GetedData: WideString); var GetedList: TStringList; fsize: Int64; State: Integer; FileNameTorr: string; StateStr: string; begin GetedList := TStringList.Create; try try GetedList.Delimiter := ' '; GetedList.QuoteChar := '|'; GetedList.DelimitedText := (GetedData); except end; try FileNameTorr := GetedList[0]; DataTask.FileName := Utf8ToAnsi(ExtractFileName(FileNameTorr)); except end; try DataTask.LoadSize := StrToInt64(GetedList[1]); except end; try DataTask.UploadSize := StrToInt64(GetedList[2]); except end; try StateStr := GetedList[3]; StateStr := trim(StateStr); fsize := StrToInt64(StateStr); DataTask.TotalSize := fsize; except end; try DataTask.NumConnected := StrToInt(GetedList[4]); except end; try DataTask.NumConnectedSeeders := StrToInt(GetedList[5]); except end; try DataTask.NumConnectedLeechers := StrToInt(GetedList[6]); except end; try StateStr := GetedList[7]; StateStr := trim(StateStr); State := StrToInt(StateStr); if State = 0 then DataTask.Status := tsBittorrentMagnetDiscovery else if State = 1 then DataTask.Status := tsSeeding else if State = 2 then DataTask.Status := tsFileError else if State = 3 then DataTask.Status := tsAllocating else if State = 4 then DataTask.Status := tsFinishedAllocating else if State = 5 then DataTask.Status := tsRebuilding; if State = 6 then DataTask.Status := tsProcessing; if State = 7 then DataTask.Status := tsJustCompleted; if State = 8 then DataTask.Status := tsLoad; if State = 9 then DataTask.Status := tsLoading; if State = 10 then DataTask.Status := tsStoped; if State = 11 then DataTask.Status := tsLeechPaused; if State = 12 then DataTask.Status := tsLocalPaused; if State = 13 then DataTask.Status := tsCancelled; if State = 14 then DataTask.Status := tsQueuedSource; if State = 15 then DataTask.Status := tsUploading; except end; try DataTask.Speed := StrToInt(GetedList[8]); except end; try DataTask.UploadSpeed := StrToInt(GetedList[9]); except end; try // DataTask.HashValue := Utf8ToAnsi(GetedList[10]); except end; try DataTask.NumFiles := StrToInt(GetedList[11]); except end; try DataTask.NumAllSeeds := StrToInt(GetedList[12]); except end; finally GetedList.Free; end; end; constructor TSeedingThread.Create(CreateSuspended: Boolean; P: Pointer; CalculateThread: Boolean); begin FreeOnTerminate := false; DataTask := P; inherited Create(CreateSuspended); end; procedure TSeedingThread.Execute; var X: Integer; BTPlugin: IBTServicePlugin; FindTorrent: Boolean; GetedData: WideString; begin FindTorrent := false; EnterCriticalSection(TorrentSection); try if not terminated then for X := 0 to Plugins.Count - 1 do begin if not terminated then if (Supports(Plugins[X], IBTServicePlugin, BTPlugin)) then begin try if not terminated then begin try FindTorrent := StrToBool(BTPlugin.FindTorrent(DataTask.HashValue)); break; except end; end; except end; end; end; finally LeaveCriticalSection(TorrentSection); end; repeat if not terminated then if DataTask.Status = tsStoping then begin EnterCriticalSection(TorrentSection); try try BTPlugin.StopTorrent(DataTask.HashValue); except end; finally LeaveCriticalSection(TorrentSection); end; with TasksList.LockList do try try DataTask.Status := tsStoped; except end; finally TasksList.UnlockList; end; end else begin EnterCriticalSection(TorrentSection); try try if not terminated then GetedData := BTPlugin.GetInfoTorrent(DataTask.HashValue); except end; finally LeaveCriticalSection(TorrentSection); end; if not terminated then GetInGeted(GetedData); end; sleep(1000); until (DataTask.Status = tsStoped) or (DataTask.Status = tsDeleted) or (terminated); end; procedure TSeedingThread.GetInGeted(GetedData: WideString); var GetedList: TStringList; fsize: Int64; State: Integer; FileNameTorr: string; StateStr: string; begin GetedList := TStringList.Create; try try GetedList.Delimiter := ' '; GetedList.QuoteChar := '|'; GetedList.DelimitedText := (GetedData); except end; try FileNameTorr := GetedList[0]; DataTask.FileName := Utf8ToAnsi(ExtractFileName(FileNameTorr)); except end; try DataTask.LoadSize := StrToInt64(GetedList[1]); except end; try DataTask.UploadSize := StrToInt64(GetedList[2]); except end; try StateStr := GetedList[3]; StateStr := trim(StateStr); fsize := StrToInt64(StateStr); DataTask.TotalSize := fsize; except end; try DataTask.NumConnected := StrToInt(GetedList[4]); except end; try DataTask.NumConnectedSeeders := StrToInt(GetedList[5]); except end; try DataTask.NumConnectedLeechers := StrToInt(GetedList[6]); except end; try StateStr := GetedList[7]; StateStr := trim(StateStr); State := StrToInt(StateStr); if State = 0 then DataTask.Status := tsBittorrentMagnetDiscovery else if State = 1 then DataTask.Status := tsSeeding else if State = 2 then DataTask.Status := tsFileError else if State = 3 then DataTask.Status := tsAllocating else if State = 4 then DataTask.Status := tsFinishedAllocating else if State = 5 then DataTask.Status := tsRebuilding else if State = 6 then DataTask.Status := tsProcessing else if State = 7 then DataTask.Status := tsJustCompleted else if State = 8 then DataTask.Status := tsLoad else if State = 9 then DataTask.Status := tsLoading else if State = 10 then DataTask.Status := tsStoped else if State = 11 then DataTask.Status := tsLeechPaused else if State = 12 then DataTask.Status := tsLocalPaused else if State = 13 then DataTask.Status := tsCancelled else if State = 14 then DataTask.Status := tsQueuedSource else if State = 15 then DataTask.Status := tsUploading; except end; try DataTask.Speed := StrToInt(GetedList[8]); except end; try DataTask.UploadSpeed := StrToInt(GetedList[9]); except end; try // DataTask.HashValue := Utf8ToAnsi(GetedList[10]); except end; try DataTask.NumFiles := StrToInt(GetedList[11]); except end; try DataTask.NumAllSeeds := StrToInt(GetedList[12]); except end; finally GetedList.Free; end; end; procedure TLoadTorrent.AfterLoad; var i: Integer; begin /// ///////////////////// При ошибке без циклирования /////////////////////////// if (DataTask.Status = tsErroring) then begin DataTask.Status := tsError; end; /// //////////////////////// После остановки закачки //////////////////////////// if (DataTask.Status = tsStoping) then begin DataTask.Status := tsStoped; end; /// ///////////////////////////////////////////////////////////////////////////// /// ///////////////////// После завершения закачки ////////////////////////////// if (DataTask.Status = tsSeeding) or (DataTask.Status = tsUploading) then begin DataTask.TimeEnd := Now; try for i := 0 to DataTask.Pieces.Count - 1 do begin DataTask.MPBar.SetPosition(TPieces(DataTask.Pieces.Items[i]).findex, TPieces(DataTask.Pieces.Items[i]).foffset + TPieces(DataTask.Pieces.Items[i]).fsize, GraphColor, ProgressBackColor); end; except end; SeedingThreads.Add(TSeedingThread.Create(false, DataTask, false)); end; if (DataTask.Status = tsLoading) then begin DataTask.Status := tsLoad; end; end; end.
type vertex = record adj:array of integer; end; pos = record row,col:integer; end; chess_board = array of array of boolean; graph = array of vertex; node = record p: pos; next: ^node; end; queue = record head: ^node; tail: ^node; end; //queues procedure init(var q: queue); begin q.head := nil; q.tail := nil; end; procedure enqueue(var q: queue; p: pos); var n: ^node; begin new(n); n^.p := p; n^.next := nil; if q.head = nil then begin q.head := n; q.tail := n; end else begin q.tail^.next := n; // append to tail q.tail := n; end; end; function dequeue(var q: queue): pos; var p: ^node; begin dequeue := q.head^.p; p := q.head; q.head := q.head^.next; dispose(p); if q.head = nil then q.tail := nil; end; function isEmpty(q: queue): boolean; begin exit(q.head = nil); end; function get_distance(const board: chess_board; start, dest: pos): integer; const dx:array[1..8] of integer=(-2, -2, 2, 2, -1, 1, 1, -1); dy:array[1..8] of integer=(-1, 1, 1, -1, -2, -2, 2, 2); var dist: array of array of integer; dir:integer; p,t:pos; q: queue; width,height:integer; i, j: integer; row1,col1:integer; dist_counter:integer=1; visited:array of array of boolean; function valid(row,col:integer):boolean; begin exit((row>=1) and (row<height) and (col>=1) and (col<width)); end; begin init(q); width:=length(board[0]); height:=length(board); setLength(dist, height, width); setLength(visited, height, width); for i:=0 to high(dist) do for j:=0 to high(dist[0]) do dist[i,j]:=-1; enqueue(q,start); visited[start.row,start.col]:=true; dist[start.row,start.col]:=0; while not isEmpty(q) do begin p:=dequeue(q); for dir:=1 to 8 do begin row1:=p.row+dx[dir]; col1:=p.col+dy[dir]; if valid(row1, col1) and (not visited[row1][col1]) then begin { writeln('ROW: ',row1 , ', COL: ', col1, ' - DIST: ', dist_counter ); } t.row:=row1; t.col:=col1; enqueue(q,t); visited[row1][col1]:=true; dist[row1][col1]:=dist[p.row][p.col]+1; end; end; end; exit(dist[dest.row][dest.col]); end; var height,width:integer; start,dest:pos; board:chess_board; begin readln(height, width); setLength(board, height+1, width+1); readln(start.row, start.col); readln(dest.row, dest.col); writeln(get_distance(board, start, dest)); end.
unit URL; interface type TURL = class(TObject) private Furl :String; Fnamespace :String; Fambiente :Integer; FsalaoID :Integer; Fmetodo :String; procedure SetAmbiente(const Value: Integer); protected public function getURL :String; constructor Create(salaoID :Integer; metodo :String); destructor Destroy; override; published end; implementation uses SysUtils; const NAMESPACE_HOMOLOGACAO = 'http://apidev.salaovip.com.br/'; const NAMESPACE_PRODUCAO = 'http://api.salaovip.com.br/'; { TURL } constructor TURL.Create(salaoID: Integer; metodo: String); var lambiente :Integer; begin inherited Create; if salaoID = 8204 then lambiente := 0 else lambiente := 1; SetAmbiente(lambiente); FsalaoID := salaoID; Fmetodo := metodo; end; destructor TURL.Destroy; begin inherited; end; function TURL.getURL: String; begin Result := Fnamespace + 'salao/' + IntToStr(FsalaoID) + '/'+ Fmetodo ; end; procedure TURL.SetAmbiente(const Value: Integer); begin Fambiente := Value; if Fambiente = 0 then Fnamespace := NAMESPACE_HOMOLOGACAO else Fnamespace := NAMESPACE_PRODUCAO; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Image.JPEG; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$if defined(Darwin) or defined(CompileForWithPIC) or not defined(cpu386)} {$define PurePascal} {$ifend} interface uses SysUtils, Classes, Math, {$ifdef fpc} FPImage,FPReadJPEG,FPWriteJPEG, {$endif} {$ifdef fpc} dynlibs, {$else} Windows, {$endif} PasVulkan.Types; const JPEG_OUTPUT_BUFFER_SIZE=2048; JPEG_DC_LUMA_CODES=12; JPEG_AC_LUMA_CODES=256; JPEG_DC_CHROMA_CODES=12; JPEG_AC_CHROMA_CODES=256; JPEG_MAX_HUFFMAN_SYMBOLS=257; JPEG_MAX_HUFFMAN_CODE_SIZE=32; type EpvLoadJPEGImage=class(Exception); PpvJPEGHuffmanSymbolFrequency=^TpvJPEGHuffmanSymbolFrequency; TpvJPEGHuffmanSymbolFrequency=record Key,Index:TpvUInt32; end; PpvJPEGHuffmanSymbolFrequencies=^TpvJPEGHuffmanSymbolFrequencies; TpvJPEGHuffmanSymbolFrequencies=array[0..65536] of TpvJPEGHuffmanSymbolFrequency; PpvJPEGEncoderInt8Array=^TpvJPEGEncoderUInt8Array; TpvJPEGEncoderInt8Array=array[0..65535] of TpvInt8; PpvJPEGEncoderUInt8Array=^TpvJPEGEncoderUInt8Array; TpvJPEGEncoderUInt8Array=array[0..65535] of TpvUInt8; PpvJPEGEncoderInt16Array=^TpvJPEGEncoderInt16Array; TpvJPEGEncoderInt16Array=array[0..65535] of TpvInt16; PpvJPEGEncoderUInt16Array=^TpvJPEGEncoderUInt16Array; TpvJPEGEncoderUInt16Array=array[0..65535] of TpvUInt16; PpvJPEGEncoderInt32Array=^TpvJPEGEncoderInt32Array; TpvJPEGEncoderInt32Array=array[0..65535] of TpvInt32; PpvJPEGEncoderUInt32Array=^TpvJPEGEncoderUInt32Array; TpvJPEGEncoderUInt32Array=array[0..65535] of TpvUInt32; TpvJPEGEncoder=class private fQuality:TpvInt32; fTwoPass:LongBool; fNoChromaDiscrimination:LongBool; fCountComponents:TpvInt32; fComponentHSamples:array[0..2] of TpvUInt8; fComponentVSamples:array[0..2] of TpvUInt8; fImageWidth:TpvInt32; fImageHeight:TpvInt32; fImageWidthMCU:TpvInt32; fImageHeightMCU:TpvInt32; fMCUsPerRow:TpvInt32; fMCUWidth:TpvInt32; fMCUHeight:TpvInt32; fMCUChannels:array[0..2] of PpvJPEGEncoderUInt8Array; fMCUYOffset:TpvInt32; fTempChannelWords:PpvJPEGEncoderUInt16Array; fTempChannelBytes:PpvJPEGEncoderUInt8Array; fTempChannelSize:TpvInt32; fSamples8Bit:array[0..63] of TpvUInt8; fSamples16Bit:array[0..63] of TpvInt16; fSamples32Bit:array[0..63] of TpvInt32; fCoefficients:array[0..63] of TpvInt16; fQuantizationTables:array[0..1,0..63] of TpvInt32; fHuffmanCodes:array[0..3,0..255] of TpvUInt32; fHuffmanCodeSizes:array[0..3,0..255] of TpvUInt8; fHuffmanBits:array[0..3,0..16] of TpvUInt8; fHuffmanValues:array[0..3,0..255] of TpvUInt8; fHuffmanCounts:array[0..3,0..255] of TpvUInt32; fLastDCValues:array[0..3] of TpvInt32; fOutputBuffer:array[0..JPEG_OUTPUT_BUFFER_SIZE-1] of TpvUInt8; fOutputBufferPointer:pbyte; fOutputBufferLeft:TpvUInt32; fOutputBufferCount:TpvUInt32; fBitsBuffer:TpvUInt32; fBitsBufferSize:TpvUInt32; fPassIndex:TpvInt32; fDataMemory:TpvPointer; fDataMemorySize:TpvUInt32; fCompressedData:TpvPointer; fCompressedDataPosition:TpvUInt32; fCompressedDataAllocated:TpvUInt32; fMaxCompressedDataSize:TpvUInt32; fBlockEncodingMode:TpvInt32; procedure EmitByte(b:TpvUInt8); procedure EmitWord(w:word); procedure EmitMarker(m:TpvUInt8); procedure EmitJFIFApp0; procedure EmitDQT; procedure EmitSOF; procedure EmitDHT(Bits,Values:pansichar;Index:TpvInt32;ACFlag:boolean); procedure EmitDHTs; procedure EmitSOS; procedure EmitMarkers; procedure ConvertRGBAToY(pDstY,pSrc:PpvJPEGEncoderUInt8Array;Count:TpvInt32); {$ifndef PurePascal}{$ifdef cpu386}stdcall;{$endif}{$endif} procedure ConvertRGBAToYCbCr(pDstY,pDstCb,pDstCr,pSrc:PpvJPEGEncoderUInt8Array;Count:TpvInt32); {$ifndef PurePascal}{$ifdef cpu386}stdcall;{$endif}{$endif} procedure ComputeHuffmanTable(Codes:PpvJPEGEncoderUInt32Array;CodeSizes,Bits,Values:PpvJPEGEncoderUInt8Array); function InitFirstPass:boolean; function InitSecondPass:boolean; procedure ComputeQuantizationTable(pDst:PpvJPEGEncoderInt32Array;pSrc:PpvJPEGEncoderInt16Array); function Setup(Width,Height:TpvInt32):boolean; procedure FlushOutputBuffer; procedure PutBits(Bits,Len:TpvUInt32); procedure LoadBlock8x8(x,y,c:TpvInt32); procedure LoadBlock16x8(x,c:TpvInt32); procedure LoadBlock16x8x8(x,c:TpvInt32); procedure DCT2D; procedure LoadQuantizedCoefficients(ComponentIndex:TpvInt32); procedure CodeCoefficientsPassOne(ComponentIndex:TpvInt32); procedure CodeCoefficientsPassTwo(ComponentIndex:TpvInt32); procedure CodeBlock(ComponentIndex:TpvInt32); procedure ProcessMCURow; procedure LoadMCU(p:TpvPointer); function RadixSortSymbols(CountSymbols:TpvUInt32;SymbolsA,SymbolsB:PpvJPEGHuffmanSymbolFrequencies):PpvJPEGHuffmanSymbolFrequency; procedure CalculateMinimumRedundancy(a:PpvJPEGHuffmanSymbolFrequencies;n:TpvInt32); procedure HuffmanEnforceMaxCodeSize(CountCodes:PpvJPEGEncoderInt32Array;CodeListLen,MaxCodeSize:TpvInt32); procedure OptimizeHuffmanTable(TableIndex,TableLen:TpvInt32); function TerminatePassOne:boolean; function TerminatePassTwo:boolean; function ProcessEndOfImage:boolean; function ProcessScanline(pScanline:TpvPointer):boolean; public constructor Create; destructor Destroy; override; function Encode(const FrameData:TpvPointer;var CompressedData:TpvPointer;Width,Height:TpvInt32;Quality,MaxCompressedDataSize:TpvUInt32;const Fast:boolean=false;const ChromaSubsampling:TpvInt32=-1):TpvUInt32; end; function LoadJPEGImage(DataPointer:TpvPointer;DataSize:TpvUInt32;var ImageData:TpvPointer;var ImageWidth,ImageHeight:TpvInt32;const HeaderOnly:boolean):boolean; function SaveJPEGImage(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;out aDestData:TpvPointer;out aDestDataSize:TpvUInt32;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; function SaveJPEGImageAsStream(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aStream:TStream;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; function SaveJPEGImageAsFile(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aFileName:string;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; implementation const NilLibHandle={$ifdef fpc}NilHandle{$else}THandle(0){$endif}; var TurboJpegLibrary:{$ifdef fpc}TLibHandle{$else}THandle{$endif}=NilLibHandle; type TtjInitCompress=function:pointer; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjInitDecompress=function:pointer; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjDestroy=function(handle:pointer):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjAlloc=function(bytes:longint):pointer; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjFree=procedure(buffer:pointer); {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjCompress2=function(handle:pointer; srcBuf:pointer; width:longint; pitch:longint; height:longint; pixelFormat:longint; var jpegBuf:pointer; var jpegSize:longword; jpegSubsamp:longint; jpegQual:longint; flags:longint):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjDecompressHeader=function(handle:pointer; jpegBuf:pointer; jpegSize:longword; out width:longint; out height:longint):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjDecompressHeader2=function(handle:pointer; jpegBuf:pointer; jpegSize:longword; out width:longint; out height:longint; out jpegSubsamp:longint):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjDecompressHeader3=function(handle:pointer; jpegBuf:pointer; jpegSize:longword; out width:longint; out height:longint; out jpegSubsamp:longint; out jpegColorSpace:longint):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} TtjDecompress2=function(handle:pointer; jpegBuf:pointer; jpegSize:longword; dstBuf:pointer; width:longint; pitch:longint; height:longint; pixelFormat:longint; flags:longint):longint; {$ifdef Windows}stdcall;{$else}cdecl;{$endif} var tjInitCompress:TtjInitCompress=nil; tjInitDecompress:TtjInitDecompress=nil; tjDestroy:TtjDestroy=nil; tjAlloc:TtjAlloc=nil; tjFree:TtjFree=nil; tjCompress2:TtjCompress2=nil; tjDecompressHeader:TtjDecompressHeader=nil; tjDecompressHeader2:TtjDecompressHeader2=nil; tjDecompressHeader3:TtjDecompressHeader3=nil; tjDecompress2:TtjDecompress2=nil; {$ifndef HasSAR} function SARLongint(Value,Shift:TpvInt32):TpvInt32; {$ifdef cpu386} {$ifdef fpc} assembler; register; //inline; asm mov ecx,edx sar eax,cl end;// ['eax','edx','ecx']; {$else} assembler; register; asm mov ecx,edx sar eax,cl end; {$endif} {$else} {$ifdef cpuarm} assembler; //inline; asm mov r0,r0,asr R1 end;// ['r0','R1']; {$else}{$ifdef CAN_INLINE}inline;{$endif} begin Shift:=Shift and 31; result:=(TpvUInt32(Value) shr Shift) or (TpvUInt32(TpvInt32(TpvUInt32(0-TpvUInt32(TpvUInt32(Value) shr 31)) and TpvUInt32(0-TpvUInt32(ord(Shift<>0) and 1)))) shl (32-Shift)); end; {$endif} {$endif} {$endif} function LoadJPEGImage(DataPointer:TpvPointer;DataSize:TpvUInt32;var ImageData:TpvPointer;var ImageWidth,ImageHeight:TpvInt32;const HeaderOnly:boolean):boolean; {$ifdef fpc} var Image:TFPMemoryImage; ReaderJPEG:TFPReaderJPEG; Stream:TMemoryStream; y,x:TpvInt32; c:TFPColor; pout:PAnsiChar; tjWidth,tjHeight,tjJpegSubsamp:TpvInt32; tjHandle:pointer; begin result:=false; try Stream:=TMemoryStream.Create; try if (DataSize>2) and (((byte(PAnsiChar(pointer(DataPointer))[0]) xor $ff)=0) and ((byte(PAnsiChar(pointer(DataPointer))[1]) xor $d8)=0)) then begin if (TurboJpegLibrary<>NilLibHandle) and assigned(tjInitDecompress) and assigned(tjDecompressHeader2) and assigned(tjDecompress2) and assigned(tjDestroy) then begin tjHandle:=tjInitDecompress; if assigned(tjHandle) then begin try if tjDecompressHeader2(tjHandle,DataPointer,DataSize,tjWidth,tjHeight,tjJpegSubsamp)>=0 then begin ImageWidth:=tjWidth; ImageHeight:=tjHeight; if HeaderOnly then begin result:=true; end else begin GetMem(ImageData,ImageWidth*ImageHeight*SizeOf(longword)); if tjDecompress2(tjHandle,DataPointer,DataSize,ImageData,tjWidth,0,tjHeight,7{TJPF_RGBA},2048{TJFLAG_FASTDCT})>=0 then begin result:=true; end else begin FreeMem(ImageData); ImageData:=nil; end; end; end; finally tjDestroy(tjHandle); end; end; end else begin if Stream.Write(DataPointer^,DataSize)=longint(DataSize) then begin if Stream.Seek(0,soFromBeginning)=0 then begin Image:=TFPMemoryImage.Create(20,20); try ReaderJPEG:=TFPReaderJPEG.Create; try Image.LoadFromStream(Stream,ReaderJPEG); ImageWidth:=Image.Width; ImageHeight:=Image.Height; GetMem(ImageData,ImageWidth*ImageHeight*4); pout:=ImageData; for y:=0 to ImageHeight-1 do begin for x:=0 to ImageWidth-1 do begin c:=Image.Colors[x,y]; pout[0]:=ansichar(byte((c.red shr 8) and $ff)); pout[1]:=ansichar(byte((c.green shr 8) and $ff)); pout[2]:=ansichar(byte((c.blue shr 8) and $ff)); pout[3]:=AnsiChar(#$ff); inc(pout,4); end; end; result:=true; finally ReaderJPEG.Free; end; finally Image.Free; end; end; end; end; end; finally Stream.Free; end; except result:=false; end; end; {$else} type PIDCTInputBlock=^TIDCTInputBlock; TIDCTInputBlock=array[0..63] of TpvInt32; PIDCTOutputBlock=^TIDCTOutputBlock; TIDCTOutputBlock=array[0..65535] of TpvUInt8; PByteArray=^TByteArray; TByteArray=array[0..65535] of TpvUInt8; TPixels=array of TpvUInt8; PHuffmanCode=^THuffmanCode; THuffmanCode=record Bits:TpvUInt8; Code:TpvUInt8; end; PHuffmanCodes=^THuffmanCodes; THuffmanCodes=array[0..65535] of THuffmanCode; PComponent=^TComponent; TComponent=record Width:TpvInt32; Height:TpvInt32; Stride:TpvInt32; Pixels:TPixels; ID:TpvInt32; SSX:TpvInt32; SSY:TpvInt32; QTSel:TpvInt32; ACTabSel:TpvInt32; DCTabSel:TpvInt32; DCPred:TpvInt32; end; PContext=^TContext; TContext=record Valid:boolean; NoDecode:boolean; FastChroma:boolean; Len:TpvInt32; Size:TpvInt32; Width:TpvInt32; Height:TpvInt32; MBWidth:TpvInt32; MBHeight:TpvInt32; MBSizeX:TpvInt32; MBSizeY:TpvInt32; Components:array[0..2] of TComponent; CountComponents:TpvInt32; QTUsed:TpvInt32; QTAvailable:TpvInt32; QTable:array[0..3,0..63] of TpvUInt8; HuffmanCodeTable:array[0..3] of THuffmanCodes; Buf:TpvInt32; BufBits:TpvInt32; RSTInterval:TpvInt32; EXIFLE:boolean; CoSitedChroma:boolean; Block:TIDCTInputBlock; end; const ZigZagOrderToRasterOrderConversionTable:array[0..63] of TpvUInt8= ( 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5, 12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28, 35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51, 58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 ); ClipTable:array[0..$3ff] of TpvUInt8= ( // 0..255 0,1,2,3,4,5,6,7,8,9,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,60,61,62,63, 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95, 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, // 256..511 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // -512..-257 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // -256..-1 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ); CF4A=-9; CF4B=111; CF4C=29; CF4D=-3; CF3A=28; CF3B=109; CF3C=-9; CF3X=104; CF3Y=27; CF3Z=-3; CF2A=139; CF2B=-11; var Context:PContext; DataPosition:TpvUInt32; procedure RaiseError; begin raise EpvLoadJPEGImage.Create('Invalid or corrupt JPEG data stream'); end; procedure ProcessIDCT(const aInputBlock:PIDCTInputBlock;const aOutputBlock:PIDCTOutputBlock;const aOutputStride:TpvInt32); const W1=2841; W2=2676; W3=2408; W5=1609; W6=1108; W7=565; var i,v0,v1,v2,v3,v4,v5,v6,v7,v8:TpvInt32; WorkBlock:PIDCTInputBlock; OutputBlock:PIDCTOutputBlock; begin for i:=0 to 7 do begin WorkBlock:=@aInputBlock^[i shl 3]; v0:=WorkBlock^[0]; v1:=WorkBlock^[4] shl 11; v2:=WorkBlock^[6]; v3:=WorkBlock^[2]; v4:=WorkBlock^[1]; v5:=WorkBlock^[7]; v6:=WorkBlock^[5]; v7:=WorkBlock^[3]; if (v1=0) and (v2=0) and (v3=0) and (v4=0) and (v5=0) and (v6=0) and (v7=0) then begin v0:=v0 shl 3; WorkBlock^[0]:=v0; WorkBlock^[1]:=v0; WorkBlock^[2]:=v0; WorkBlock^[3]:=v0; WorkBlock^[4]:=v0; WorkBlock^[5]:=v0; WorkBlock^[6]:=v0; WorkBlock^[7]:=v0; end else begin v0:=(v0 shl 11)+128; v8:=W7*(v4+v5); v4:=v8+((W1-W7)*v4); v5:=v8-((W1+W7)*v5); v8:=W3*(v6+v7); v6:=v8-((W3-W5)*v6); v7:=v8-((W3+W5)*v7); v8:=v0+v1; dec(v0,v1); v1:=W6*(v3+v2); v2:=v1-((W2+W6)*v2); v3:=v1+((W2-W6)*v3); v1:=v4+v6; dec(v4,v6); v6:=v5+v7; dec(v5,v7); v7:=v8+v3; dec(v8,v3); v3:=v0+v2; dec(v0,v2); v2:=SARLongint(((v4+v5)*181)+128,8); v4:=SARLongint(((v4-v5)*181)+128,8); WorkBlock^[0]:=SARLongint(v7+v1,8); WorkBlock^[1]:=SARLongint(v3+v2,8); WorkBlock^[2]:=SARLongint(v0+v4,8); WorkBlock^[3]:=SARLongint(v8+v6,8); WorkBlock^[4]:=SARLongint(v8-v6,8); WorkBlock^[5]:=SARLongint(v0-v4,8); WorkBlock^[6]:=SARLongint(v3-v2,8); WorkBlock^[7]:=SARLongint(v7-v1,8); end; end; for i:=0 to 7 do begin WorkBlock:=@aInputBlock^[i]; v0:=WorkBlock^[0 shl 3]; v1:=WorkBlock^[4 shl 3] shl 8; v2:=WorkBlock^[6 shl 3]; v3:=WorkBlock^[2 shl 3]; v4:=WorkBlock^[1 shl 3]; v5:=WorkBlock^[7 shl 3]; v6:=WorkBlock^[5 shl 3]; v7:=WorkBlock^[3 shl 3]; if (v1=0) and (v2=0) and (v3=0) and (v4=0) and (v5=0) and (v6=0) and (v7=0) then begin v0:=ClipTable[(SARLongint(v0+32,6)+128) and $3ff]; OutputBlock:=@aOutputBlock^[i]; OutputBlock^[aOutputStride*0]:=v0; OutputBlock^[aOutputStride*1]:=v0; OutputBlock^[aOutputStride*2]:=v0; OutputBlock^[aOutputStride*3]:=v0; OutputBlock^[aOutputStride*4]:=v0; OutputBlock^[aOutputStride*5]:=v0; OutputBlock^[aOutputStride*6]:=v0; OutputBlock^[aOutputStride*7]:=v0; end else begin v0:=(v0 shl 8)+8192; v8:=((v4+v5)*W7)+4; v4:=SARLongint(v8+((W1-W7)*v4),3); v5:=SARLongint(v8-((W1+W7)*v5),3); v8:=((v6+v7)*W3)+4; v6:=SARLongint(v8-((W3-W5)*v6),3); v7:=SARLongint(v8-((W3+W5)*v7),3); v8:=v0+v1; dec(v0,v1); v1:=((v3+v2)*w6)+4; v2:=SARLongint(v1-((W2+W6)*v2),3); v3:=SARLongint(v1+((W2-W6)*v3),3); v1:=v4+v6; dec(v4,v6); v6:=v5+v7; dec(v5,v7); v7:=v8+v3; dec(v8,v3); v3:=v0+v2; dec(v0,v2); v2:=SARLongint(((v4+v5)*181)+128,8); v4:=SARLongint(((v4-v5)*181)+128,8); OutputBlock:=@aOutputBlock^[i]; OutputBlock^[aOutputStride*0]:=ClipTable[(SARLongint(v7+v1,14)+128) and $3ff]; OutputBlock^[aOutputStride*1]:=ClipTable[(SARLongint(v3+v2,14)+128) and $3ff]; OutputBlock^[aOutputStride*2]:=ClipTable[(SARLongint(v0+v4,14)+128) and $3ff]; OutputBlock^[aOutputStride*3]:=ClipTable[(SARLongint(v8+v6,14)+128) and $3ff]; OutputBlock^[aOutputStride*4]:=ClipTable[(SARLongint(v8-v6,14)+128) and $3ff]; OutputBlock^[aOutputStride*5]:=ClipTable[(SARLongint(v0-v4,14)+128) and $3ff]; OutputBlock^[aOutputStride*6]:=ClipTable[(SARLongint(v3-v2,14)+128) and $3ff]; OutputBlock^[aOutputStride*7]:=ClipTable[(SARLongint(v7-v1,14)+128) and $3ff]; end; end; end; function PeekBits(Bits:TpvInt32):TpvInt32; var NewByte,Marker:TpvInt32; begin if Bits>0 then begin while Context^.BufBits<Bits do begin if DataPosition>=DataSize then begin Context^.Buf:=(Context^.Buf shl 8) or $ff; inc(Context^.BufBits,8); end else begin NewByte:=PByteArray(DataPointer)^[DataPosition]; inc(DataPosition); Context^.Buf:=(Context^.Buf shl 8) or NewByte; inc(Context^.BufBits,8); if NewByte=$ff then begin if DataPosition<DataSize then begin Marker:=PByteArray(DataPointer)^[DataPosition]; inc(DataPosition); case Marker of $00,$ff:begin end; $d9:begin DataPosition:=DataSize; end; else begin if (Marker and $f8)=$d0 then begin Context^.Buf:=(Context^.Buf shl 8) or Marker; inc(Context^.BufBits,8); end else begin RaiseError; end; end; end; end else begin RaiseError; end; end; end; end; result:=(Context^.Buf shr (Context^.BufBits-Bits)) and ((1 shl Bits)-1); end else begin result:=0; end; end; procedure SkipBits(Bits:TpvInt32); begin if Context^.BufBits<Bits then begin PeekBits(Bits); end; dec(Context^.BufBits,Bits); end; function GetBits(Bits:TpvInt32):TpvInt32; begin result:=PeekBits(Bits); if Context^.BufBits<Bits then begin PeekBits(Bits); end; dec(Context^.BufBits,Bits); end; function GetHuffmanCode(const Huffman:PHuffmanCodes;const Code:PpvInt32):TpvInt32; var Bits:TpvInt32; begin result:=PeekBits(16); Bits:=Huffman^[result].Bits; if Bits=0 then begin // writeln(result); RaiseError; result:=0; end else begin SkipBits(Bits); result:=Huffman^[result].Code; if assigned(Code) then begin Code^:=result and $ff; end; Bits:=result and $0f; if Bits=0 then begin result:=0; end else begin result:=GetBits(Bits); if result<(1 shl (Bits-1)) then begin inc(result,(TpvInt32(-1) shl Bits)+1); end; end; end; end; procedure UpsampleHCoSited(const Component:PComponent); var MaxX,x,y:TpvInt32; NewPixels:TPixels; ip,op:PByteArray; begin MaxX:=Component^.Width-1; NewPixels:=nil; try SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1); ip:=@Component^.Pixels[0]; op:=@NewPixels[0]; for y:=0 to Component^.Height-1 do begin op^[0]:=ip^[0]; op^[1]:=ClipTable[SARLongint(((((ip^[0] shl 3)+(9*ip^[1]))-ip^[2]))+8,4) and $3ff]; op^[2]:=ip^[1]; for x:=2 to MaxX-1 do begin op^[(x shl 1)-1]:=ClipTable[SARLongint(((9*(ip^[x-1]+ip^[x]))-(ip^[x-2]+ip^[x+1]))+8,4) and $3ff]; op^[x shl 1]:=ip^[x]; end; ip:=@ip^[Component^.Stride-3]; op:=@op^[(Component^.Width shl 1)-3]; op^[0]:=ClipTable[SARLongint(((((ip^[2] shl 3)+(9*ip^[1]))-ip^[0]))+8,4) and $3ff]; op^[1]:=ip^[2]; op^[2]:=ClipTable[SARLongint(((ip^[2]*17)-ip^[1])+8,4) and $3ff]; ip:=@ip^[3]; op:=@op^[3]; end; finally Component^.Width:=Component^.Width shl 1; Component^.Stride:=Component^.Width; Component^.Pixels:=NewPixels; NewPixels:=nil; end; end; procedure UpsampleHCentered(const Component:PComponent); var MaxX,x,y:TpvInt32; NewPixels:TPixels; ip,op:PByteArray; begin MaxX:=Component^.Width-3; NewPixels:=nil; try SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1); ip:=@Component^.Pixels[0]; op:=@NewPixels[0]; for y:=0 to Component^.Height-1 do begin op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[1]))+64,7) and $3ff]; op^[1]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[1])+(CF3Z*ip^[2]))+64,7) and $3ff]; op^[2]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[1])+(CF3C*ip^[2]))+64,7) and $3ff]; for x:=0 to MaxX-1 do begin op^[(x shl 1)+3]:=ClipTable[SARLongint(((CF4A*ip^[x])+(CF4B*ip^[x+1])+(CF4C*ip^[x+2])+(CF4D*ip^[x+3]))+64,7) and $3ff]; op^[(x shl 1)+4]:=ClipTable[SARLongint(((CF4D*ip^[x])+(CF4C*ip^[x+1])+(CF4B*ip^[x+2])+(CF4A*ip^[x+3]))+64,7) and $3ff]; end; ip:=@ip^[Component^.Stride-3]; op:=@op^[(Component^.Width shl 1)-3]; op^[0]:=ClipTable[SARLongint(((CF3A*ip^[2])+(CF3B*ip^[1])+(CF3C*ip^[0]))+64,7) and $3ff]; op^[1]:=ClipTable[SARLongint(((CF3X*ip^[2])+(CF3Y*ip^[1])+(CF3Z*ip^[0]))+64,7) and $3ff]; op^[2]:=ClipTable[SARLongint(((CF2A*ip^[2])+(CF2B*ip^[1]))+64,7) and $3ff]; ip:=@ip^[3]; op:=@op^[3]; end; finally Component^.Width:=Component^.Width shl 1; Component^.Stride:=Component^.Width; Component^.Pixels:=NewPixels; NewPixels:=nil; end; end; procedure UpsampleVCoSited(const Component:PComponent); var w,h,s1,s2,x,y:TpvInt32; NewPixels:TPixels; ip,op:PByteArray; begin w:=Component^.Width; h:=Component^.Height; s1:=Component^.Stride; s2:=s1 shl 1; NewPixels:=nil; try SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1); for x:=0 to w-1 do begin ip:=@Component^.Pixels[x]; op:=@NewPixels[x]; op^[0]:=ip^[0]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((((ip^[0] shl 3)+(9*ip^[s1]))-ip^[s2]))+8,4) and $3ff]; op:=@op^[w]; op^[0]:=ip^[s1]; op:=@op^[w]; ip:=@ip^[s1]; for y:=0 to h-4 do begin op^[0]:=ClipTable[SARLongint((((9*(ip^[0]+ip^[s1]))-(ip^[-s1]+ip^[s2])))+8,4) and $3ff]; op:=@op^[w]; op^[0]:=ip^[s1]; op:=@op^[w]; ip:=@ip^[s1]; end; op^[0]:=ClipTable[SARLongint(((ip^[s1] shl 3)+(9*ip^[0])-(ip^[-s1]))+8,4) and $3ff]; op:=@op^[w]; op^[0]:=ip[-s1]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((17*ip^[s1])-ip^[0])+8,4) and $3ff]; end; finally Component^.Height:=Component^.Height shl 1; Component^.Pixels:=NewPixels; NewPixels:=nil; end; end; procedure UpsampleVCentered(const Component:PComponent); var w,h,s1,s2,x,y:TpvInt32; NewPixels:TPixels; ip,op:PByteArray; begin w:=Component^.Width; h:=Component^.Height; s1:=Component^.Stride; s2:=s1 shl 1; NewPixels:=nil; try SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1); for x:=0 to w-1 do begin ip:=@Component^.Pixels[x]; op:=@NewPixels[x]; op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[s1]))+64,7) and $3ff]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[s1])+(CF3Z*ip^[s2]))+64,7) and $3ff]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[s1])+(CF3C*ip^[s2]))+64,7) and $3ff]; op:=@op^[w]; ip:=@ip^[s1]; for y:=0 to h-4 do begin op^[0]:=ClipTable[SARLongint(((CF4A*ip^[-s1])+(CF4B*ip^[0])+(CF4C*ip^[s1])+(CF4D*ip^[s2]))+64,7) and $3ff]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((CF4D*ip^[-s1])+(CF4C*ip^[0])+(CF4B*ip^[s1])+(CF4A*ip^[s2]))+64,7) and $3ff]; op:=@op^[w]; ip:=@ip^[s1]; end; ip:=@ip^[s1]; op^[0]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[-s1])+(CF3C*ip^[-s2]))+64,7) and $3ff]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[-s1])+(CF3Z*ip^[-s2]))+64,7) and $3ff]; op:=@op^[w]; op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[-s1]))+64,7) and $3ff]; end; finally Component^.Height:=Component^.Height shl 1; Component^.Pixels:=NewPixels; NewPixels:=nil; end; end; var Index,SubIndex,Len,MaxSSX,MaxSSY,Value,Remain,Spread,CodeLen,DHTCurrentCount,Code,Coef, NextDataPosition,Count,v0,v1,v2,v3,mbx,mby,sbx,sby,RSTCount,NextRST,x,y,vY,vCb,vCr, tjWidth,tjHeight,tjJpegSubsamp:TpvInt32; ChunkTag:TpvUInt8; Component:PComponent; DHTCounts:array[0..15] of TpvUInt8; Huffman:PHuffmanCode; pY,aCb,aCr,oRGBX:PpvUInt8; tjHandle:pointer; begin result:=false; ImageData:=nil; if (DataSize>=2) and (((PByteArray(DataPointer)^[0] xor $ff) or (PByteArray(DataPointer)^[1] xor $d8))=0) then begin if (TurboJpegLibrary<>NilLibHandle) and assigned(tjInitDecompress) and assigned(tjDecompressHeader2) and assigned(tjDecompress2) and assigned(tjDestroy) then begin tjHandle:=tjInitDecompress; if assigned(tjHandle) then begin try if tjDecompressHeader2(tjHandle,DataPointer,DataSize,tjWidth,tjHeight,tjJpegSubsamp)>=0 then begin ImageWidth:=tjWidth; ImageHeight:=tjHeight; if HeaderOnly then begin result:=true; end else begin GetMem(ImageData,ImageWidth*ImageHeight*SizeOf(longword)); if tjDecompress2(tjHandle,DataPointer,DataSize,ImageData,tjWidth,0,tjHeight,7{TJPF_RGBA},2048{TJFLAG_FASTDCT})>=0 then begin result:=true; end else begin FreeMem(ImageData); ImageData:=nil; end; end; end; finally tjDestroy(tjHandle); end; end; end else begin DataPosition:=2; GetMem(Context,SizeOf(TContext)); try FillChar(Context^,SizeOf(TContext),#0); Initialize(Context^); try while ((DataPosition+2)<DataSize) and (PByteArray(DataPointer)^[DataPosition]=$ff) do begin ChunkTag:=PByteArray(DataPointer)^[DataPosition+1]; inc(DataPosition,2); case ChunkTag of $c0{SQF}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if ((DataPosition+TpvUInt32(Len))>=DataSize) or (Len<9) or (PByteArray(DataPointer)^[DataPosition+2]<>8) then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); Context^.Width:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+1]) shl 8) or PByteArray(DataPointer)^[DataPosition+2]; Context^.Height:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+3]) shl 8) or PByteArray(DataPointer)^[DataPosition+4]; Context^.CountComponents:=PByteArray(DataPointer)^[DataPosition+5]; if (Context^.Width=0) or (Context^.Height=0) or not (Context^.CountComponents in [1,3]) then begin RaiseError; end; inc(DataPosition,6); dec(Len,6); if Len<(Context^.CountComponents*3) then begin RaiseError; end; MaxSSX:=0; MaxSSY:=0; for Index:=0 to Context^.CountComponents-1 do begin Component:=@Context^.Components[Index]; Component^.ID:=PByteArray(DataPointer)^[DataPosition+0]; Component^.SSX:=PByteArray(DataPointer)^[DataPosition+1] shr 4; Component^.SSY:=PByteArray(DataPointer)^[DataPosition+1] and 15; Component^.QTSel:=PByteArray(DataPointer)^[DataPosition+2]; inc(DataPosition,3); dec(Len,3); if (Component^.SSX=0) or ((Component^.SSX and (Component^.SSX-1))<>0) or (Component^.SSY=0) or ((Component^.SSY and (Component^.SSY-1))<>0) or ((Component^.QTSel and $fc)<>0) then begin RaiseError; end; Context^.QTUsed:=Context^.QTUsed or (1 shl Component^.QTSel); MaxSSX:=Max(MaxSSX,Component^.SSX); MaxSSY:=Max(MaxSSY,Component^.SSY); end; if Context^.CountComponents=1 then begin Component:=@Context^.Components[0]; Component^.SSX:=1; Component^.SSY:=1; MaxSSX:=0; MaxSSY:=0; end; Context^.MBSizeX:=MaxSSX shl 3; Context^.MBSizeY:=MaxSSY shl 3; Context^.MBWidth:=(Context^.Width+(Context^.MBSizeX-1)) div Context^.MBSizeX; Context^.MBHeight:=(Context^.Height+(Context^.MBSizeY-1)) div Context^.MBSizeY; for Index:=0 to Context^.CountComponents-1 do begin Component:=@Context^.Components[Index]; Component^.Width:=((Context^.Width*Component^.SSX)+(MaxSSX-1)) div MaxSSX; Component^.Height:=((Context^.Height*Component^.SSY)+(MaxSSY-1)) div MaxSSY; Component^.Stride:=(Context^.MBWidth*Component^.SSX) shl 3; if ((Component^.Width<3) and (Component^.SSX<>MaxSSX)) or ((Component^.Height<3) and (Component^.SSY<>MaxSSY)) then begin RaiseError; end; Count:=Component^.Stride*((Context^.MBHeight*Component^.ssy) shl 3); // Count:=(Component^.Stride*((Context^.MBHeight*Context^.MBSizeY*Component^.ssy) div MaxSSY)) shl 3; if not HeaderOnly then begin SetLength(Component^.Pixels,Count); FillChar(Component^.Pixels[0],Count,#$80); end; end; inc(DataPosition,Len); end; $c4{DHT}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if (DataPosition+TpvUInt32(Len))>=DataSize then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); while Len>=17 do begin Value:=PByteArray(DataPointer)^[DataPosition]; if (Value and ($ec or $02))<>0 then begin RaiseError; end; Value:=(Value or (Value shr 3)) and 3; for CodeLen:=1 to 16 do begin DHTCounts[CodeLen-1]:=PByteArray(DataPointer)^[DataPosition+TpvUInt32(CodeLen)]; end; inc(DataPosition,17); dec(Len,17); Huffman:=@Context^.HuffmanCodeTable[Value,0]; Remain:=65536; Spread:=65536; for CodeLen:=1 to 16 do begin Spread:=Spread shr 1; DHTCurrentCount:=DHTCounts[CodeLen-1]; if DHTCurrentCount<>0 then begin dec(Remain,DHTCurrentCount shl (16-CodeLen)); if (Len<DHTCurrentCount) or (Remain<0) then begin RaiseError; end; for Index:=0 to DHTCurrentCount-1 do begin Code:=PByteArray(DataPointer)^[DataPosition+TpvUInt32(Index)]; for SubIndex:=0 to Spread-1 do begin Huffman^.Bits:=CodeLen; Huffman^.Code:=Code; inc(Huffman); end; end; inc(DataPosition,DHTCurrentCount); dec(Len,DHTCurrentCount); end; end; while Remain>0 do begin dec(Remain); Huffman^.Bits:=0; inc(Huffman); end; end; if Len>0 then begin RaiseError; end; inc(DataPosition,Len); end; $da{SOS}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if ((DataPosition+TpvUInt32(Len))>=DataSize) or (Len<2) then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); if (Len<(4+(2*Context^.CountComponents))) or (PByteArray(DataPointer)^[DataPosition+0]<>Context^.CountComponents) then begin RaiseError; end; inc(DataPosition); dec(Len); for Index:=0 to Context^.CountComponents-1 do begin Component:=@Context^.Components[Index]; if (PByteArray(DataPointer)^[DataPosition+0]<>Component^.ID) or ((PByteArray(DataPointer)^[DataPosition+1] and $ee)<>0) then begin RaiseError; end; Component^.DCTabSel:=PByteArray(DataPointer)^[DataPosition+1] shr 4; Component^.ACTabSel:=(PByteArray(DataPointer)^[DataPosition+1] and 1) or 2; inc(DataPosition,2); dec(Len,2); end; if (PByteArray(DataPointer)^[DataPosition+0]<>0) or (PByteArray(DataPointer)^[DataPosition+1]<>63) or (PByteArray(DataPointer)^[DataPosition+2]<>0) then begin RaiseError; end; inc(DataPosition,Len); if not HeaderOnly then begin mbx:=0; mby:=0; RSTCount:=Context^.RSTInterval; NextRST:=0; repeat for Index:=0 to Context^.CountComponents-1 do begin Component:=@Context^.Components[Index]; for sby:=0 to Component^.ssy-1 do begin for sbx:=0 to Component^.ssx-1 do begin Code:=0; Coef:=0; FillChar(Context^.Block,SizeOf(Context^.Block),#0); inc(Component^.DCPred,GetHuffmanCode(@Context^.HuffmanCodeTable[Component^.DCTabSel],nil)); Context^.Block[0]:=Component^.DCPred*Context^.QTable[Component^.QTSel,0]; repeat Value:=GetHuffmanCode(@Context^.HuffmanCodeTable[Component^.ACTabSel],@Code); if Code=0 then begin // EOB break; end else if ((Code and $0f)=0) and (Code<>$f0) then begin RaiseError; end else begin inc(Coef,(Code shr 4)+1); if Coef>63 then begin RaiseError; end else begin Context^.Block[ZigZagOrderToRasterOrderConversionTable[Coef]]:=Value*Context^.QTable[Component^.QTSel,Coef]; end; end; until Coef>=63; ProcessIDCT(@Context^.Block, @Component^.Pixels[((((mby*Component^.ssy)+sby)*Component^.Stride)+ ((mbx*Component^.ssx)+sbx)) shl 3], Component^.Stride); end; end; end; inc(mbx); if mbx>=Context^.MBWidth then begin mbx:=0; inc(mby); if mby>=Context^.MBHeight then begin mby:=0; ImageWidth:=Context^.Width; ImageHeight:=Context^.Height; GetMem(ImageData,(Context^.Width*Context^.Height) shl 2); FillChar(ImageData^,(Context^.Width*Context^.Height) shl 2,#0); for Index:=0 to Context^.CountComponents-1 do begin Component:=@Context^.Components[Index]; while (Component^.Width<Context^.Width) or (Component^.Height<Context^.Height) do begin if Component^.Width<Context^.Width then begin if Context^.CoSitedChroma then begin UpsampleHCoSited(Component); end else begin UpsampleHCentered(Component); end; end; if Component^.Height<Context^.Height then begin if Context^.CoSitedChroma then begin UpsampleVCoSited(Component); end else begin UpsampleVCentered(Component); end; end; end; if (Component^.Width<Context^.Width) or (Component^.Height<Context^.Height) then begin RaiseError; end; end; case Context^.CountComponents of 3:begin pY:=@Context^.Components[0].Pixels[0]; aCb:=@Context^.Components[1].Pixels[0]; aCr:=@Context^.Components[2].Pixels[0]; oRGBX:=ImageData; for y:=0 to Context^.Height-1 do begin for x:=0 to Context^.Width-1 do begin vY:=PByteArray(pY)^[x] shl 8; vCb:=PByteArray(aCb)^[x]-128; vCr:=PByteArray(aCr)^[x]-128; PByteArray(oRGBX)^[0]:=ClipTable[SARLongint((vY+(vCr*359))+128,8) and $3ff]; PByteArray(oRGBX)^[1]:=ClipTable[SARLongint(((vY-(vCb*88))-(vCr*183))+128,8) and $3ff]; PByteArray(oRGBX)^[2]:=ClipTable[SARLongint((vY+(vCb*454))+128,8) and $3ff]; PByteArray(oRGBX)^[3]:=$ff; inc(oRGBX,4); end; inc(pY,Context^.Components[0].Stride); inc(aCb,Context^.Components[1].Stride); inc(aCr,Context^.Components[2].Stride); end; end; else begin pY:=@Context^.Components[0].Pixels[0]; oRGBX:=ImageData; for y:=0 to Context^.Height-1 do begin for x:=0 to Context^.Width-1 do begin vY:=ClipTable[PByteArray(pY)^[x] and $3ff]; PByteArray(oRGBX)^[0]:=vY; PByteArray(oRGBX)^[1]:=vY; PByteArray(oRGBX)^[2]:=vY; PByteArray(oRGBX)^[3]:=$ff; inc(oRGBX,4); end; inc(pY,Context^.Components[0].Stride); end; end; end; result:=true; break; end; end; if Context^.RSTInterval<>0 then begin dec(RSTCount); if RSTCount=0 then begin Context^.BufBits:=Context^.BufBits and $f8; Value:=GetBits(16); if (((Value and $fff8)<>$ffd0) or ((Value and 7)<>NextRST)) then begin RaiseError; end; NextRST:=(NextRST+1) and 7; RSTCount:=Context^.RSTInterval; for Index:=0 to 2 do begin Context^.Components[Index].DCPred:=0; end; end; end; until false; end; break; end; $db{DQT}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if (DataPosition+TpvUInt32(Len))>=DataSize then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); while Len>=65 do begin Value:=PByteArray(DataPointer)^[DataPosition]; inc(DataPosition); dec(Len); if (Value and $fc)<>0 then begin RaiseError; end; Context^.QTUsed:=Context^.QTUsed or (1 shl Value); for Index:=0 to 63 do begin Context^.QTable[Value,Index]:=PByteArray(DataPointer)^[DataPosition]; inc(DataPosition); dec(Len); end; end; inc(DataPosition,Len); end; $dd{DRI}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if ((DataPosition+TpvUInt32(Len))>=DataSize) or (Len<4) then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); Context^.RSTInterval:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; inc(DataPosition,Len); end; $e1{EXIF}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if ((DataPosition+TpvUInt32(Len))>=DataSize) or (Len<18) then begin RaiseError; end; inc(DataPosition,2); dec(Len,2); NextDataPosition:=DataPosition+TpvUInt32(Len); if (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+0]))='E') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+1]))='x') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+2]))='i') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+3]))='f') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+4]))=#0) and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+5]))=#0) and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+6]))=TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+7]))) and (((TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+6]))='I') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+8]))='*') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+9]))=#0)) or ((TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+6]))='M') and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+8]))=#0) and (TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+9]))='*'))) then begin Context^.EXIFLE:=TpvRawByteChar(TpvUInt8(PByteArray(DataPointer)^[DataPosition+6]))='I'; if Len>=14 then begin if Context^.EXIFLE then begin Value:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+10]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+11]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+12]) shl 16) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+13]) shl 24); end else begin Value:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+10]) shl 24) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+11]) shl 16) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+12]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+13]) shl 0); end; inc(Value,6); if (Value>=14) and ((Value+2)<Len) then begin inc(DataPosition,Value); dec(Len,Value); if Context^.EXIFLE then begin Count:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+0]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+1]) shl 8); end else begin Count:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+1]) shl 0); end; inc(DataPosition,2); dec(Len,2); if Count<=(Len div 12) then begin while Count>0 do begin dec(Count); if Context^.EXIFLE then begin v0:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+0]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+1]) shl 8); v1:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+2]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+3]) shl 8); v2:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+4]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+5]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+6]) shl 16) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+7]) shl 24); v3:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+8]) shl 0) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+9]) shl 8); end else begin v0:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+1]) shl 0); v1:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+2]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+3]) shl 0); v2:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+4]) shl 24) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+5]) shl 16) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+6]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+7]) shl 0); v3:=(TpvInt32(PByteArray(DataPointer)^[DataPosition+8]) shl 8) or (TpvInt32(PByteArray(DataPointer)^[DataPosition+9]) shl 0); end; if (v0=$0213{YCbCrPositioning}) and (v1=$0003{SHORT}) and (v2=1{LENGTH}) then begin Context^.CoSitedChroma:=v3=2; break; end; inc(DataPosition,12); dec(Len,12); end; end; end; end; end; DataPosition:=NextDataPosition; end; $e0,$e2..$ef,$fe{Skip}:begin if (DataPosition+2)>=DataSize then begin RaiseError; end; Len:=(TpvUInt16(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1]; if (DataPosition+TpvUInt32(Len))>=DataSize then begin RaiseError; end; inc(DataPosition,Len); end; else begin RaiseError; end; end; end; except on e:EpvLoadJPEGImage do begin result:=false; end; on e:Exception do begin raise; end; end; finally if assigned(ImageData) and not result then begin FreeMem(ImageData); ImageData:=nil; end; Finalize(Context^); FreeMem(Context); end; end; end; end; {$endif} function ClampToByte(v:longint):byte; {$ifdef PurePascal} begin if v<0 then begin result:=0; end else if v>255 then begin result:=255; end else begin result:=v; end; end; {$else} {$ifdef cpu386} assembler; register; asm {cmp eax,255 cmovgt eax,255 test eax,eax cmovlt eax,0{} mov ecx,eax and ecx,$ffffff00 neg ecx sbb ecx,ecx or eax,ecx{} {mov ecx,255 sub ecx,eax sar ecx,31 or cl,al sar eax,31 not al and al,cl{} end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} constructor TpvJPEGEncoder.Create; begin inherited Create; fDataMemory:=nil; fDataMemorySize:=0; fTempChannelWords:=nil; fTempChannelBytes:=nil; fTempChannelSize:=0; end; destructor TpvJPEGEncoder.Destroy; begin if assigned(fDataMemory) then begin FreeMem(fDataMemory); end; if assigned(fTempChannelWords) then begin FreeMem(fTempChannelWords); end; if assigned(fTempChannelBytes) then begin FreeMem(fTempChannelBytes); end; inherited Destroy; end; procedure TpvJPEGEncoder.EmitByte(b:TpvUInt8); begin if fMaxCompressedDataSize>0 then begin if fCompressedDataPosition<fMaxCompressedDataSize then begin PpvJPEGEncoderUInt8Array(fCompressedData)^[fCompressedDataPosition]:=b; inc(fCompressedDataPosition); end; end else begin if fCompressedDataAllocated<(fCompressedDataPosition+1) then begin fCompressedDataAllocated:=(fCompressedDataPosition+1)*2; ReallocMem(fCompressedData,fCompressedDataAllocated); end; PpvJPEGEncoderUInt8Array(fCompressedData)^[fCompressedDataPosition]:=b; inc(fCompressedDataPosition); end; end; procedure TpvJPEGEncoder.EmitWord(w:word); begin EmitByte(w shr 8); EmitByte(w and $ff); end; procedure TpvJPEGEncoder.EmitMarker(m:TpvUInt8); begin EmitByte($ff); EmitByte(m); end; procedure TpvJPEGEncoder.EmitJFIFApp0; const M_APP0=$e0; begin EmitMarker(M_APP0); EmitWord(2+4+1+2+1+2+2+1+1); EmitByte($4a); EmitByte($46); EmitByte($49); EmitByte($46); EmitByte(0); EmitByte(1); // Major version EmitByte(1); // Minor version EmitByte(0); // Density unit EmitWord(1); EmitWord(1); EmitByte(0); // No thumbnail image EmitByte(0); end; procedure TpvJPEGEncoder.EmitDQT; const M_DQT=$db; var i,j,k:TpvInt32; begin if fCountComponents=3 then begin k:=2; end else begin k:=1; end; for i:=0 to k-1 do begin EmitMarker(M_DQT); EmitWord(64+1+2); EmitByte(i); for j:=0 to 63 do begin EmitByte(fQuantizationTables[i,j]); end; end; end; procedure TpvJPEGEncoder.EmitSOF; const M_SOF0=$c0; var i:TpvInt32; begin EmitMarker(M_SOF0); // baseline EmitWord((3*fCountComponents)+2+5+1); EmitByte(8); // precision EmitWord(fImageHeight); EmitWord(fImageWidth); EmitByte(fCountComponents); for i:=0 to fCountComponents-1 do begin EmitByte(i+1); // component ID EmitByte((fComponentHSamples[i] shl 4)+fComponentVSamples[i]); // h and v sampling if i>0 then begin // quant. table num EmitByte(1); end else begin EmitByte(0); end; end; end; procedure TpvJPEGEncoder.EmitDHT(Bits,Values:pansichar;Index:TpvInt32;ACFlag:boolean); const M_DHT=$c4; var i,l:TpvInt32; begin EmitMarker(M_DHT); l:=0; for i:=1 to 16 do begin inc(l,TpvUInt8(ansichar(Bits[i]))); end; EmitWord(l+2+1+16); if ACFlag then begin EmitByte(Index+16); end else begin EmitByte(Index); end; for i:=1 to 16 do begin EmitByte(TpvUInt8(ansichar(Bits[i]))); end; for i:=0 to l-1 do begin EmitByte(TpvUInt8(ansichar(Values[i]))); end; end; procedure TpvJPEGEncoder.EmitDHTs; begin EmitDHT(TpvPointer(@fHuffmanBits[0+0]),TpvPointer(@fHuffmanValues[0+0]),0,false); EmitDHT(TpvPointer(@fHuffmanBits[2+0]),TpvPointer(@fHuffmanValues[2+0]),0,true); if fCountComponents=3 then begin EmitDHT(TpvPointer(@fHuffmanBits[0+1]),TpvPointer(@fHuffmanValues[0+1]),1,false); EmitDHT(TpvPointer(@fHuffmanBits[2+1]),TpvPointer(@fHuffmanValues[2+1]),1,true); end; end; procedure TpvJPEGEncoder.EmitSOS; const M_SOS=$da; var i:TpvInt32; begin EmitMarker(M_SOS); EmitWord((2*fCountComponents)+2+1+3); EmitByte(fCountComponents); for i:=0 to fCountComponents-1 do begin EmitByte(i+1); if i=0 then begin EmitByte((0 shl 4)+0); end else begin EmitByte((1 shl 4)+1); end; end; EmitByte(0); // spectral selection EmitByte(63); EmitByte(0); end; procedure TpvJPEGEncoder.EmitMarkers; const M_SOI=$d8; begin EmitMarker(M_SOI); EmitJFIFApp0; EmitDQT; EmitSOF; EmitDHTS; EmitSOS; end; procedure TpvJPEGEncoder.ConvertRGBAToY(pDstY,pSrc:PpvJPEGEncoderUInt8Array;Count:TpvInt32); {$ifndef PurePascal}{$ifdef cpu386}stdcall;{$endif}{$endif} {$ifdef PurePascal} const YR=19595; YG=38470; YB=7471; var x,r,g,b:TpvInt32; begin for x:=1 to Count do begin r:=pSrc^[0]; g:=pSrc^[1]; b:=pSrc^[2]; pSrc:=TpvPointer(@pSrc^[4]); pDstY^[0]:=ClampToByte(SARLongint((r*YR)+(g*YG)+(b*YB)+32768,16)); pDstY:=TpvPointer(@pDstY^[1]); end; end; {$else} {$ifdef cpu386} {$ifdef UseAlternativeSIMDColorConversionImplementation} const YR=19595; YG=38470; YB=7471; MaskRED:array[0..15] of TpvUInt8=($ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00); MaskGREEN:array[0..15] of TpvUInt8=($00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00); MaskBLUE:array[0..15] of TpvUInt8=($00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00); YRCoeffs:array[0..7] of word=(19595,19595,19595,19595,19595,19595,19595,19595); YGCoeffs:array[0..7] of word=(38470,38470,38470,38470,38470,38470,38470,38470); YBCoeffs:array[0..7] of word=(7471,7471,7471,7471,7471,7471,7471,7471); {$else} const YR=9798; YG=19235; YB=3736; YA=16384; MaskOffGA:array[0..15] of TpvUInt8=($ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00); YAGCoeffs:array[0..7] of TpvInt16=(19235,0,19235,0,19235,0,19235,0); YRBCoeffs:array[0..7] of TpvInt16=(9798,3736,9798,3736,9798,3736,9798,3736); Add16384:array[0..3] of TpvUInt32=(16384,16384,16384,16384); {$endif} asm push eax push ebx push esi push edi mov edi,dword ptr pSrc mov ecx,dword ptr pDstY mov esi,dword ptr Count mov edx,esi and edx,7 shr esi,3 test esi,esi jz @Done1 {$ifdef UseAlternativeSIMDColorConversionImplementation} // Get 16-bit aligned memory space on the stack lea ebx,[esp-128] and ebx,$fffffff0 // Load constant stuff into 16-bit aligned memory offsets o the stack, since at least old delphi compiler versions puts these not always 16-TpvUInt8 aligned movdqu xmm0,dqword ptr MaskRED movdqa dqword ptr [ebx],xmm0 movdqu xmm0,dqword ptr MaskGREEN movdqa dqword ptr [ebx+16],xmm0 movdqu xmm0,dqword ptr MaskBLUE movdqa dqword ptr [ebx+32],xmm0 movdqu xmm0,dqword ptr YRCoeffs movdqa dqword ptr [ebx+48],xmm0 movdqu xmm0,dqword ptr YGCoeffs movdqa dqword ptr [ebx+64],xmm0 movdqu xmm0,dqword ptr YBCoeffs movdqa dqword ptr [ebx+80],xmm0 {$else} // Get 16-bit aligned memory space on the stack lea ebx,[esp-64] and ebx,$fffffff0 // Load constant stuff into 16-bit aligned memory offsets o the stack, since at least old delphi compiler versions puts these not always 16-TpvUInt8 aligned movdqu xmm0,dqword ptr MaskOffGA movdqa dqword ptr [ebx],xmm0 movdqu xmm0,dqword ptr YAGCoeffs movdqa dqword ptr [ebx+16],xmm0 movdqu xmm0,dqword ptr YRBCoeffs movdqa dqword ptr [ebx+32],xmm0 movdqu xmm0,dqword ptr Add16384 movdqa dqword ptr [ebx+48],xmm0 {$endif} test edi,$f jz @Loop1Aligned @Loop1Unaligned: {$ifdef UseAlternativeSIMDColorConversionImplementation} movdqu xmm0,[edi] // First four RGB32 pixel vector values movdqu xmm1,[edi+16] // Other four RGB32 pixel vector values add edi,32 // xmm5 = Eight red values (from xmm0 and xmm1) movdqa xmm5,xmm0 movdqa xmm6,xmm1 pand xmm5,dqword ptr [ebx] // MaskRED pand xmm6,dqword ptr [ebx] // MaskRED packssdw xmm5,xmm6 // xmm6 = Eight green values (from xmm0 and xmm1) movdqa xmm6,xmm0 movdqa xmm7,xmm1 pand xmm6,dqword ptr [ebx+16] // MaskGREEN psrld xmm6,8 pand xmm7,dqword ptr [ebx+16] // MaskGREEN psrld xmm7,8 packssdw xmm6,xmm7 // xmm7 = Eight blue values (from xmm0 and xmm1) movdqa xmm7,xmm0 movdqa xmm4,xmm1 pand xmm7,dqword ptr [ebx+32] // MaskBLUE psrld xmm7,16 pand xmm4,dqword ptr [ebx+32] // MaskBLUE psrld xmm4,16 packssdw xmm7,xmm4 // xmm0 = Eight Y values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm0,xmm5 pmulhuw xmm0,dqword ptr [ebx+48] // YRCoeffs movdqu xmm1,xmm6 pmulhuw xmm1,dqword ptr [ebx+64] // YGCoeffs paddw xmm0,xmm1 movdqu xmm1,xmm7 pmulhuw xmm1,dqword ptr [ebx+80] // YBCoeffs paddw xmm0,xmm1 packuswb xmm0,xmm0 // Store the Y result values movq qword ptr [ecx],xmm0 // Y add ecx,8 {$else} // xmm0 .. xmm3 = ga br vectors movdqa xmm4,dqword ptr [ebx] // MaskOffGA movdqu xmm0,dqword ptr [edi] movdqa xmm1,xmm0 psrlw xmm0,8 pand xmm1,xmm4 // MaskOffGA movdqu xmm2,dqword ptr [edi+16] movdqa xmm3,xmm2 psrlw xmm2,8 pand xmm3,xmm4 // MaskOffGA add edi,32 // Y movdqa xmm7,dqword ptr [ebx+16] // YAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // YAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+32] // YRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+48] // Add16384 psrld xmm4,15 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // YAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+32] // YRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+48] // Add16384 psrld xmm5,15 packssdw xmm4,xmm5 packuswb xmm4,xmm4 movq qword ptr [ecx],xmm4 // Y add ecx,8 {$endif} dec esi jnz @Loop1Unaligned jmp @Done1 @Loop1Aligned: {$ifdef UseAlternativeSIMDColorConversionImplementation} movdqa xmm0,[edi] // First four RGB32 pixel vector values movdqa xmm1,[edi+16] // Other four RGB32 pixel vector values add edi,32 // xmm5 = Eight red values (from xmm0 and xmm1) movdqa xmm5,xmm0 movdqa xmm6,xmm1 pand xmm5,dqword ptr [ebx] // MaskRED pand xmm6,dqword ptr [ebx] // MaskRED packssdw xmm5,xmm6 // xmm6 = Eight green values (from xmm0 and xmm1) movdqa xmm6,xmm0 movdqa xmm7,xmm1 pand xmm6,dqword ptr [ebx+16] // MaskGREEN psrld xmm6,8 pand xmm7,dqword ptr [ebx+16] // MaskGREEN psrld xmm7,8 packssdw xmm6,xmm7 // xmm7 = Eight blue values (from xmm0 and xmm1) movdqa xmm7,xmm0 movdqa xmm4,xmm1 pand xmm7,dqword ptr [ebx+32] // MaskBLUE psrld xmm7,16 pand xmm4,dqword ptr [ebx+32] // MaskBLUE psrld xmm4,16 packssdw xmm7,xmm4 // xmm0 = Eight Y values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm0,xmm5 pmulhuw xmm0,dqword ptr [ebx+48] // YRCoeffs movdqu xmm1,xmm6 pmulhuw xmm1,dqword ptr [ebx+64] // YGCoeffs paddw xmm0,xmm1 movdqu xmm1,xmm7 pmulhuw xmm1,dqword ptr [ebx+80] // YBCoeffs paddw xmm0,xmm1 packuswb xmm0,xmm0 // Store the Y result values movq qword ptr [ecx],xmm0 // Y add ecx,8 {$else} // xmm0 .. xmm3 = ga br vectors movdqa xmm4,dqword ptr [ebx] // MaskOffGA movdqa xmm0,dqword ptr [edi] movdqa xmm1,xmm0 psrlw xmm0,8 pand xmm1,xmm4 // MaskOffGA movdqu xmm2,dqword ptr [edi+16] movdqa xmm3,xmm2 psrlw xmm2,8 pand xmm3,xmm4 // MaskOffGA add edi,32 // Y movdqa xmm7,dqword ptr [ebx+16] // YAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // YAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+32] // YRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+48] // Add16384 psrld xmm4,15 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // YAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+32] // YRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+48] // Add16384 psrld xmm5,15 packssdw xmm4,xmm5 packuswb xmm4,xmm4 movq qword ptr [ecx],xmm4 // Y add ecx,8 {$endif} dec esi jnz @Loop1Aligned @Done1: test edx,edx jz @Done2 @Loop2: {$ifdef UseAlternativeSIMDColorConversionImplementation} // Y movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,YR shr eax,16 movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,YG shr ebx,16 add eax,ebx movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,YB shr ebx,16 add eax,ebx mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov TpvUInt8 ptr [ecx],al inc ecx {$else} // Y movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,YR movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,YG lea eax,[eax+ebx+YA] movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,YB add eax,ebx shr ebx,15 mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov TpvUInt8 ptr [ecx],al inc ecx {$endif} add edi,4 dec edx jnz @Loop2 @Done2: pop edi pop esi pop ebx pop eax end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} procedure TpvJPEGEncoder.ConvertRGBAToYCbCr(pDstY,pDstCb,pDstCr,pSrc:PpvJPEGEncoderUInt8Array;Count:TpvInt32); {$ifndef PurePascal}{$ifdef cpu386}stdcall;{$endif}{$endif} {$ifdef PurePascal} const YR=19595; YG=38470; YB=7471; Cb_R=-11059; Cb_G=-21709; Cb_B=32768; Cr_R=32768; Cr_G=-27439; Cr_B=-5329; var x,r,g,b:TpvInt32; begin for x:=0 to Count-1 do begin r:=pSrc^[0]; g:=pSrc^[1]; b:=pSrc^[2]; pSrc:=TpvPointer(@pSrc^[4]); pDstY^[x]:=ClampToByte(SARLongint((r*YR)+(g*YG)+(b*YB)+32768,16)); pDstCb^[x]:=ClampToByte(128+SARLongint((r*Cb_R)+(g*Cb_G)+(b*Cb_B)+32768,16)); pDstCr^[x]:=ClampToByte(128+SARLongint((r*Cr_R)+(g*Cr_G)+(b*Cr_B)+32768,16)); end; end; {$else} {$ifdef cpu386} {$ifdef UseAlternativeSIMDColorConversionImplementation} const YR=19595; YG=38470; YB=7471; Cb_R=-11059; Cb_G=-21709; Cb_B=32768; Cr_R=32768; Cr_G=-27439; Cr_B=-5329; MaskRED:array[0..15] of TpvUInt8=($ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00); MaskGREEN:array[0..15] of TpvUInt8=($00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00); MaskBLUE:array[0..15] of TpvUInt8=($00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00,$00,$00,$ff,$00); YRCoeffs:array[0..7] of word=(19595,19595,19595,19595,19595,19595,19595,19595); YGCoeffs:array[0..7] of word=(38470,38470,38470,38470,38470,38470,38470,38470); YBCoeffs:array[0..7] of word=(7471,7471,7471,7471,7471,7471,7471,7471); CbRCoeffs:array[0..7] of TpvInt16=(-11059,-11059,-11059,-11059,-11059,-11059,-11059,-11059); CbGCoeffs:array[0..7] of TpvInt16=(-21709,-21709,-21709,-21709,-21709,-21709,-21709,-21709); CbBCoeffs:array[0..7] of word=(32768,32768,32768,32768,32768,32768,32768,32768); CrRCoeffs:array[0..7] of word=(32768,32768,32768,32768,32768,32768,32768,32768); CrGCoeffs:array[0..7] of TpvInt16=(-27439,-27439,-27439,-27439,-27439,-27439,-27439,-27439); CrBCoeffs:array[0..7] of TpvInt16=(-5329,-5329,-5329,-5329,-5329,-5329,-5329,-5329); Add128:array[0..7] of word=($80,$80,$80,$80,$80,$80,$80,$80); {$else} const YR=9798; YG=19235; YB=3736; YA=16384; Cb_R=-11059; Cb_G=-21709; Cb_B=32767; Cb_A=32768; Cr_R=32767; Cr_G=-27439; Cr_B=-5329; Cr_A=32768; MaskOffGA:array[0..15] of TpvUInt8=($ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00); YAGCoeffs:array[0..7] of TpvInt16=(19235,0,19235,0,19235,0,19235,0); YRBCoeffs:array[0..7] of TpvInt16=(9798,3736,9798,3736,9798,3736,9798,3736); CbAGCoeffs:array[0..7] of TpvInt16=(-21709,0,-21709,0,-21709,0,-21709,0); CbRBCoeffs:array[0..7] of TpvInt16=(-11059,32767,-11059,32767,-11059,32767,-11059,32767); CrAGCoeffs:array[0..7] of TpvInt16=(-27439,0,-27439,0,-27439,0,-27439,0); CrRBCoeffs:array[0..7] of TpvInt16=(32767,-5329,32767,-5329,32767,-5329,32767,-5329); Add128:array[0..7] of word=(128,128,128,128,128,128,128,128); Add16384:array[0..3] of TpvUInt32=(16384,16384,16384,16384); Add32678:array[0..3] of TpvUInt32=(32768,32768,32768,32768); {$endif} asm push eax push ebx push esi push edi mov edi,dword ptr pSrc mov ecx,dword ptr pDstY mov esi,dword ptr Count shr esi,3 test esi,esi jz @Done1 mov edx,dword ptr pDstCb // Get 16-bit aligned memory space on the stack lea ebx,[esp-256] and ebx,$fffffff0 // Load constant stuff into 16-bit aligned memory offsets o the stack, since at least old delphi compiler versions puts these not always 16-TpvUInt8 aligned {$ifdef UseAlternativeSIMDColorConversionImplementation} movdqu xmm0,dqword ptr MaskRED movdqa dqword ptr [ebx],xmm0 movdqu xmm0,dqword ptr MaskGREEN movdqa dqword ptr [ebx+16],xmm0 movdqu xmm0,dqword ptr MaskBLUE movdqa dqword ptr [ebx+32],xmm0 movdqu xmm0,dqword ptr YRCoeffs movdqa dqword ptr [ebx+48],xmm0 movdqu xmm0,dqword ptr YGCoeffs movdqa dqword ptr [ebx+64],xmm0 movdqu xmm0,dqword ptr YBCoeffs movdqa dqword ptr [ebx+80],xmm0 movdqu xmm0,dqword ptr CbRCoeffs movdqa dqword ptr [ebx+96],xmm0 movdqu xmm0,dqword ptr CbGCoeffs movdqa dqword ptr [ebx+112],xmm0 movdqu xmm0,dqword ptr CbBCoeffs movdqa dqword ptr [ebx+128],xmm0 movdqu xmm0,dqword ptr CrRCoeffs movdqa dqword ptr [ebx+144],xmm0 movdqu xmm0,dqword ptr CrGCoeffs movdqa dqword ptr [ebx+160],xmm0 movdqu xmm0,dqword ptr CrBCoeffs movdqa dqword ptr [ebx+176],xmm0 movdqu xmm0,dqword ptr [Add128] movdqa dqword ptr [ebx+192],xmm0 {$else} movdqu xmm0,dqword ptr MaskOffGA movdqa dqword ptr [ebx],xmm0 movdqu xmm0,dqword ptr YAGCoeffs movdqa dqword ptr [ebx+16],xmm0 movdqu xmm0,dqword ptr YRBCoeffs movdqa dqword ptr [ebx+32],xmm0 movdqu xmm0,dqword ptr CbAGCoeffs movdqa dqword ptr [ebx+48],xmm0 movdqu xmm0,dqword ptr CbRBCoeffs movdqa dqword ptr [ebx+64],xmm0 movdqu xmm0,dqword ptr CrAGCoeffs movdqa dqword ptr [ebx+80],xmm0 movdqu xmm0,dqword ptr CrRBCoeffs movdqa dqword ptr [ebx+96],xmm0 movdqu xmm0,dqword ptr Add128 movdqa dqword ptr [ebx+112],xmm0 movdqu xmm0,dqword ptr Add16384 movdqa dqword ptr [ebx+128],xmm0 movdqu xmm0,dqword ptr Add32678 movdqa dqword ptr [ebx+144],xmm0 {$endif} test edi,$f jz @Loop1Aligned @Loop1Unaligned: {$ifdef UseAlternativeSIMDColorConversionImplementation} movdqu xmm0,[edi] // First four RGB32 pixel vector values movdqu xmm1,[edi+16] // Other four RGB32 pixel vector values add edi,32 // xmm5 = Eight red values (from xmm0 and xmm1) movdqa xmm5,xmm0 movdqa xmm6,xmm1 pand xmm5,dqword ptr [ebx] // MaskRED pand xmm6,dqword ptr [ebx] // MaskRED packssdw xmm5,xmm6 // xmm6 = Eight green values (from xmm0 and xmm1) movdqa xmm6,xmm0 movdqa xmm7,xmm1 pand xmm6,dqword ptr [ebx+16] // MaskGREEN psrld xmm6,8 pand xmm7,dqword ptr [ebx+16] // MaskGREEN psrld xmm7,8 packssdw xmm6,xmm7 // xmm7 = Eight blue values (from xmm0 and xmm1) movdqa xmm7,xmm0 movdqa xmm4,xmm1 pand xmm7,dqword ptr [ebx+32] // MaskBLUE psrld xmm7,16 pand xmm4,dqword ptr [ebx+32] // MaskBLUE psrld xmm4,16 packssdw xmm7,xmm4 // xmm0 = Eight Y values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm0,xmm5 pmulhuw xmm0,dqword ptr [ebx+48] // YRCoeffs movdqu xmm1,xmm6 pmulhuw xmm1,dqword ptr [ebx+64] // YGCoeffs paddw xmm0,xmm1 movdqu xmm1,xmm7 pmulhuw xmm1,dqword ptr [ebx+80] // YBCoeffs paddw xmm0,xmm1 packuswb xmm0,xmm0 // xmm1 = Eight Cb values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm1,xmm5 pmulhw xmm1,dqword ptr [ebx+96] // CbRCoeffs movdqu xmm2,xmm6 pmulhw xmm2,dqword ptr [ebx+112] // CbGCoeffs paddw xmm1,xmm2 movdqu xmm2,xmm7 pmulhuw xmm2,dqword ptr [ebx+128] // CbBCoeffs paddw xmm1,xmm2 paddw xmm1,dqword ptr [ebx+192] // Add128 packuswb xmm1,xmm1 // xmm2 = Eight Cr values movdqu xmm2,xmm5 pmulhuw xmm2,dqword ptr [ebx+144] // CrRCoeffs movdqu xmm3,xmm6 pmulhw xmm3,dqword ptr [ebx+160] // CrGCoeffs paddw xmm2,xmm3 movdqu xmm3,xmm7 pmulhw xmm3,dqword ptr [ebx+176] // CrBCoeffs paddw xmm2,xmm3 paddw xmm2,dqword ptr [ebx+192] // Add128 packuswb xmm2,xmm2 // Store the YCbCr result values to separate arrays at different memory locations movq qword ptr [ecx],xmm0 // Y add ecx,8 movq qword ptr [edx],xmm1 // Cb add edx,8 mov eax,dword ptr pDstCr movq qword ptr [eax],xmm2 // Ct add eax,8 mov dword ptr pDstCr,eax {$else} // xmm0 .. xmm3 = ga br vectors movdqa xmm4,dqword ptr [ebx] // MaskOffGA movdqu xmm0,dqword ptr [edi] movdqa xmm1,xmm0 psrlw xmm0,8 pand xmm1,xmm4 // MaskOffGA movdqu xmm2,dqword ptr [edi+16] movdqa xmm3,xmm2 psrlw xmm2,8 pand xmm3,xmm4 // MaskOffGA add edi,32 // Y movdqa xmm7,dqword ptr [ebx+16] // YAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // YAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+32] // YRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+128] // Add16384 psrld xmm4,15 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // YAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+32] // YRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+128] // Add16384 psrld xmm5,15 packssdw xmm4,xmm5 packuswb xmm4,xmm4 movq qword ptr [ecx],xmm4 // Y add ecx,8 // Cb movdqa xmm7,dqword ptr [ebx+48] // CbAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // CbAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+64] // CbRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+144] // Add32768 psrad xmm4,16 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // CbAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+64] // CbRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+144] // Add32768 psrad xmm5,16 packssdw xmm4,xmm5 paddw xmm4,dqword ptr [ebx+112] // Add128 packuswb xmm4,xmm4 movq qword ptr [edx],xmm4 // Cb add edx,8 // Cr movdqa xmm7,dqword ptr [ebx+80] // CrAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // CrAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+96] // CrRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+144] // Add32768 psrad xmm4,16 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // CrAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+96] // CrRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+144] // Add32768 psrad xmm5,16 packssdw xmm4,xmm5 paddw xmm4,dqword ptr [ebx+112] // Add128 packuswb xmm4,xmm4 mov eax,dword ptr pDstCr movq qword ptr [eax],xmm4 // Ct add eax,8 mov dword ptr pDstCr,eax {$endif} dec esi jnz @Loop1Unaligned jmp @Loop1UnalignedDone @Loop1Aligned: {$ifdef UseAlternativeSIMDColorConversionImplementation} movdqa xmm0,[edi] // First four RGB32 pixel vector values movdqa xmm1,[edi+16] // Other four RGB32 pixel vector values add edi,32 // xmm5 = Eight red values (from xmm0 and xmm1) movdqa xmm5,xmm0 movdqa xmm6,xmm1 pand xmm5,dqword ptr [ebx] // MaskRED pand xmm6,dqword ptr [ebx] // MaskRED packssdw xmm5,xmm6 // xmm6 = Eight green values (from xmm0 and xmm1) movdqa xmm6,xmm0 movdqa xmm7,xmm1 pand xmm6,dqword ptr [ebx+16] // MaskGREEN psrld xmm6,8 pand xmm7,dqword ptr [ebx+16] // MaskGREEN psrld xmm7,8 packssdw xmm6,xmm7 // xmm7 = Eight blue values (from xmm0 and xmm1) movdqa xmm7,xmm0 movdqa xmm4,xmm1 pand xmm7,dqword ptr [ebx+32] // MaskBLUE psrld xmm7,16 pand xmm4,dqword ptr [ebx+32] // MaskBLUE psrld xmm4,16 packssdw xmm7,xmm4 // xmm0 = Eight Y values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm0,xmm5 pmulhuw xmm0,dqword ptr [ebx+48] // YRCoeffs movdqu xmm1,xmm6 pmulhuw xmm1,dqword ptr [ebx+64] // YGCoeffs paddw xmm0,xmm1 movdqu xmm1,xmm7 pmulhuw xmm1,dqword ptr [ebx+80] // YBCoeffs paddw xmm0,xmm1 packuswb xmm0,xmm0 // xmm1 = Eight Cb values (from xmm5/red, xmm6/green and xmm7/blue) movdqu xmm1,xmm5 pmulhw xmm1,dqword ptr [ebx+96] // CbRCoeffs movdqu xmm2,xmm6 pmulhw xmm2,dqword ptr [ebx+112] // CbGCoeffs paddw xmm1,xmm2 movdqu xmm2,xmm7 pmulhuw xmm2,dqword ptr [ebx+128] // CbBCoeffs paddw xmm1,xmm2 paddw xmm1,dqword ptr [ebx+192] // Add128 packuswb xmm1,xmm1 // xmm2 = Eight Cr values movdqu xmm2,xmm5 pmulhuw xmm2,dqword ptr [ebx+144] // CrRCoeffs movdqu xmm3,xmm6 pmulhw xmm3,dqword ptr [ebx+160] // CrGCoeffs paddw xmm2,xmm3 movdqu xmm3,xmm7 pmulhw xmm3,dqword ptr [ebx+176] // CrBCoeffs paddw xmm2,xmm3 paddw xmm2,dqword ptr [ebx+192] // Add128 packuswb xmm2,xmm2 // Store the YCbCr result values to separate arrays at different memory locations movq qword ptr [ecx],xmm0 // Y add ecx,8 movq qword ptr [edx],xmm1 // Cb add edx,8 mov eax,dword ptr pDstCr movq qword ptr [eax],xmm2 // Ct add eax,8 mov dword ptr pDstCr,eax {$else} // xmm0 .. xmm3 = ga br vectors movdqa xmm4,dqword ptr [ebx] // MaskOffGA movdqa xmm0,dqword ptr [edi] movdqa xmm1,xmm0 psrlw xmm0,8 pand xmm1,xmm4 // MaskOffGA movdqa xmm2,dqword ptr [edi+16] movdqa xmm3,xmm2 psrlw xmm2,8 pand xmm3,xmm4 // MaskOffGA add edi,32 // Y movdqa xmm7,dqword ptr [ebx+16] // YAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // YAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+32] // YRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+128] // Add16384 psrld xmm4,15 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // YAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+32] // YRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+128] // Add16384 psrld xmm5,15 packssdw xmm4,xmm5 packuswb xmm4,xmm4 movq qword ptr [ecx],xmm4 // Y add ecx,8 // Cb movdqa xmm7,dqword ptr [ebx+48] // CbAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // CbAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+64] // CbRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+144] // Add32768 psrad xmm4,16 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // CbAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+64] // CbRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+144] // Add32768 psrad xmm5,16 packssdw xmm4,xmm5 paddw xmm4,dqword ptr [ebx+112] // Add128 packuswb xmm4,xmm4 movq qword ptr [edx],xmm4 // Cb add edx,8 // Cr movdqa xmm7,dqword ptr [ebx+80] // CrAGCoeffs movdqa xmm4,xmm0 pmaddwd xmm4,xmm7 // CrAGCoeffs movdqa xmm5,xmm1 pmaddwd xmm5,dqword ptr [ebx+96] // CrRBCoeffs paddd xmm4,xmm5 paddd xmm4,dqword ptr [ebx+144] // Add32768 psrad xmm4,16 movdqa xmm5,xmm2 pmaddwd xmm5,xmm7 // CrAGCoeffs movdqa xmm6,xmm3 pmaddwd xmm6,dqword ptr [ebx+96] // CrRBCoeffs paddd xmm5,xmm6 paddd xmm5,dqword ptr [ebx+144] // Add32768 psrad xmm5,16 packssdw xmm4,xmm5 paddw xmm4,dqword ptr [ebx+112] // Add128 packuswb xmm4,xmm4 mov eax,dword ptr pDstCr movq qword ptr [eax],xmm4 // Ct add eax,8 mov dword ptr pDstCr,eax {$endif} dec esi jnz @Loop1Aligned @Loop1UnalignedDone: mov dword ptr pDstCb,edx @Done1: mov esi,dword ptr Count and esi,7 test esi,esi jz @Done2 @Loop2: {$ifdef UseAlternativeSIMDColorConversionImplementation} // Y movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,YR shr eax,16 movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,YG shr ebx,16 add eax,ebx movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,YB shr ebx,16 add eax,ebx mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov TpvUInt8 ptr [ecx],al inc ecx // Cb movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,Cb_R sar eax,16 movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,Cb_G sar ebx,16 add eax,ebx movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,Cb_B shr ebx,16 lea eax,[eax+ebx+128] mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov edx,dword ptr pDstCb mov TpvUInt8 ptr [edx],al inc dword ptr pDstCb // Cr movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,Cr_R shr eax,16 movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,Cr_G sar ebx,16 add eax,ebx movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,Cr_B sar ebx,16 lea eax,[eax+ebx+128] mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov edx,dword ptr pDstCr mov TpvUInt8 ptr [edx],al inc dword ptr pDstCr {$else} // Y movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,YR movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,YG lea eax,[eax+ebx+YA] movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,YB add eax,ebx shr ebx,15 mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov TpvUInt8 ptr [ecx],al inc ecx // Cb movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,Cb_R movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,Cb_G lea eax,[eax+ebx+Cb_A] movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,Cb_B add eax,ebx sar eax,16 add eax,128 mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov edx,dword ptr pDstCb mov TpvUInt8 ptr [edx],al inc dword ptr pDstCb // Cr movzx eax,TpvUInt8 ptr [edi+0] imul eax,eax,Cr_R movzx ebx,TpvUInt8 ptr [edi+1] imul ebx,ebx,Cr_G lea eax,[eax+ebx+Cr_A] movzx ebx,TpvUInt8 ptr [edi+2] imul ebx,ebx,Cr_B add eax,ebx sar eax,16 add eax,128 mov ebx,eax and ebx,$ffffff00 neg ebx sbb ebx,ebx or eax,ebx mov edx,dword ptr pDstCr mov TpvUInt8 ptr [edx],al inc dword ptr pDstCr {$endif} add edi,4 dec esi jnz @Loop2 @Done2: pop edi pop esi pop ebx pop eax end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} procedure TpvJPEGEncoder.ComputeHuffmanTable(Codes:PpvJPEGEncoderUInt32Array;CodeSizes,Bits,Values:PpvJPEGEncoderUInt8Array); var i,l,LastP,si,p:TpvInt32; HuffmanSizes:array[0..256] of TpvUInt8; HuffmanCodes:array[0..256] of TpvUInt32; Code:TpvUInt32; begin p:=0; for l:=1 to 16 do begin for i:=1 to Bits^[l] do begin HuffmanSizes[p]:=l; inc(p); end; end; HuffmanSizes[p]:=0; LastP:=p; Code:=0; si:=HuffmanSizes[0]; p:=0; while HuffmanSizes[p]<>0 do begin while HuffmanSizes[p]=si do begin HuffmanCodes[p]:=Code; inc(p); inc(Code); end; Code:=Code shl 1; inc(si); end; FillChar(Codes^[0],SizeOf(TpvUInt32)*256,#0); FillChar(CodeSizes^[0],SizeOf(TpvUInt8)*256,#0); for p:=0 to LastP-1 do begin Codes^[Values^[p]]:=HuffmanCodes[p]; CodeSizes^[Values^[p]]:=HuffmanSizes[p]; end; end; function TpvJPEGEncoder.InitFirstPass:boolean; begin fBitsBuffer:=0; fBitsBufferSize:=0; FillChar(fLastDCValues,SizeOf(fLastDCValues),#0); fMCUYOffset:=0; fPassIndex:=1; result:=true; end; function TpvJPEGEncoder.InitSecondPass:boolean; begin ComputeHuffmanTable(TpvPointer(@fHuffmanCodes[0+0,0]),TpvPointer(@fHuffmanCodeSizes[0+0,0]),TpvPointer(@fHuffmanBits[0+0]),TpvPointer(@fHuffmanValues[0+0])); ComputeHuffmanTable(TpvPointer(@fHuffmanCodes[2+0,0]),TpvPointer(@fHuffmanCodeSizes[2+0,0]),TpvPointer(@fHuffmanBits[2+0]),TpvPointer(@fHuffmanValues[2+0])); if fCountComponents>1 then begin ComputeHuffmanTable(TpvPointer(@fHuffmanCodes[0+1,0]),TpvPointer(@fHuffmanCodeSizes[0+1,0]),TpvPointer(@fHuffmanBits[0+1]),TpvPointer(@fHuffmanValues[0+1])); ComputeHuffmanTable(TpvPointer(@fHuffmanCodes[2+1,0]),TpvPointer(@fHuffmanCodeSizes[2+1,0]),TpvPointer(@fHuffmanBits[2+1]),TpvPointer(@fHuffmanValues[2+1])); end; InitFirstPass; EmitMarkers; fPassIndex:=2; result:=true; end; procedure TpvJPEGEncoder.ComputeQuantizationTable(pDst:PpvJPEGEncoderInt32Array;pSrc:PpvJPEGEncoderInt16Array); var q,i,j:TpvInt32; begin if fQuality<50 then begin q:=5000 div fQuality; end else begin q:=200-(fQuality*2); end; for i:=0 to 63 do begin j:=((pSrc^[i]*q)+50) div 100; if j<1 then begin j:=1; end else if j>255 then begin j:=255; end; pDst^[i]:=j; end; end; function TpvJPEGEncoder.Setup(Width,Height:TpvInt32):boolean; const StandardLumaQuantizationTable:array[0..63] of TpvInt16=(16,11,12,14,12,10,16,14,13,14,18,17,16,19,24,40,26,24,22,22,24,49,35,37,29,40,58,51,61,60,57,51,56,55,64,72,92,78,64,68,87,69,55,56,80,109,81,87,95,98,103,104,103,62,77,113,121,112,100,120,92,101,103,99); StandardChromaQuantizationTable:array[0..63] of TpvInt16=(17,18,18,24,21,24,47,26,26,47,99,66,56,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99); DCLumaBits:array[0..16] of TpvUInt8=(0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0); DCLumaValues:array[0..JPEG_DC_LUMA_CODES-1] of TpvUInt8=(0,1,2,3,4,5,6,7,8,9,10,11); ACLumaBits:array[0..16] of TpvUInt8=(0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,$7d); ACLumaValues:array[0..JPEG_AC_LUMA_CODES-1] of TpvUInt8=( $01,$02,$03,$00,$04,$11,$05,$12,$21,$31,$41,$06,$13,$51,$61,$07,$22,$71,$14,$32,$81,$91,$a1,$08,$23,$42,$b1,$c1,$15,$52,$d1,$f0, $24,$33,$62,$72,$82,$09,$0a,$16,$17,$18,$19,$1a,$25,$26,$27,$28,$29,$2a,$34,$35,$36,$37,$38,$39,$3a,$43,$44,$45,$46,$47,$48,$49, $4a,$53,$54,$55,$56,$57,$58,$59,$5a,$63,$64,$65,$66,$67,$68,$69,$6a,$73,$74,$75,$76,$77,$78,$79,$7a,$83,$84,$85,$86,$87,$88,$89, $8a,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$c2,$c3,$c4,$c5, $c6,$c7,$c8,$c9,$ca,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8, $f9,$fa,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ); DCChromaBits:array[0..16] of TpvUInt8=(0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0); DCChromaValues:array[0..JPEG_DC_CHROMA_CODES-1] of TpvUInt8=(0,1,2,3,4,5,6,7,8,9,10,11); ACChromaBits:array[0..16] of TpvUInt8=(0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,$77); ACChromaValues:array[0..JPEG_AC_CHROMA_CODES-1] of TpvUInt8=( $00,$01,$02,$03,$11,$04,$05,$21,$31,$06,$12,$41,$51,$07,$61,$71,$13,$22,$32,$81,$08,$14,$42,$91,$a1,$b1,$c1,$09,$23,$33,$52,$f0, $15,$62,$72,$d1,$0a,$16,$24,$34,$e1,$25,$f1,$17,$18,$19,$1a,$26,$27,$28,$29,$2a,$35,$36,$37,$38,$39,$3a,$43,$44,$45,$46,$47,$48, $49,$4a,$53,$54,$55,$56,$57,$58,$59,$5a,$63,$64,$65,$66,$67,$68,$69,$6a,$73,$74,$75,$76,$77,$78,$79,$7a,$82,$83,$84,$85,$86,$87, $88,$89,$8a,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$c2,$c3, $c4,$c5,$c6,$c7,$c8,$c9,$ca,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$f2,$f3,$f4,$f5,$f6,$f7,$f8, $f9,$fa,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ); var c:TpvInt32; DataSize:TpvUInt32; begin case fBlockEncodingMode of 0:begin // Greyscale fCountComponents:=1; fComponentHSamples[0]:=1; fComponentVSamples[0]:=1; fMCUWidth:=8; fMCUHeight:=8; end; 1:begin // H1V1 fCountComponents:=3; fComponentHSamples[0]:=1; fComponentVSamples[0]:=1; fComponentHSamples[1]:=1; fComponentVSamples[1]:=1; fComponentHSamples[2]:=1; fComponentVSamples[2]:=1; fMCUWidth:=8; fMCUHeight:=8; end; 2:begin // H2V1 fCountComponents:=3; fComponentHSamples[0]:=2; fComponentVSamples[0]:=1; fComponentHSamples[1]:=1; fComponentVSamples[1]:=1; fComponentHSamples[2]:=1; fComponentVSamples[2]:=1; fMCUWidth:=16; fMCUHeight:=8; end; else {3:}begin // H2V2 fCountComponents:=3; fComponentHSamples[0]:=2; fComponentVSamples[0]:=2; fComponentHSamples[1]:=1; fComponentVSamples[1]:=1; fComponentHSamples[2]:=1; fComponentVSamples[2]:=1; fMCUWidth:=16; fMCUHeight:=16; end; end; fImageWidth:=Width; fImageHeight:=Height; fImageWidthMCU:=((fImageWidth+fMCUWidth)-1) and not (fMCUWidth-1); fImageHeightMCU:=((fImageHeight+fMCUHeight)-1) and not (fMCUHeight-1); fMCUsPerRow:=fImageWidthMCU div fMCUWidth; DataSize:=fImageWidthMCU*fMCUHeight*3; if (not assigned(fDataMemory)) or (fDataMemorySize<DataSize) then begin fDataMemorySize:=DataSize; if assigned(fDataMemory) then begin ReallocMem(fDataMemory,fDataMemorySize); end else begin GetMem(fDataMemory,fDataMemorySize); end; end; for c:=0 to 2 do begin fMCUChannels[c]:=@PpvJPEGEncoderUInt8Array(fDataMemory)^[fImageWidthMCU*fMCUHeight*c]; end; if (not (assigned(fTempChannelWords) and assigned(fTempChannelBytes))) or (fTempChannelSize<fImageWidth) then begin fTempChannelSize:=fImageWidth; if assigned(fTempChannelBytes) then begin ReallocMem(fTempChannelBytes,SizeOf(TpvUInt8)*fTempChannelSize); end else begin GetMem(fTempChannelBytes,SizeOf(TpvUInt8)*fTempChannelSize); end; if assigned(fTempChannelWords) then begin ReallocMem(fTempChannelWords,SizeOf(word)*fTempChannelSize); end else begin GetMem(fTempChannelWords,SizeOf(word)*fTempChannelSize); end; end; ComputeQuantizationTable(TpvPointer(@fQuantizationTables[0]),TpvPointer(@StandardLumaQuantizationTable)); if fNoChromaDiscrimination then begin ComputeQuantizationTable(TpvPointer(@fQuantizationTables[1]),TpvPointer(@StandardLumaQuantizationTable)); end else begin ComputeQuantizationTable(TpvPointer(@fQuantizationTables[1]),TpvPointer(@StandardChromaQuantizationTable)); end; fOutputBufferLeft:=JPEG_OUTPUT_BUFFER_SIZE; fOutputBufferCount:=0; fOutputBufferPointer:=TpvPointer(@fOutputBuffer[0]); if fTwoPass then begin FillChar(fHuffmanCounts,SizeOf(fHuffmanCounts),#0); InitFirstPass; end else begin Move(DCLumaBits,fHuffmanBits[0+0],17); Move(DCLumaValues,fHuffmanValues[0+0],JPEG_DC_LUMA_CODES); Move(ACLumaBits,fHuffmanBits[2+0],17); Move(ACLumaValues,fHuffmanValues[2+0],JPEG_AC_LUMA_CODES); Move(DCChromaBits,fHuffmanBits[0+1],17); Move(DCChromaValues,fHuffmanValues[0+1],JPEG_DC_CHROMA_CODES); Move(ACChromaBits,fHuffmanBits[2+1],17); Move(ACChromaValues,fHuffmanValues[2+1],JPEG_AC_CHROMA_CODES); if not InitSecondPass then begin result:=false; exit; end; end; result:=true; end; procedure TpvJPEGEncoder.FlushOutputBuffer; var i:TpvInt32; begin if fOutputBufferCount>0 then begin for i:=0 to fOutputBufferCount-1 do begin EmitByte(fOutputBuffer[i]); end; end; fOutputBufferPointer:=TpvPointer(@fOutputBuffer[0]); fOutputBufferLeft:=JPEG_OUTPUT_BUFFER_SIZE; fOutputBufferCount:=0; end; procedure TpvJPEGEncoder.PutBits(Bits,Len:TpvUInt32); var c:TpvUInt32; begin inc(fBitsBufferSize,Len); fBitsBuffer:=fBitsBuffer or (Bits shl (24-fBitsBufferSize)); while fBitsBufferSize>=8 do begin c:=(fBitsBuffer shr 16) and $ff; fOutputBufferPointer^:=c; inc(fOutputBufferPointer); inc(fOutputBufferCount); dec(fOutputBufferLeft); if fOutputBufferLeft=0 then begin FlushOutputBuffer; end; if c=$ff then begin fOutputBufferPointer^:=0; inc(fOutputBufferPointer); inc(fOutputBufferCount); dec(fOutputBufferLeft); if fOutputBufferLeft=0 then begin FlushOutputBuffer; end; end; fBitsBuffer:=fBitsBuffer shl 8; dec(fBitsBufferSize,8); end; end; procedure TpvJPEGEncoder.LoadBlock8x8(x,y,c:TpvInt32); {$ifdef PurePascal} {$ifdef cpu64} type PInt64=^int64; var i,w:TpvInt32; pSrc:PpvJPEGEncoderUInt8Array; r0,r1,r2,r3,r4,r5,r6,r7,r8:int64; begin pSrc:=TpvPointer(@fMCUChannels[c]^[((y shl 3)*fImageWidthMCU)+(x shl 3)]); w:=fImageWidthMCU; // Load into registers (hopefully, when the optimizer by the compiler isn't dumb) r0:=int64(TpvPointer(@pSrc^[0])^); r1:=int64(TpvPointer(@pSrc^[w])^); r2:=int64(TpvPointer(@pSrc^[w*2])^); r3:=int64(TpvPointer(@pSrc^[w*3])^); r4:=int64(TpvPointer(@pSrc^[w*4])^); r5:=int64(TpvPointer(@pSrc^[w*5])^); r6:=int64(TpvPointer(@pSrc^[w*6])^); r7:=int64(TpvPointer(@pSrc^[w*7])^); // Write back from registers (hopefully, when the optimizer by the compiler isn't dumb) int64(TpvPointer(@fSamples8Bit[0])^):=r0; int64(TpvPointer(@fSamples8Bit[8])^):=r1; int64(TpvPointer(@fSamples8Bit[16])^):=r2; int64(TpvPointer(@fSamples8Bit[24])^):=r3; int64(TpvPointer(@fSamples8Bit[32])^):=r4; int64(TpvPointer(@fSamples8Bit[40])^):=r5; int64(TpvPointer(@fSamples8Bit[48])^):=r6; int64(TpvPointer(@fSamples8Bit[56])^):=r7; end; {$else} {$ifdef MoreCompact} type PInt64=^int64; var i,w:TpvInt32; pSrc:PpvJPEGEncoderUInt8Array; pDst:PInt64; begin w:=fImageWidthMCU; pSrc:=TpvPointer(@fMCUChannels[c]^[((y shl 3)*w)+(x shl 3)]); pDst:=TpvPointer(@fSamples8Bit[0]); for i:=0 to 7 do begin pDst^:=int64(TpvPointer(pSrc)^); inc(pDst); pSrc:=TpvPointer(@pSrc^[w]); end; end; {$else} type PInt64=^int64; var i,w:TpvInt32; pSrc:PpvJPEGEncoderUInt8Array; begin pSrc:=TpvPointer(@fMCUChannels[c]^[((y shl 3)*fImageWidthMCU)+(x shl 3)]); w:=fImageWidthMCU; TpvUInt32(TpvPointer(@fSamples8Bit[0])^):=TpvUInt32(TpvPointer(@pSrc^[0])^); TpvUInt32(TpvPointer(@fSamples8Bit[4])^):=TpvUInt32(TpvPointer(@pSrc^[4])^); TpvUInt32(TpvPointer(@fSamples8Bit[8])^):=TpvUInt32(TpvPointer(@pSrc^[w])^); TpvUInt32(TpvPointer(@fSamples8Bit[12])^):=TpvUInt32(TpvPointer(@pSrc^[w+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[16])^):=TpvUInt32(TpvPointer(@pSrc^[w*2])^); TpvUInt32(TpvPointer(@fSamples8Bit[20])^):=TpvUInt32(TpvPointer(@pSrc^[(w*2)+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[24])^):=TpvUInt32(TpvPointer(@pSrc^[w*3])^); TpvUInt32(TpvPointer(@fSamples8Bit[28])^):=TpvUInt32(TpvPointer(@pSrc^[(w*3)+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[32])^):=TpvUInt32(TpvPointer(@pSrc^[w*4])^); TpvUInt32(TpvPointer(@fSamples8Bit[36])^):=TpvUInt32(TpvPointer(@pSrc^[(w*4)+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[40])^):=TpvUInt32(TpvPointer(@pSrc^[w*5])^); TpvUInt32(TpvPointer(@fSamples8Bit[44])^):=TpvUInt32(TpvPointer(@pSrc^[(w*5)+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[48])^):=TpvUInt32(TpvPointer(@pSrc^[w*6])^); TpvUInt32(TpvPointer(@fSamples8Bit[52])^):=TpvUInt32(TpvPointer(@pSrc^[(w*6)+4])^); TpvUInt32(TpvPointer(@fSamples8Bit[56])^):=TpvUInt32(TpvPointer(@pSrc^[w*7])^); TpvUInt32(TpvPointer(@fSamples8Bit[60])^):=TpvUInt32(TpvPointer(@pSrc^[(w*7)+4])^); end; {$endif} {$endif} {$else} {$ifdef cpu386} var pSrc,pDst:TpvPointer; w:TpvInt32; begin pSrc:=TpvPointer(@fMCUChannels[c]^[((y shl 3)*fImageWidthMCU)+(x shl 3)]); pDst:=TpvPointer(@fSamples8Bit[0]); w:=fImageWidthMCU; asm mov eax,dword ptr pSrc mov edx,dword ptr pDst mov ecx,dword ptr w {$ifdef MoreCompact} push esi mov esi,8 @loop: movq xmm0,qword ptr [eax] add eax,ecx movq qword ptr [edx],xmm0 add edx,8 dec esi jne @loop pop esi {$else} // Load into registers movq xmm0,qword ptr [eax] add eax,ecx movq xmm1,qword ptr [eax] add eax,ecx movq xmm2,qword ptr [eax] add eax,ecx movq xmm3,qword ptr [eax] add eax,ecx movq xmm4,qword ptr [eax] add eax,ecx movq xmm5,qword ptr [eax] add eax,ecx movq xmm6,qword ptr [eax] movq xmm7,qword ptr [eax+ecx] // Write back from registers movq qword ptr [edx],xmm0 movq qword ptr [edx+8],xmm1 movq qword ptr [edx+16],xmm2 movq qword ptr [edx+24],xmm3 movq qword ptr [edx+32],xmm4 movq qword ptr [edx+40],xmm5 movq qword ptr [edx+48],xmm6 movq qword ptr [edx+56],xmm7 {$endif} end; end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} procedure TpvJPEGEncoder.LoadBlock16x8(x,c:TpvInt32); {$ifdef PurePascal} var a,b,i,t,w:TpvInt32; pDst,pSrc,pSrc1,pSrc2:PpvJPEGEncoderUInt8Array; begin a:=0; b:=2; w:=fImageWidthMCU; pDst:=TpvPointer(@fSamples8Bit[0]); pSrc:=TpvPointer(@fMCUChannels[c]^[x shl 4]); for i:=0 to 7 do begin pSrc1:=pSrc; pSrc2:=TpvPointer(@pSrc1^[w]); pSrc:=TpvPointer(@pSrc2^[w]); pDst^[0]:=(pSrc1^[0]+pSrc1^[1]+pSrc2^[0]+pSrc2^[1]+a) shr 2; pDst^[1]:=(pSrc1^[2]+pSrc1^[3]+pSrc2^[2]+pSrc2^[3]+b) shr 2; pDst^[2]:=(pSrc1^[4]+pSrc1^[5]+pSrc2^[4]+pSrc2^[5]+a) shr 2; pDst^[3]:=(pSrc1^[6]+pSrc1^[7]+pSrc2^[6]+pSrc2^[7]+b) shr 2; pDst^[4]:=(pSrc1^[8]+pSrc1^[9]+pSrc2^[8]+pSrc2^[9]+a) shr 2; pDst^[5]:=(pSrc1^[10]+pSrc1^[11]+pSrc2^[10]+pSrc2^[11]+b) shr 2; pDst^[6]:=(pSrc1^[12]+pSrc1^[13]+pSrc2^[12]+pSrc2^[13]+a) shr 2; pDst^[7]:=(pSrc1^[14]+pSrc1^[15]+pSrc2^[14]+pSrc2^[15]+b) shr 2; t:=a; a:=b; b:=t; pDst:=TpvPointer(@PDst[8]); end; end; {$else} {$ifdef cpu386} const xmm00ff00ff00ff00ff00ff00ff00ff00ff:array[0..15] of TpvUInt8=($ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00); xmm00020002000200020002000200020002:array[0..15] of TpvUInt8=($02,$00,$02,$00,$02,$00,$02,$00,$02,$00,$02,$00,$02,$00,$02,$00); var pSrc,pDst:TpvPointer; w:TpvInt32; begin pSrc:=TpvPointer(@fMCUChannels[c]^[x shl 4]); pDst:=TpvPointer(@fSamples8Bit[0]); w:=fImageWidthMCU; asm push esi movdqu xmm4,[xmm00ff00ff00ff00ff00ff00ff00ff00ff] movdqu xmm5,[xmm00020002000200020002000200020002] mov eax,dword ptr pSrc mov edx,dword ptr pDst mov ecx,dword ptr w mov esi,4 // for(int i = 0; i < 16; i += 4){ @loop: movdqu xmm1,[eax] // r0 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; movdqu xmm0,[eax] // r1 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; movdqa xmm3,xmm0 psrlw xmm0,8 // b1 = _mm_srli_epi16(r1, 8); // u1' 0 u3' 0 u5' 0 ... pand xmm3,xmm4 // a1 = _mm_and_si128(r1, mask); // u0' 0 u2' 0 u4' 0 ... movdqu xmm2,[eax] // r0 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; paddw xmm3,xmm0 // a1b1 = _mm_add_epi16(a1, b1); movdqa xmm0,xmm1 psrlw xmm1,8 // b0 = _mm_srli_epi16(r0, 8); // u1 0 u3 0 u5 0 ... pand xmm0,xmm4 // a0 = _mm_and_si128(r0, mask); // u0 0 u2 0 u4 0 ... paddw xmm0,xmm1 // a0b0 = _mm_add_epi16(a0, b0); paddw xmm3,xmm0 // res0 = _mm_add_epi16(a0b0, a1b1); movdqu xmm0,[eax] // r1 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; paddw xmm3,xmm5 // res0 = _mm_add_epi16(res0, delta); psrlw xmm3,2 // res0 = _mm_srli_epi16(res0, 2); movdqa xmm1,xmm0 psrlw xmm0,8 // b1 = _mm_srli_epi16(r1, 8); // u1' 0 u3' 0 u5' 0 ... pand xmm1,xmm4 // a1 = _mm_and_si128(r1, mask); // u0' 0 u2' 0 u4' 0 ... paddw xmm1,xmm0 // a1b1 = _mm_add_epi16(a1, b1); movdqa xmm0,xmm2 psrlw xmm2,8 // b0 = _mm_srli_epi16(r0, 8); // u1 0 u3 0 u5 0 ... pand xmm0,xmm4 // a0 = _mm_and_si128(r0, mask); // u0 0 u2 0 u4 0 ... paddw xmm0,xmm2 // a0b0 = _mm_add_epi16(a0, b0); paddw xmm1,xmm0 // res1 = _mm_add_epi16(a0b0, a1b1); paddw xmm1,xmm5 // res1 = _mm_add_epi16(res1, delta); psrlw xmm1,2 // res1 = _mm_srli_epi16(res1, 2); packuswb xmm3,xmm1 // res0 = _mm_packus_epi16(res0, res1); movdqu [edx],xmm3 // _mm_storeu_si128((__m128i*)pDst, res0); add edx,16 // pDst += 16 dec esi jne @loop pop esi end; end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} procedure TpvJPEGEncoder.LoadBlock16x8x8(x,c:TpvInt32); {$ifdef PurePascal} var i,w:TpvInt32; pDst,pSrc:PpvJPEGEncoderUInt8Array; begin w:=fImageWidthMCU; pDst:=TpvPointer(@fSamples8Bit[0]); pSrc:=TpvPointer(@fMCUChannels[c]^[x shl 4]); for i:=0 to 7 do begin pDst[0]:=(pSrc[0]+pSrc[1]) shr 1; pDst[1]:=(pSrc[2]+pSrc[3]) shr 1; pDst[2]:=(pSrc[4]+pSrc[5]) shr 1; pDst[3]:=(pSrc[6]+pSrc[7]) shr 1; pDst[4]:=(pSrc[8]+pSrc[9]) shr 1; pDst[5]:=(pSrc[10]+pSrc[11]) shr 1; pDst[6]:=(pSrc[12]+pSrc[13]) shr 1; pDst[7]:=(pSrc[14]+pSrc[15]) shr 1; pDst:=TpvPointer(@PDst[8]); pSrc:=TpvPointer(@pSrc^[w]); end; end; {$else} {$ifdef cpu386} const xmm00ff00ff00ff00ff00ff00ff00ff00ff:array[0..15] of TpvUInt8=($ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00,$ff,$00); var pSrc,pDst:TpvPointer; w:TpvInt32; begin pSrc:=TpvPointer(@fMCUChannels[c]^[x shl 4]); pDst:=TpvPointer(@fSamples8Bit[0]); w:=fImageWidthMCU; asm push esi movdqu xmm3,[xmm00ff00ff00ff00ff00ff00ff00ff00ff] mov eax,dword ptr pSrc mov edx,dword ptr pDst mov ecx,dword ptr w mov esi,4 // for(int i = 0; i < 8; i += 2){ @loop: movdqu xmm0,[eax] // r0 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; movdqa xmm1,xmm0 psrlw xmm0,8 // b0 = _mm_srli_epi16(r0, 8); // u1 0 u3 0 u5 0 ... pand xmm1,xmm3 // a0 = _mm_and_si128(r0, mask); // u0 0 u2 0 u4 0 ... movdqu xmm2,[eax] // r1 = _mm_loadu_si128((const __m128i*)pSrc); add eax,ecx // pSrc += w; paddw xmm1,xmm0 // _mm_add_epi16(a0, b0); psrlw xmm1,1 // r0 = _mm_srli_epi16(r0, 1); movdqa xmm0,xmm2 psrlw xmm2,8 // b1 = _mm_srli_epi16(r1, 8); // u1 0 u3 0 u5 0 ... pand xmm0,xmm3 // a1 = _mm_and_si128(r1, mask); // u0 0 u2 0 u4 0 ... paddw xmm0,xmm2 // r1 = _mm_add_epi16(a1, b1); psrlw xmm0,1 // r1 = _mm_srli_epi16(r1, 1); packuswb xmm1,xmm0 // r0 = _mm_packus_epi16(r0, r1); movdqu [edx],xmm1 // _mm_storeu_si128((__m128i*)pDst, r0); add edx,16 // pDst += 16 dec esi jne @loop pop esi end; end; {$else} {$error You must define PurePascal, since no inline assembler function variant doesn't exist for your target platform } {$endif} {$endif} {$ifndef PurePascal} {$ifdef cpu386} {$ifdef UseAlternativeSIMDDCT2DImplementation} procedure DCT2DSSE(InputData,OutputData:TpvPointer); assembler; stdcall; const _FIX_6b_=-480; _rounder_11_=-464; _FIX_6a_=-448; _rounder_18_=-432; _FIX_1_=-416; _FIX_3a_=-400; _FIX_5a_=-384; _FIX_2_=-368; _FIX_5b_=-352; _FIX_4b_=-336; _FIX_4a_=-320; _FIX_3b_=-304; _k_128_=-288; _rounder_5_=-272; _data_=-256; _buffer_=-128; __xmm_00000400000004000000040000000400:array[0..15] of TpvUInt8=($00,$04,$00,$00,$00,$04,$00,$00,$00,$04,$00,$00,$00,$04,$00,$00); __xmm_00024000000240000002400000024000:array[0..15] of TpvUInt8=($00,$40,$02,$00,$00,$40,$02,$00,$00,$40,$02,$00,$00,$40,$02,$00); __xmm_00120012001200120012001200120012:array[0..15] of TpvUInt8=($12,$00,$12,$00,$12,$00,$12,$00,$12,$00,$12,$00,$12,$00,$12,$00); __xmm_115129cf115129cf115129cf115129cf:array[0..15] of TpvUInt8=($cf,$29,$51,$11,$cf,$29,$51,$11,$cf,$29,$51,$11,$cf,$29,$51,$11); __xmm_d6301151d6301151d6301151d6301151:array[0..15] of TpvUInt8=($51,$11,$30,$d6,$51,$11,$30,$d6,$51,$11,$30,$d6,$51,$11,$30,$d6); __xmm_08d4192508d4192508d4192508d41925:array[0..15] of TpvUInt8=($25,$19,$d4,$08,$25,$19,$d4,$08,$25,$19,$d4,$08,$25,$19,$d4,$08); __xmm_25a12c6325a12c6325a12c6325a12c63:array[0..15] of TpvUInt8=($63,$2c,$a1,$25,$63,$2c,$a1,$25,$63,$2c,$a1,$25,$63,$2c,$a1,$25); __xmm_e6dcd39ee6dcd39ee6dcd39ee6dcd39e:array[0..15] of TpvUInt8=($9e,$d3,$dc,$e6,$9e,$d3,$dc,$e6,$9e,$d3,$dc,$e6,$9e,$d3,$dc,$e6); __xmm_f72d25a1f72d25a1f72d25a1f72d25a1:array[0..15] of TpvUInt8=($a1,$25,$2d,$f7,$a1,$25,$2d,$f7,$a1,$25,$2d,$f7,$a1,$25,$2d,$f7); __xmm_25a108d525a108d525a108d525a108d5:array[0..15] of TpvUInt8=($d5,$08,$a1,$25,$d5,$08,$a1,$25,$d5,$08,$a1,$25,$d5,$08,$a1,$25); __xmm_d39e1925d39e1925d39e1925d39e1925:array[0..15] of TpvUInt8=($25,$19,$9e,$d3,$25,$19,$9e,$d3,$25,$19,$9e,$d3,$25,$19,$9e,$d3); __xmm_d39d25a1d39d25a1d39d25a1d39d25a1:array[0..15] of TpvUInt8=($a1,$25,$9d,$d3,$a1,$25,$9d,$d3,$a1,$25,$9d,$d3,$a1,$25,$9d,$d3); __xmm_e6dc08d4e6dc08d4e6dc08d4e6dc08d4:array[0..15] of TpvUInt8=($d4,$04,$dc,$e6,$d4,$04,$dc,$e6,$d4,$04,$dc,$e6,$d4,$04,$dc,$e6); __xmm_00800080008000800080008000800080:array[0..15] of TpvUInt8=($80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00); asm mov ecx,esp sub esp,512 and esp,$fffffff0 movdqu xmm0,dqword ptr __xmm_00000400000004000000040000000400 movdqa dqword ptr [esp+480+_rounder_11_],xmm0 movdqu xmm0,dqword ptr __xmm_00024000000240000002400000024000 movdqa dqword ptr [esp+480+_rounder_18_],xmm0 movdqu xmm0,dqword ptr __xmm_00120012001200120012001200120012 movdqa dqword ptr [esp+480+_rounder_5_],xmm0 movdqu xmm0,dqword ptr __xmm_115129cf115129cf115129cf115129cf movdqa dqword ptr [esp+480+_FIX_1_],xmm0 movdqu xmm0,dqword ptr __xmm_d6301151d6301151d6301151d6301151 movdqa dqword ptr [esp+480+_FIX_2_],xmm0 movdqu xmm0,dqword ptr __xmm_08d4192508d4192508d4192508d41925 movdqa dqword ptr [esp+480+_FIX_3a_],xmm0 movdqu xmm0,dqword ptr __xmm_25a12c6325a12c6325a12c6325a12c63 movdqa dqword ptr [esp+480+_FIX_3b_],xmm0 movdqu xmm0,dqword ptr __xmm_e6dcd39ee6dcd39ee6dcd39ee6dcd39e movdqa dqword ptr [esp+480+_FIX_4a_],xmm0 movdqu xmm0,dqword ptr __xmm_f72d25a1f72d25a1f72d25a1f72d25a1 movdqa dqword ptr [esp+480+_FIX_4b_],xmm0 movdqu xmm0,dqword ptr __xmm_25a108d525a108d525a108d525a108d5 movdqa dqword ptr [esp+480+_FIX_5a_],xmm0 movdqu xmm0,dqword ptr __xmm_d39e1925d39e1925d39e1925d39e1925 movdqa dqword ptr [esp+480+_FIX_5b_],xmm0 movdqu xmm0,dqword ptr __xmm_d39d25a1d39d25a1d39d25a1d39d25a1 movdqa dqword ptr [esp+480+_FIX_6a_],xmm0 movdqu xmm0,dqword ptr __xmm_e6dc08d4e6dc08d4e6dc08d4e6dc08d4 movdqa dqword ptr [esp+480+_FIX_6b_],xmm0 movdqu xmm0,dqword ptr __xmm_00800080008000800080008000800080 movdqa dqword ptr [esp+480+_k_128_],xmm0 push eax push edx lea eax,dword ptr [esp+488+_data_] mov edx,dword ptr InputData pxor xmm7,xmm7 movdqa xmm6,dqword ptr [esp+488+_k_128_] movq xmm0,qword ptr [edx] movq xmm1,qword ptr [edx+8] movq xmm2,qword ptr [edx+16] movq xmm3,qword ptr [edx+24] movq xmm4,qword ptr [edx+32] movq xmm5,qword ptr [edx+40] punpcklbw xmm0,xmm7 punpcklbw xmm1,xmm7 punpcklbw xmm2,xmm7 punpcklbw xmm3,xmm7 punpcklbw xmm4,xmm7 punpcklbw xmm5,xmm7 psubw xmm0,xmm6 psubw xmm1,xmm6 psubw xmm2,xmm6 psubw xmm3,xmm6 psubw xmm4,xmm6 psubw xmm5,xmm6 movdqa dqword ptr [eax],xmm0 movdqa dqword ptr [eax+16],xmm1 movq xmm0,qword ptr [edx+48] movq xmm1,qword ptr [edx+56] punpcklbw xmm0,xmm7 punpcklbw xmm1,xmm7 psubw xmm0,xmm6 psubw xmm1,xmm6 movdqa dqword ptr [eax+32],xmm2 movdqa dqword ptr [eax+48],xmm3 movdqa dqword ptr [eax+64],xmm4 movdqa dqword ptr [eax+80],xmm5 movdqa dqword ptr [eax+96],xmm0 movdqa dqword ptr [eax+112],xmm1 lea edx,dword ptr [esp+488+_buffer_] prefetchnta TpvUInt8 ptr [esp+488+_FIX_1_] prefetchnta TpvUInt8 ptr [esp+488+_FIX_3a_] prefetchnta TpvUInt8 ptr [esp+488+_FIX_5a_] movdqa xmm0,dqword ptr [eax] movdqa xmm6,dqword ptr [eax+32] movdqa xmm4,dqword ptr [eax+64] movdqa xmm7,dqword ptr [eax+96] punpckhwd xmm0,dqword ptr [eax+16] movdqa xmm2,xmm0 punpckhwd xmm6,dqword ptr [eax+48] punpckhwd xmm4,dqword ptr [eax+80] movdqa xmm5,xmm4 punpckhwd xmm7,dqword ptr [eax+112] punpckldq xmm0,xmm6 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 punpckhdq xmm2,xmm6 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 punpcklqdq xmm0,xmm4 punpcklqdq xmm2,xmm5 punpckhqdq xmm1,xmm4 punpckhqdq xmm3,xmm5 movdqa dqword ptr [edx+64],xmm0 movdqa dqword ptr [edx+80],xmm1 movdqa dqword ptr [edx+96],xmm2 movdqa dqword ptr [edx+112],xmm3 movdqa xmm0,dqword ptr [eax] movdqa xmm6,dqword ptr [eax+32] movdqa xmm4,dqword ptr [eax+64] movdqa xmm7,dqword ptr [eax+96] punpcklwd xmm0,dqword ptr [eax+16] movdqa xmm2,xmm0 punpcklwd xmm6,dqword ptr [eax+48] punpcklwd xmm4,dqword ptr [eax+80] movdqa xmm5,xmm4 punpcklwd xmm7,dqword ptr [eax+112] punpckldq xmm0,xmm6 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 punpckhdq xmm2,xmm6 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 punpcklqdq xmm0,xmm4 punpcklqdq xmm2,xmm5 punpckhqdq xmm1,xmm4 punpckhqdq xmm3,xmm5 movdqa dqword ptr [edx],xmm0 movdqa dqword ptr [edx+16],xmm1 movdqa dqword ptr [edx+32],xmm2 movdqa dqword ptr [edx+48],xmm3 paddsw xmm0,dqword ptr [edx+112] movdqa xmm4,xmm0 paddsw xmm1,dqword ptr [edx+96] movdqa xmm5,xmm1 paddsw xmm2,dqword ptr [edx+80] paddsw xmm3,dqword ptr [edx+64] paddsw xmm0,xmm3 movdqa xmm6,xmm0 paddsw xmm1,xmm2 psubsw xmm4,xmm3 psubsw xmm5,xmm2 paddsw xmm0,xmm1 psubsw xmm6,xmm1 psllw xmm0,2 psllw xmm6,2 movdqa xmm1,xmm4 movdqa xmm2,xmm4 movdqa dqword ptr [eax],xmm0 movdqa dqword ptr [eax+64],xmm6 movdqa xmm7,dqword ptr [esp+488+_FIX_1_] punpckhwd xmm1,xmm5 movdqa xmm6,xmm1 punpcklwd xmm2,xmm5 movdqa xmm0,xmm2 movdqa xmm4,dqword ptr [esp+488+_FIX_2_] movdqa xmm5,dqword ptr [esp+488+_rounder_11_] pmaddwd xmm2,xmm7 pmaddwd xmm1,xmm7 pmaddwd xmm0,xmm4 pmaddwd xmm6,xmm4 paddd xmm2,xmm5 paddd xmm1,xmm5 psrad xmm2,11 psrad xmm1,11 packssdw xmm2,xmm1 movdqa dqword ptr [eax+32],xmm2 paddd xmm0,xmm5 paddd xmm6,xmm5 psrad xmm0,11 psrad xmm6,11 packssdw xmm0,xmm6 movdqa dqword ptr [eax+96],xmm0 movdqa xmm0,dqword ptr [edx] movdqa xmm1,dqword ptr [edx+16] movdqa xmm2,dqword ptr [edx+32] movdqa xmm3,dqword ptr [edx+48] psubsw xmm0,dqword ptr [edx+112] movdqa xmm4,xmm0 psubsw xmm1,dqword ptr [edx+96] psubsw xmm2,dqword ptr [edx+80] movdqa xmm6,xmm2 psubsw xmm3,dqword ptr [edx+64] punpckhwd xmm4,xmm1 punpcklwd xmm0,xmm1 punpckhwd xmm6,xmm3 punpcklwd xmm2,xmm3 movdqa xmm1,dqword ptr [esp+488+_FIX_3a_] movdqa xmm5,dqword ptr [esp+488+_FIX_3b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_11_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa dqword ptr [eax+16],xmm1 movdqa xmm1,dqword ptr [esp+488+_FIX_4a_] movdqa xmm5,dqword ptr [esp+488+_FIX_4b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_11_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa dqword ptr [eax+48],xmm1 movdqa xmm1,dqword ptr [esp+488+_FIX_5a_] movdqa xmm5,dqword ptr [esp+488+_FIX_5b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_11_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa dqword ptr [eax+80],xmm1 pmaddwd xmm2,dqword ptr [esp+488+_FIX_6a_] pmaddwd xmm0,dqword ptr [esp+488+_FIX_6b_] paddd xmm2,xmm0 pmaddwd xmm6,dqword ptr [esp+488+_FIX_6a_] pmaddwd xmm4,dqword ptr [esp+488+_FIX_6b_] paddd xmm6,xmm4 paddd xmm2,xmm5 paddd xmm6,xmm5 psrad xmm2,11 psrad xmm6,11 packssdw xmm2,xmm6 movdqa dqword ptr [eax+112],xmm2 movdqa xmm0,dqword ptr [eax] movdqa xmm6,dqword ptr [eax+32] movdqa xmm4,dqword ptr [eax+64] movdqa xmm7,dqword ptr [eax+96] punpckhwd xmm0,dqword ptr [eax+16] movdqa xmm2,xmm0 punpckhwd xmm6,dqword ptr [eax+48] punpckhwd xmm4,dqword ptr [eax+80] movdqa xmm5,xmm4 punpckhwd xmm7,dqword ptr [eax+112] punpckldq xmm0,xmm6 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 punpckhdq xmm2,xmm6 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 punpcklqdq xmm0,xmm4 punpcklqdq xmm2,xmm5 punpckhqdq xmm1,xmm4 punpckhqdq xmm3,xmm5 movdqa dqword ptr [edx+64],xmm0 movdqa dqword ptr [edx+80],xmm1 movdqa dqword ptr [edx+96],xmm2 movdqa dqword ptr [edx+112],xmm3 movdqa xmm0,dqword ptr [eax] movdqa xmm6,dqword ptr [eax+32] movdqa xmm4,dqword ptr [eax+64] movdqa xmm7,dqword ptr [eax+96] punpcklwd xmm0,dqword ptr [eax+16] movdqa xmm2,xmm0 punpcklwd xmm6,dqword ptr [eax+48] punpcklwd xmm4,dqword ptr [eax+80] movdqa xmm5,xmm4 punpcklwd xmm7,dqword ptr [eax+112] punpckldq xmm0,xmm6 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 punpckhdq xmm2,xmm6 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 punpcklqdq xmm0,xmm4 punpcklqdq xmm2,xmm5 punpckhqdq xmm1,xmm4 punpckhqdq xmm3,xmm5 movdqa dqword ptr [edx],xmm0 movdqa dqword ptr [edx+16],xmm1 movdqa dqword ptr [edx+32],xmm2 movdqa dqword ptr [edx+48],xmm3 movdqa xmm7,dqword ptr [esp+488+_rounder_5_] paddsw xmm0,dqword ptr [edx+112] movdqa xmm4,xmm0 paddsw xmm1,dqword ptr [edx+96] movdqa xmm5,xmm1 paddsw xmm2,dqword ptr [edx+80] paddsw xmm3,dqword ptr [edx+64] paddsw xmm0,xmm3 paddsw xmm0,xmm7 psraw xmm0,5 movdqa xmm6,xmm0 paddsw xmm1,xmm2 psubsw xmm4,xmm3 psubsw xmm5,xmm2 paddsw xmm1,xmm7 psraw xmm1,5 paddsw xmm0,xmm1 psubsw xmm6,xmm1 movdqa xmm1,xmm4 movdqa xmm2,xmm4 movdqa dqword ptr [eax],xmm0 movdqa dqword ptr [eax+64],xmm6 movdqa xmm7,dqword ptr [esp+488+_FIX_1_] punpckhwd xmm1,xmm5 movdqa xmm6,xmm1 punpcklwd xmm2,xmm5 movdqa xmm0,xmm2 movdqa xmm4,dqword ptr [esp+488+_FIX_2_] movdqa xmm5,dqword ptr [esp+488+_rounder_18_] pmaddwd xmm2,xmm7 pmaddwd xmm1,xmm7 pmaddwd xmm0,xmm4 pmaddwd xmm6,xmm4 paddd xmm2,xmm5 paddd xmm1,xmm5 psrad xmm2,18 psrad xmm1,18 packssdw xmm2,xmm1 movdqa dqword ptr [eax+32],xmm2 paddd xmm0,xmm5 paddd xmm6,xmm5 psrad xmm0,18 psrad xmm6,18 packssdw xmm0,xmm6 movdqa dqword ptr [eax+96],xmm0 movdqa xmm0,dqword ptr [edx] movdqa xmm1,dqword ptr [edx+16] movdqa xmm2,dqword ptr [edx+32] movdqa xmm3,dqword ptr [edx+48] psubsw xmm0,dqword ptr [edx+112] movdqa xmm4,xmm0 psubsw xmm1,dqword ptr [edx+96] psubsw xmm2,dqword ptr [edx+80] movdqa xmm6,xmm2 psubsw xmm3,dqword ptr [edx+64] punpckhwd xmm4,xmm1 punpcklwd xmm0,xmm1 punpckhwd xmm6,xmm3 punpcklwd xmm2,xmm3 movdqa xmm1,dqword ptr [esp+488+_FIX_3a_] movdqa xmm5,dqword ptr [esp+488+_FIX_3b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_18_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa dqword ptr [eax+16],xmm1 movdqa xmm1,dqword ptr [esp+488+_FIX_4a_] movdqa xmm5,dqword ptr [esp+488+_FIX_4b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_18_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa dqword ptr [eax+48],xmm1 movdqa xmm1,dqword ptr [esp+488+_FIX_5a_] movdqa xmm5,dqword ptr [esp+488+_FIX_5b_] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,dqword ptr [esp+488+_rounder_18_] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa dqword ptr [eax+80],xmm1 pmaddwd xmm2,dqword ptr [esp+488+_FIX_6a_] pmaddwd xmm0,dqword ptr [esp+488+_FIX_6b_] paddd xmm2,xmm0 pmaddwd xmm6,dqword ptr [esp+488+_FIX_6a_] pmaddwd xmm4,dqword ptr [esp+488+_FIX_6b_] paddd xmm6,xmm4 paddd xmm2,xmm5 paddd xmm6,xmm5 psrad xmm2,18 psrad xmm6,18 packssdw xmm2,xmm6 movdqa dqword ptr [eax+112],xmm2 mov edx,dword ptr OutputData movdqa xmm0,dqword ptr [eax] movdqa xmm1,dqword ptr [eax+16] movdqa xmm2,dqword ptr [eax+32] movdqa xmm3,dqword ptr [eax+48] movdqa xmm4,dqword ptr [eax+64] movdqa xmm5,dqword ptr [eax+80] movdqa xmm6,dqword ptr [eax+96] movdqa xmm7,dqword ptr [eax+112] movdqu dqword ptr [edx],xmm0 movdqu dqword ptr [edx+16],xmm1 movdqu dqword ptr [edx+32],xmm2 movdqu dqword ptr [edx+48],xmm3 movdqu dqword ptr [edx+64],xmm4 movdqu dqword ptr [edx+80],xmm5 movdqu dqword ptr [edx+96],xmm6 movdqu dqword ptr [edx+112],xmm7 pop edx pop eax mov esp,ecx end; {$else} {$ifdef GoodCompilerForSIMD} procedure DCT2DSSE(InputData,OutputData:TpvPointer); assembler; stdcall; const _x7_1_=-128; _t5_1_=-112; _b7_1_=-112; _a7_1_=-96; _y4_1_=-80; _y6_1_=-64; _y7_1_=-48; _b5_1_=-32; _t9_1_=-16; _y5_1_=-16; __xmm_00800080008000800080008000800080:array[0..15] of TpvUInt8=($80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00); __xmm_00004000000040000000400000004000:array[0..15] of TpvUInt8=($00,$40,$00,$00,$00,$40,$00,$00,$00,$40,$00,$00,$00,$40,$00,$00); __xmm_35053505350535053505350535053505:array[0..15] of TpvUInt8=($05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35); __xmm_5a825a825a825a825a825a825a825a82:array[0..15] of TpvUInt8=($82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a); __xmm_a57ea57ea57ea57ea57ea57ea57ea57e:array[0..15] of TpvUInt8=($7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5); __xmm_19761976197619761976197619761976:array[0..15] of TpvUInt8=($76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19); __xmm_55875587558755875587558755875587:array[0..15] of TpvUInt8=($87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55); __xmm_aa79aa79aa79aa79aa79aa79aa79aa79:array[0..15] of TpvUInt8=($79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa); __xmm_163114e712d00fff12d014e716310fff:array[0..15] of TpvUInt8=($ff,$0f,$31,$16,$e7,$14,$d0,$12,$ff,$0f,$d0,$12,$e7,$14,$31,$16); __xmm_1ec81cfe1a1816311a181cfe1ec81631:array[0..15] of TpvUInt8=($31,$16,$c8,$1e,$fe,$1c,$18,$1a,$31,$16,$18,$1a,$fe,$1c,$c8,$1e); __xmm_1cfe1b50189414e718941b501cfe14e7:array[0..15] of TpvUInt8=($e7,$14,$fe,$1c,$50,$1b,$94,$18,$e7,$14,$94,$18,$50,$1b,$fe,$1c); __xmm_1a181894161f12d0161f18941a1812d0:array[0..15] of TpvUInt8=($d0,$12,$18,$1a,$94,$18,$1f,$16,$d0,$12,$1f,$16,$94,$18,$18,$1a); asm mov edx,esp sub esp,160 and esp,$fffffff0 mov eax,dword ptr InputData xorps xmm1,xmm1 movdqu xmm0,dqword ptr __xmm_00800080008000800080008000800080 movq xmm2,qword ptr [eax+32] movq xmm5,qword ptr [eax] movq xmm6,qword ptr [eax+8] movq xmm4,qword ptr [eax+16] movq xmm3,qword ptr [eax+24] movq xmm7,qword ptr [eax+40] punpcklbw xmm2,xmm1 psubw xmm2,xmm0 punpcklbw xmm5,xmm1 movdqa dqword ptr [esp+128+_y4_1_],xmm2 psubw xmm5,xmm0 movq xmm2,qword ptr [eax+48] punpcklbw xmm2,xmm1 psubw xmm2,xmm0 punpcklbw xmm6,xmm1 movdqa dqword ptr [esp+128+_y6_1_],xmm2 psubw xmm6,xmm0 movq xmm2,qword ptr [eax+56] mov eax,2 punpcklbw xmm2,xmm1 punpcklbw xmm4,xmm1 psubw xmm2,xmm0 punpcklbw xmm3,xmm1 psubw xmm4,xmm0 punpcklbw xmm7,xmm1 psubw xmm3,xmm0 movdqa dqword ptr [esp+128+_x7_1_],xmm5 psubw xmm7,xmm0 movdqa dqword ptr [esp+128+_y7_1_],xmm2 jmp @LoopEntry nop @Loop: movdqa xmm7,dqword ptr [esp+128+_y5_1_] @LoopEntry: movdqa xmm0,dqword ptr [esp+128+_x7_1_] movdqa xmm1,xmm3 punpckhwd xmm0,dqword ptr [esp+128+_y4_1_] movdqa xmm2,xmm6 punpckhwd xmm3,dqword ptr [esp+128+_y7_1_] punpcklwd xmm5,dqword ptr [esp+128+_y4_1_] punpcklwd xmm1,dqword ptr [esp+128+_y7_1_] movdqa dqword ptr [esp+128+_x7_1_],xmm0 movdqa xmm0,xmm4 punpcklwd xmm0,dqword ptr [esp+128+_y6_1_] punpckhwd xmm4,dqword ptr [esp+128+_y6_1_] punpckhwd xmm6,xmm7 punpcklwd xmm2,xmm7 movdqa xmm7,xmm5 punpckhwd xmm5,xmm0 punpcklwd xmm7,xmm0 movdqa xmm0,dqword ptr [esp+128+_x7_1_] movdqa dqword ptr [esp+128+_b7_1_],xmm3 movdqa xmm3,xmm0 punpckhwd xmm0,xmm4 movdqa dqword ptr [esp+128+_x7_1_],xmm0 movdqa xmm0,xmm2 punpcklwd xmm0,xmm1 punpcklwd xmm3,xmm4 movdqa xmm4,xmm5 punpckhwd xmm2,xmm1 movdqa xmm1,xmm6 punpckhwd xmm6,dqword ptr [esp+128+_b7_1_] punpcklwd xmm1,dqword ptr [esp+128+_b7_1_] punpckhwd xmm5,xmm2 movdqa dqword ptr [esp+128+_a7_1_],xmm6 movdqa xmm6,xmm7 punpcklwd xmm6,xmm0 punpckhwd xmm7,xmm0 movdqa dqword ptr [esp+128+_t5_1_],xmm5 movdqa xmm5,dqword ptr [esp+128+_x7_1_] movdqa xmm0,xmm5 punpcklwd xmm4,xmm2 punpcklwd xmm0,dqword ptr [esp+128+_a7_1_] movdqa xmm2,xmm3 punpckhwd xmm5,dqword ptr [esp+128+_a7_1_] punpckhwd xmm3,xmm1 punpcklwd xmm2,xmm1 movdqa xmm1,xmm3 movdqa dqword ptr [esp+128+_x7_1_],xmm5 paddsw xmm1,xmm4 paddsw xmm5,xmm6 psubsw xmm4,xmm3 psubsw xmm6,dqword ptr [esp+128+_x7_1_] movdqa xmm3,dqword ptr [esp+128+_t5_1_] movdqa dqword ptr [esp+128+_t9_1_],xmm6 movdqa xmm6,xmm0 paddsw xmm6,xmm7 psubsw xmm7,xmm0 movdqa xmm0,xmm2 paddsw xmm0,xmm3 psubsw xmm3,xmm2 movdqa dqword ptr [esp+128+_t5_1_],xmm3 movdqa xmm2,xmm4 movdqa xmm3,xmm0 paddsw xmm2,xmm7 paddsw xmm3,xmm5 psubsw xmm7,xmm4 movdqa xmm4,dqword ptr __xmm_00004000000040000000400000004000 psubsw xmm5,xmm0 movdqa xmm0,xmm1 paddsw xmm0,xmm6 psubsw xmm6,xmm1 movdqa xmm1,xmm3 psubsw xmm3,xmm0 paddsw xmm1,xmm0 movdqa dqword ptr [esp+128+_y4_1_],xmm3 movdqa dqword ptr [esp+128+_x7_1_],xmm1 movdqa xmm1,dqword ptr __xmm_35053505350535053505350535053505 movdqa xmm0,xmm1 pmullw xmm1,xmm6 pmulhw xmm0,xmm6 movdqa xmm3,xmm1 punpcklwd xmm3,xmm0 paddd xmm3,xmm4 psrad xmm3,15 punpckhwd xmm1,xmm0 paddd xmm1,xmm4 pslld xmm3,16 psrad xmm1,15 psrad xmm3,16 pslld xmm1,16 psrad xmm1,16 packssdw xmm3,xmm1 movdqa xmm1,dqword ptr __xmm_35053505350535053505350535053505 paddsw xmm3,xmm5 movdqa xmm0,xmm1 movdqa dqword ptr [esp+128+_b5_1_],xmm3 pmullw xmm1,xmm5 pmulhw xmm0,xmm5 movdqa xmm3,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,xmm4 punpcklwd xmm3,xmm0 paddd xmm3,xmm4 psrad xmm1,15 psrad xmm3,15 pslld xmm1,16 pslld xmm3,16 psrad xmm1,16 psrad xmm3,16 packssdw xmm3,xmm1 movdqa xmm1,dqword ptr __xmm_5a825a825a825a825a825a825a825a82 psubsw xmm3,xmm6 movdqa xmm0,xmm1 movdqa xmm6,dqword ptr __xmm_a57ea57ea57ea57ea57ea57ea57ea57e pmullw xmm1,xmm7 pmulhw xmm0,xmm7 movdqa dqword ptr [esp+128+_y6_1_],xmm3 movdqa xmm3,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,xmm4 punpcklwd xmm3,xmm0 psrad xmm1,15 paddd xmm3,xmm4 psrad xmm3,15 movdqa xmm0,xmm6 pslld xmm1,16 pslld xmm3,16 psrad xmm1,16 psrad xmm3,16 pmulhw xmm0,xmm7 packssdw xmm3,xmm1 movdqa xmm1,xmm6 pmullw xmm1,xmm7 movdqa xmm7,dqword ptr __xmm_00004000000040000000400000004000 paddsw xmm3,dqword ptr [esp+128+_t5_1_] movdqa xmm5,xmm1 punpckhwd xmm1,xmm0 punpcklwd xmm5,xmm0 paddd xmm1,xmm7 psrad xmm1,15 paddd xmm5,xmm7 psrad xmm5,15 movdqa xmm0,xmm6 pslld xmm1,16 pslld xmm5,16 psrad xmm1,16 psrad xmm5,16 pmulhw xmm0,xmm2 packssdw xmm5,xmm1 movdqa xmm1,xmm6 paddsw xmm5,dqword ptr [esp+128+_t5_1_] pmullw xmm1,xmm2 movdqa xmm4,xmm1 punpckhwd xmm1,xmm0 punpcklwd xmm4,xmm0 paddd xmm1,xmm7 paddd xmm4,xmm7 psrad xmm1,15 psrad xmm4,15 pslld xmm1,16 pslld xmm4,16 psrad xmm1,16 psrad xmm4,16 packssdw xmm4,xmm1 paddsw xmm4,dqword ptr [esp+128+_t9_1_] movdqa xmm1,dqword ptr __xmm_5a825a825a825a825a825a825a825a82 movdqa xmm0,xmm1 pmullw xmm1,xmm2 pmulhw xmm0,xmm2 movdqa xmm2,xmm1 punpckhwd xmm1,xmm0 punpcklwd xmm2,xmm0 paddd xmm1,xmm7 psrad xmm1,15 paddd xmm2,xmm7 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm2,xmm1 movdqa xmm1,dqword ptr __xmm_19761976197619761976197619761976 paddsw xmm2,dqword ptr [esp+128+_t9_1_] movdqa xmm0,xmm1 pmullw xmm1,xmm3 pmulhw xmm0,xmm3 movdqa xmm6,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,xmm7 punpcklwd xmm6,xmm0 psrad xmm1,15 paddd xmm6,xmm7 psrad xmm6,15 pslld xmm1,16 pslld xmm6,16 psrad xmm1,16 psrad xmm6,16 packssdw xmm6,xmm1 movdqa xmm1,dqword ptr __xmm_19761976197619761976197619761976 paddsw xmm6,xmm2 movdqa xmm0,xmm1 movdqa dqword ptr [esp+128+_a7_1_],xmm6 pmullw xmm1,xmm2 pmulhw xmm0,xmm2 movdqa xmm2,xmm1 punpcklwd xmm2,xmm0 punpckhwd xmm1,xmm0 paddd xmm2,xmm7 paddd xmm1,xmm7 psrad xmm2,15 psrad xmm1,15 pslld xmm2,16 pslld xmm1,16 psrad xmm2,16 psrad xmm1,16 packssdw xmm2,xmm1 movdqa xmm1,dqword ptr __xmm_55875587558755875587558755875587 psubsw xmm2,xmm3 movdqa xmm0,xmm1 movdqa dqword ptr [esp+128+_y7_1_],xmm2 pmullw xmm1,xmm4 pmulhw xmm0,xmm4 movdqa xmm2,xmm1 punpcklwd xmm2,xmm0 punpckhwd xmm1,xmm0 paddd xmm2,xmm7 paddd xmm1,xmm7 psrad xmm2,15 psrad xmm1,15 pslld xmm2,16 pslld xmm1,16 psrad xmm2,16 psrad xmm1,16 packssdw xmm2,xmm1 movdqa xmm1,dqword ptr __xmm_aa79aa79aa79aa79aa79aa79aa79aa79 paddsw xmm2,xmm5 movdqa xmm0,xmm1 movdqa dqword ptr [esp+128+_y5_1_],xmm2 pmullw xmm1,xmm5 pmulhw xmm0,xmm5 movdqa xmm3,xmm1 punpcklwd xmm3,xmm0 paddd xmm3,xmm7 psrad xmm3,15 pslld xmm3,16 psrad xmm3,16 movdqa xmm5,dqword ptr [esp+128+_x7_1_] punpckhwd xmm1,xmm0 paddd xmm1,xmm7 psrad xmm1,15 pslld xmm1,16 psrad xmm1,16 packssdw xmm3,xmm1 paddsw xmm3,xmm4 movdqa xmm4,dqword ptr [esp+128+_b5_1_] movdqa dqword ptr [esp+128+_b7_1_],xmm3 dec eax jne @Loop movdqa xmm3,dqword ptr __xmm_163114e712d00fff12d014e716310fff mov eax,dword ptr OutputData movdqa xmm2,xmm3 pmullw xmm2,dqword ptr [esp+128+_x7_1_] movdqa xmm1,xmm3 pmulhw xmm1,dqword ptr [esp+128+_x7_1_] movdqa xmm6,dqword ptr __xmm_1ec81cfe1a1816311a181cfe1ec81631 movdqa xmm5,dqword ptr __xmm_1cfe1b50189414e718941b501cfe14e7 movdqa xmm4,dqword ptr __xmm_1a181894161f12d0161f18941a1812d0 movdqa xmm0,xmm2 punpckhwd xmm2,xmm1 punpcklwd xmm0,xmm1 paddd xmm2,xmm7 psrad xmm2,15 xorps xmm1,xmm1 paddd xmm0,xmm7 pslld xmm2,16 psrad xmm0,15 psrad xmm2,16 pslld xmm0,16 psrad xmm0,16 packssdw xmm0,xmm2 movdqa xmm2,xmm6 pmullw xmm2,dqword ptr [esp+128+_a7_1_] paddsw xmm0,xmm1 movdqu dqword ptr [eax],xmm0 movdqa xmm0,xmm6 pmulhw xmm0,dqword ptr [esp+128+_a7_1_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm7 psrad xmm1,15 paddd xmm2,xmm7 psrad xmm2,15 xorps xmm0,xmm0 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 movdqa xmm2,xmm5 pmullw xmm2,dqword ptr [esp+128+_b5_1_] paddsw xmm1,xmm0 movdqu dqword ptr [eax+16],xmm1 movdqa xmm0,xmm5 pmulhw xmm0,dqword ptr [esp+128+_b5_1_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm7 paddd xmm2,xmm7 psrad xmm1,15 psrad xmm2,15 xorps xmm0,xmm0 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 movdqa xmm2,xmm4 pmullw xmm2,dqword ptr [esp+128+_b7_1_] paddsw xmm1,xmm0 movdqu dqword ptr [eax+32],xmm1 movdqa xmm0,xmm4 pmulhw xmm0,dqword ptr [esp+128+_b7_1_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm7 paddd xmm2,xmm7 psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 xorps xmm2,xmm2 paddsw xmm1,xmm2 movdqu dqword ptr [eax+48],xmm1 movdqa xmm0,xmm3 pmullw xmm3,dqword ptr [esp+128+_y4_1_] pmulhw xmm0,dqword ptr [esp+128+_y4_1_] movdqa xmm1,xmm3 punpcklwd xmm1,xmm0 paddd xmm1,xmm7 punpckhwd xmm3,xmm0 psrad xmm1,15 paddd xmm3,xmm7 psrad xmm3,15 movdqa xmm0,xmm4 pmullw xmm4,dqword ptr [esp+128+_y5_1_] pmulhw xmm0,dqword ptr [esp+128+_y5_1_] pslld xmm1,16 pslld xmm3,16 psrad xmm1,16 psrad xmm3,16 packssdw xmm1,xmm3 paddsw xmm1,xmm2 movdqu dqword ptr [eax+64],xmm1 movdqa xmm1,xmm4 punpckhwd xmm4,xmm0 punpcklwd xmm1,xmm0 paddd xmm4,xmm7 paddd xmm1,xmm7 psrad xmm4,15 psrad xmm1,15 movdqa xmm0,xmm5 pmullw xmm5,dqword ptr [esp+128+_y6_1_] pmulhw xmm0,dqword ptr [esp+128+_y6_1_] pslld xmm1,16 pslld xmm4,16 psrad xmm1,16 psrad xmm4,16 packssdw xmm1,xmm4 paddsw xmm1,xmm2 movdqu dqword ptr [eax+80],xmm1 movdqa xmm1,xmm5 punpckhwd xmm5,xmm0 punpcklwd xmm1,xmm0 paddd xmm5,xmm7 paddd xmm1,xmm7 psrad xmm5,15 psrad xmm1,15 movdqa xmm0,xmm6 pmullw xmm6,dqword ptr [esp+128+_y7_1_] pmulhw xmm0,dqword ptr [esp+128+_y7_1_] pslld xmm1,16 pslld xmm5,16 psrad xmm1,16 psrad xmm5,16 packssdw xmm1,xmm5 paddsw xmm1,xmm2 movdqu dqword ptr [eax+96],xmm1 movdqa xmm1,xmm6 punpckhwd xmm6,xmm0 punpcklwd xmm1,xmm0 paddd xmm6,xmm7 paddd xmm1,xmm7 psrad xmm6,15 psrad xmm1,15 pslld xmm6,16 pslld xmm1,16 psrad xmm6,16 psrad xmm1,16 packssdw xmm1,xmm6 paddsw xmm1,xmm2 movdqu dqword ptr [eax+112],xmm1 mov esp,edx end; {$else} procedure DCT2DSSE(InputData,OutputData:TpvPointer); assembler; stdcall; const _tmp_lo_1=-224; _c_=-208; _vx_16_=-192; _vx_15_=-192; _vy_15_=-192; _t5_2_=-176; _b5_2_=-176; _k__128_=-176; _t9_2_=-160; _t9_1_=-160; _a7_1_=-160; _t5_1_=-144; _vy_20_=-128; _vy_1_=-128; _vy_14_=-112; _vy_9_=-112; _a7_2_=-112; _vy_21_=-96; _c13573_=-96; _c23170_=-80; _vy_24_=-64; _c6518_=-64; _cNeg21895_=-48; _c21895_=-32; _cNeg23170_=-16; __xmm_35053505350535053505350535053505:array[0..15] of TpvUInt8=($05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35,$05,$35); __xmm_55875587558755875587558755875587:array[0..15] of TpvUInt8=($87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55,$87,$55); __xmm_aa79aa79aa79aa79aa79aa79aa79aa79:array[0..15] of TpvUInt8=($79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa,$79,$aa); __xmm_5a825a825a825a825a825a825a825a82:array[0..15] of TpvUInt8=($82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a,$82,$5a); __xmm_a57ea57ea57ea57ea57ea57ea57ea57e:array[0..15] of TpvUInt8=($7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5,$7e,$a5); __xmm_19761976197619761976197619761976:array[0..15] of TpvUInt8=($76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19,$76,$19); __xmm_00004000000040000000400000004000:array[0..15] of TpvUInt8=($00,$40,$00,$00,$00,$40,$00,$00,$00,$40,$00,$00,$00,$40,$00,$00); __xmm_00800080008000800080008000800080:array[0..15] of TpvUInt8=($80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00,$80,$00); PostScaleArray:array[0..63] of TpvInt16=( 4095,5681,5351,4816,4095,4816,5351,5681, 5681,7880,7422,6680,5681,6680,7422,7880, 5351,7422,6992,6292,5351,6292,6992,7422, 4816,6680,6292,5663,4816,5663,6292,6680, 4095,5681,5351,4816,4095,4816,5351,5681, 4816,6680,6292,5663,4816,5663,6292,6680, 5351,7422,6992,6292,5351,6292,6992,7422, 5681,7880,7422,6680,5681,6680,7422,7880 ); asm mov edx,esp sub esp,272 and esp,$fffffff0 movdqu xmm0,dqword ptr __xmm_35053505350535053505350535053505 xorps xmm5,xmm5 movdqa dqword ptr [esp+256+_c13573_],xmm0 movdqu xmm0,dqword ptr __xmm_55875587558755875587558755875587 movdqa dqword ptr [esp+256+_c21895_],xmm0 movdqu xmm0,dqword ptr __xmm_aa79aa79aa79aa79aa79aa79aa79aa79 mov eax,dword ptr InputData movdqa dqword ptr [esp+256+_cNeg21895_],xmm0 movdqu xmm0,dqword ptr __xmm_5a825a825a825a825a825a825a825a82 movdqa dqword ptr [esp+256+_c23170_],xmm0 movdqu xmm0,dqword ptr __xmm_a57ea57ea57ea57ea57ea57ea57ea57e movdqa dqword ptr [esp+256+_cNeg23170_],xmm0 movdqu xmm0,dqword ptr __xmm_19761976197619761976197619761976 movdqa dqword ptr [esp+256+_c6518_],xmm0 movdqu xmm0,dqword ptr __xmm_00004000000040000000400000004000 movdqa dqword ptr [esp+256+_c_],xmm0 movdqu xmm0,dqword ptr __xmm_00800080008000800080008000800080 movq xmm6,qword ptr [eax+16] movq xmm7,qword ptr [eax+24] movq xmm1,qword ptr [eax+40] movq xmm2,qword ptr [eax+48] movq xmm3,qword ptr [eax+56] movdqa dqword ptr [esp+256+_k__128_],xmm0 movdqa xmm4,dqword ptr [esp+256+_k__128_] movq xmm0,qword ptr [eax] punpcklbw xmm0,xmm5 psubw xmm0,xmm4 punpcklbw xmm1,xmm5 movdqa dqword ptr [esp+256+_vx_15_],xmm0 psubw xmm1,xmm4 movq xmm0,qword ptr [eax+8] punpcklbw xmm0,xmm5 psubw xmm0,xmm4 punpcklbw xmm3,xmm5 movdqa dqword ptr [esp+256+_a7_1_],xmm0 psubw xmm3,xmm4 movq xmm0,qword ptr [eax+32] punpcklbw xmm0,xmm5 psubw xmm0,xmm4 punpcklbw xmm7,xmm5 punpcklbw xmm2,xmm5 psubw xmm7,xmm4 psubw xmm2,xmm4 punpcklbw xmm6,xmm5 psubw xmm6,xmm4 movdqa xmm4,dqword ptr [esp+256+_vx_15_] movdqa xmm5,xmm4 punpckhwd xmm4,xmm0 punpcklwd xmm5,xmm0 movdqa xmm0,xmm6 movdqa dqword ptr [esp+256+_t5_1_],xmm5 movdqa xmm5,dqword ptr [esp+256+_a7_1_] movdqa dqword ptr [esp+256+_vx_15_],xmm4 movdqa xmm4,xmm5 punpcklwd xmm4,xmm1 punpckhwd xmm5,xmm1 movdqa xmm1,xmm7 punpcklwd xmm1,xmm3 punpckhwd xmm7,xmm3 movdqa xmm3,dqword ptr [esp+256+_t5_1_] punpcklwd xmm0,xmm2 punpckhwd xmm6,xmm2 movdqa xmm2,xmm3 punpckhwd xmm3,xmm0 punpcklwd xmm2,xmm0 movdqa xmm0,dqword ptr [esp+256+_vx_15_] movdqa dqword ptr [esp+256+_t5_1_],xmm3 movdqa xmm3,xmm0 punpckhwd xmm0,xmm6 movdqa dqword ptr [esp+256+_vx_15_],xmm0 movdqa xmm0,xmm4 punpcklwd xmm0,xmm1 punpckhwd xmm4,xmm1 movdqa xmm1,xmm5 punpckhwd xmm5,xmm7 punpcklwd xmm1,xmm7 movdqa xmm7,xmm2 punpcklwd xmm3,xmm6 movdqa dqword ptr [esp+256+_a7_1_],xmm5 punpcklwd xmm7,xmm0 punpckhwd xmm2,xmm0 movdqa xmm0,dqword ptr [esp+256+_t5_1_] movdqa xmm5,xmm0 movdqa dqword ptr [esp+256+_tmp_lo_1],xmm2 punpckhwd xmm0,xmm4 movdqa xmm2,xmm3 punpckhwd xmm3,xmm1 punpcklwd xmm2,xmm1 movdqa xmm1,dqword ptr [esp+256+_tmp_lo_1] movdqa dqword ptr [esp+256+_t5_1_],xmm0 punpcklwd xmm5,xmm4 movdqa xmm4,dqword ptr [esp+256+_vx_15_] movdqa xmm0,xmm4 punpckhwd xmm4,dqword ptr [esp+256+_a7_1_] punpcklwd xmm0,dqword ptr [esp+256+_a7_1_] movdqa xmm6,xmm4 paddsw xmm6,xmm7 psubsw xmm7,xmm4 movdqa xmm4,xmm0 movdqa dqword ptr [esp+256+_t9_1_],xmm7 paddsw xmm4,xmm1 psubsw xmm1,xmm0 movdqa dqword ptr [esp+256+_tmp_lo_1],xmm1 movdqa xmm0,xmm2 movdqa xmm1,xmm3 paddsw xmm1,xmm5 psubsw xmm5,xmm3 movdqa xmm3,dqword ptr [esp+256+_t5_1_] movdqa xmm7,xmm5 paddsw xmm0,xmm3 psubsw xmm3,xmm2 movdqa xmm2,dqword ptr [esp+256+_tmp_lo_1] movdqa dqword ptr [esp+256+_t5_1_],xmm3 paddsw xmm7,xmm2 movdqa xmm3,xmm0 psubsw xmm2,xmm5 movdqa xmm5,dqword ptr [esp+256+_c13573_] paddsw xmm3,xmm6 psubsw xmm6,xmm0 movdqa xmm0,xmm1 paddsw xmm0,xmm4 psubsw xmm4,xmm1 movdqa xmm1,xmm3 psubsw xmm3,xmm0 paddsw xmm1,xmm0 movdqa dqword ptr [esp+256+_vy_14_],xmm3 movdqa dqword ptr [esp+256+_vx_16_],xmm1 movdqa xmm0,xmm4 pmulhw xmm0,xmm5 movdqa xmm1,xmm4 pmullw xmm1,xmm5 movdqa xmm3,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,dqword ptr [esp+256+_c_] punpcklwd xmm3,xmm0 movdqa xmm0,xmm6 paddd xmm3,dqword ptr [esp+256+_c_] psrad xmm1,15 psrad xmm3,15 pslld xmm1,16 pslld xmm3,16 psrad xmm1,16 psrad xmm3,16 pmulhw xmm0,xmm5 packssdw xmm3,xmm1 paddsw xmm3,xmm6 pmullw xmm6,xmm5 movdqa xmm5,dqword ptr [esp+256+_c_] movdqa dqword ptr [esp+256+_b5_2_],xmm3 movdqa xmm1,xmm6 punpckhwd xmm6,xmm0 punpcklwd xmm1,xmm0 paddd xmm6,xmm5 paddd xmm1,xmm5 psrad xmm6,15 psrad xmm1,15 pslld xmm6,16 pslld xmm1,16 psrad xmm6,16 psrad xmm1,16 packssdw xmm1,xmm6 psubsw xmm1,xmm4 movdqa xmm4,dqword ptr [esp+256+_cNeg23170_] movdqa xmm0,xmm2 pmulhw xmm0,dqword ptr [esp+256+_c23170_] movdqa dqword ptr [esp+256+_vy_20_],xmm1 movdqa xmm1,xmm2 pmullw xmm1,dqword ptr [esp+256+_c23170_] movdqa xmm3,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,xmm5 punpcklwd xmm3,xmm0 paddd xmm3,xmm5 psrad xmm1,15 movdqa xmm0,xmm2 psrad xmm3,15 pmullw xmm2,xmm4 pslld xmm1,16 pmulhw xmm0,xmm4 psrad xmm1,16 pslld xmm3,16 movdqa xmm5,xmm2 psrad xmm3,16 punpckhwd xmm2,xmm0 paddd xmm2,dqword ptr [esp+256+_c_] packssdw xmm3,xmm1 movdqa xmm1,xmm7 punpcklwd xmm5,xmm0 movdqa xmm0,xmm7 paddd xmm5,dqword ptr [esp+256+_c_] paddsw xmm3,dqword ptr [esp+256+_t5_1_] pmullw xmm1,xmm4 pmulhw xmm0,xmm4 movdqa xmm4,dqword ptr [esp+256+_c_] psrad xmm2,15 psrad xmm5,15 movdqa xmm6,xmm1 pslld xmm2,16 punpckhwd xmm1,xmm0 punpcklwd xmm6,xmm0 paddd xmm1,xmm4 movdqa xmm0,xmm7 psrad xmm2,16 pmullw xmm7,dqword ptr [esp+256+_c23170_] paddd xmm6,xmm4 pmulhw xmm0,dqword ptr [esp+256+_c23170_] pslld xmm5,16 psrad xmm1,15 psrad xmm5,16 psrad xmm6,15 packssdw xmm5,xmm2 movdqa xmm2,xmm7 punpckhwd xmm7,xmm0 punpcklwd xmm2,xmm0 paddd xmm7,xmm4 paddsw xmm5,dqword ptr [esp+256+_t5_1_] paddd xmm2,xmm4 movdqa xmm4,dqword ptr [esp+256+_c6518_] movdqa xmm0,xmm3 pslld xmm1,16 pslld xmm6,16 psrad xmm7,15 psrad xmm1,16 psrad xmm6,16 psrad xmm2,15 pslld xmm7,16 packssdw xmm6,xmm1 movdqa xmm1,xmm3 paddsw xmm6,dqword ptr [esp+256+_t9_1_] psrad xmm7,16 pslld xmm2,16 pmullw xmm1,xmm4 psrad xmm2,16 pmulhw xmm0,xmm4 packssdw xmm2,xmm7 paddsw xmm2,dqword ptr [esp+256+_t9_1_] movdqa xmm7,xmm1 punpcklwd xmm7,xmm0 paddd xmm7,dqword ptr [esp+256+_c_] psrad xmm7,15 punpckhwd xmm1,xmm0 pslld xmm7,16 psrad xmm7,16 paddd xmm1,dqword ptr [esp+256+_c_] movdqa xmm0,xmm2 psrad xmm1,15 pmulhw xmm0,xmm4 pslld xmm1,16 psrad xmm1,16 packssdw xmm7,xmm1 movdqa xmm1,xmm6 pmullw xmm1,dqword ptr [esp+256+_c21895_] paddsw xmm7,xmm2 pmullw xmm2,xmm4 movdqa xmm4,xmm2 punpckhwd xmm2,xmm0 paddd xmm2,dqword ptr [esp+256+_c_] punpcklwd xmm4,xmm0 movdqa xmm0,xmm6 paddd xmm4,dqword ptr [esp+256+_c_] pmulhw xmm0,dqword ptr [esp+256+_c21895_] psrad xmm2,15 psrad xmm4,15 pslld xmm2,16 pslld xmm4,16 psrad xmm2,16 psrad xmm4,16 packssdw xmm4,xmm2 movdqa xmm2,xmm1 punpckhwd xmm1,xmm0 psubsw xmm4,xmm3 movdqa xmm3,dqword ptr [esp+256+_c_] punpcklwd xmm2,xmm0 paddd xmm1,xmm3 paddd xmm2,xmm3 psrad xmm1,15 psrad xmm2,15 movdqa xmm0,xmm5 pmulhw xmm0,dqword ptr [esp+256+_cNeg21895_] pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm2,xmm1 paddsw xmm2,xmm5 pmullw xmm5,dqword ptr [esp+256+_cNeg21895_] movdqa dqword ptr [esp+256+_tmp_lo_1],xmm5 movdqa xmm1,dqword ptr [esp+256+_tmp_lo_1] punpckhwd xmm1,xmm0 punpcklwd xmm5,xmm0 paddd xmm1,xmm3 paddd xmm5,xmm3 psrad xmm1,15 psrad xmm5,15 movdqa xmm3,xmm7 pslld xmm1,16 pslld xmm5,16 psrad xmm1,16 psrad xmm5,16 punpckhwd xmm7,xmm2 packssdw xmm5,xmm1 movdqa xmm1,dqword ptr [esp+256+_vx_16_] paddsw xmm5,xmm6 movdqa xmm6,xmm1 punpcklwd xmm3,xmm2 punpckhwd xmm1,dqword ptr [esp+256+_vy_14_] movdqa xmm2,dqword ptr [esp+256+_b5_2_] punpcklwd xmm6,dqword ptr [esp+256+_vy_14_] movdqa xmm0,xmm2 punpckhwd xmm2,dqword ptr [esp+256+_vy_20_] punpcklwd xmm0,dqword ptr [esp+256+_vy_20_] movdqa dqword ptr [esp+256+_vx_16_],xmm1 movdqa xmm1,xmm5 movdqa dqword ptr [esp+256+_b5_2_],xmm2 movdqa xmm2,xmm6 movdqa dqword ptr [esp+256+_a7_2_],xmm7 movdqa xmm7,dqword ptr [esp+256+_vx_16_] punpckhwd xmm7,dqword ptr [esp+256+_b5_2_] punpcklwd xmm1,xmm4 punpckhwd xmm5,xmm4 movdqa xmm4,dqword ptr [esp+256+_vx_16_] punpcklwd xmm4,dqword ptr [esp+256+_b5_2_] punpcklwd xmm2,xmm0 punpckhwd xmm6,xmm0 movdqa dqword ptr [esp+256+_vx_16_],xmm7 movdqa xmm0,xmm3 movdqa xmm7,dqword ptr [esp+256+_a7_2_] punpcklwd xmm0,xmm1 punpckhwd xmm3,xmm1 movdqa xmm1,xmm7 punpcklwd xmm1,xmm5 punpckhwd xmm7,xmm5 movdqa xmm5,xmm2 punpckhwd xmm2,xmm0 punpcklwd xmm5,xmm0 movdqa dqword ptr [esp+256+_tmp_lo_1],xmm2 movdqa xmm2,xmm4 punpcklwd xmm2,xmm1 punpckhwd xmm4,xmm1 movdqa dqword ptr [esp+256+_t9_2_],xmm5 movdqa xmm5,xmm6 movdqa xmm1,dqword ptr [esp+256+_t9_2_] punpckhwd xmm6,xmm3 punpcklwd xmm5,xmm3 movdqa xmm3,dqword ptr [esp+256+_vx_16_] movdqa xmm0,xmm3 movdqa dqword ptr [esp+256+_t5_2_],xmm6 punpckhwd xmm3,xmm7 punpcklwd xmm0,xmm7 movdqa xmm6,xmm3 movdqa xmm7,dqword ptr [esp+256+_tmp_lo_1] paddsw xmm6,xmm1 psubsw xmm1,xmm3 movdqa xmm3,xmm0 movdqa dqword ptr [esp+256+_t9_2_],xmm1 paddsw xmm3,xmm7 psubsw xmm7,xmm0 movdqa xmm1,xmm4 paddsw xmm1,xmm5 movdqa xmm0,xmm2 psubsw xmm5,xmm4 movdqa xmm4,dqword ptr [esp+256+_t5_2_] paddsw xmm0,xmm4 psubsw xmm4,xmm2 movdqa xmm2,xmm0 movdqa dqword ptr [esp+256+_t5_2_],xmm4 paddsw xmm2,xmm6 movdqa xmm4,xmm5 psubsw xmm6,xmm0 paddsw xmm4,xmm7 movdqa xmm0,xmm1 psubsw xmm7,xmm5 movdqa xmm5,dqword ptr [esp+256+_c13573_] paddsw xmm0,xmm3 psubsw xmm3,xmm1 movdqa xmm1,xmm2 paddsw xmm1,xmm0 psubsw xmm2,xmm0 movdqa dqword ptr [esp+256+_vy_1_],xmm1 movdqa xmm0,xmm3 movdqa dqword ptr [esp+256+_vy_15_],xmm2 movdqa xmm1,xmm3 pmullw xmm1,xmm5 pmulhw xmm0,xmm5 movdqa xmm2,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,dqword ptr [esp+256+_c_] punpcklwd xmm2,xmm0 movdqa xmm0,xmm6 paddd xmm2,dqword ptr [esp+256+_c_] psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 pmulhw xmm0,xmm5 packssdw xmm2,xmm1 paddsw xmm2,xmm6 pmullw xmm6,xmm5 movdqa xmm5,dqword ptr [esp+256+_c_] movdqa dqword ptr [esp+256+_vy_9_],xmm2 movdqa xmm1,xmm6 punpcklwd xmm1,xmm0 paddd xmm1,xmm5 punpckhwd xmm6,xmm0 movdqa xmm0,xmm7 pmulhw xmm0,dqword ptr [esp+256+_c23170_] paddd xmm6,xmm5 psrad xmm1,15 psrad xmm6,15 pslld xmm1,16 movdqa xmm2,dqword ptr [esp+256+_cNeg23170_] psrad xmm1,16 pslld xmm6,16 psrad xmm6,16 packssdw xmm1,xmm6 psubsw xmm1,xmm3 movdqa dqword ptr [esp+256+_vy_21_],xmm1 movdqa xmm1,xmm7 pmullw xmm1,dqword ptr [esp+256+_c23170_] movdqa xmm3,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,xmm5 punpcklwd xmm3,xmm0 paddd xmm3,xmm5 psrad xmm1,15 movdqa xmm0,xmm7 psrad xmm3,15 pmullw xmm7,xmm2 pmulhw xmm0,xmm2 pslld xmm1,16 pslld xmm3,16 psrad xmm1,16 movdqa xmm6,xmm7 psrad xmm3,16 punpcklwd xmm6,xmm0 punpckhwd xmm7,xmm0 paddd xmm6,xmm5 packssdw xmm3,xmm1 paddd xmm7,xmm5 movdqa xmm1,xmm4 paddsw xmm3,dqword ptr [esp+256+_t5_2_] pmullw xmm1,xmm2 movdqa xmm0,xmm4 pmulhw xmm0,xmm2 psrad xmm6,15 psrad xmm7,15 pslld xmm6,16 movdqa xmm5,xmm1 pslld xmm7,16 punpcklwd xmm5,xmm0 punpckhwd xmm1,xmm0 movdqa xmm0,xmm4 pmullw xmm4,dqword ptr [esp+256+_c23170_] pmulhw xmm0,dqword ptr [esp+256+_c23170_] psrad xmm7,16 psrad xmm6,16 movdqa xmm2,xmm4 packssdw xmm6,xmm7 movdqa xmm7,dqword ptr [esp+256+_c_] paddsw xmm6,dqword ptr [esp+256+_t5_2_] paddd xmm5,xmm7 punpcklwd xmm2,xmm0 paddd xmm1,xmm7 punpckhwd xmm4,xmm0 paddd xmm2,xmm7 paddd xmm4,xmm7 psrad xmm5,15 movdqa xmm7,dqword ptr [esp+256+_c6518_] movdqa xmm0,xmm3 psrad xmm2,15 psrad xmm1,15 psrad xmm4,15 pslld xmm5,16 pslld xmm2,16 pslld xmm1,16 pslld xmm4,16 psrad xmm5,16 psrad xmm2,16 psrad xmm1,16 psrad xmm4,16 packssdw xmm5,xmm1 paddsw xmm5,dqword ptr [esp+256+_t9_2_] packssdw xmm2,xmm4 paddsw xmm2,dqword ptr [esp+256+_t9_2_] pmulhw xmm0,xmm7 movdqa xmm1,xmm3 pmullw xmm1,xmm7 mov eax,OFFSET PostScaleArray movdqa xmm4,xmm1 punpckhwd xmm1,xmm0 paddd xmm1,dqword ptr [esp+256+_c_] punpcklwd xmm4,xmm0 movdqa xmm0,xmm2 paddd xmm4,dqword ptr [esp+256+_c_] psrad xmm1,15 pmulhw xmm0,xmm7 pslld xmm1,16 psrad xmm4,15 psrad xmm1,16 pslld xmm4,16 psrad xmm4,16 packssdw xmm4,xmm1 paddsw xmm4,xmm2 pmullw xmm2,xmm7 movdqa xmm1,xmm2 punpckhwd xmm2,xmm0 paddd xmm2,dqword ptr [esp+256+_c_] punpcklwd xmm1,xmm0 movdqa xmm0,xmm5 paddd xmm1,dqword ptr [esp+256+_c_] pmulhw xmm0,dqword ptr [esp+256+_c21895_] psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 movdqa xmm2,dqword ptr [esp+256+_c_] psubsw xmm1,xmm3 movdqa dqword ptr [esp+256+_vy_24_],xmm1 movdqa xmm1,xmm5 pmullw xmm1,dqword ptr [esp+256+_c21895_] movdqa xmm7,xmm1 punpckhwd xmm1,xmm0 punpcklwd xmm7,xmm0 paddd xmm1,xmm2 paddd xmm7,xmm2 psrad xmm1,15 psrad xmm7,15 movdqa xmm0,xmm6 pmulhw xmm0,dqword ptr [esp+256+_cNeg21895_] pslld xmm7,16 pslld xmm1,16 psrad xmm7,16 psrad xmm1,16 packssdw xmm7,xmm1 paddsw xmm7,xmm6 pmullw xmm6,dqword ptr [esp+256+_cNeg21895_] movdqa xmm3,xmm6 punpckhwd xmm6,xmm0 punpcklwd xmm3,xmm0 paddd xmm6,xmm2 paddd xmm3,xmm2 psrad xmm6,15 movdqu xmm2,dqword ptr [eax] mov eax,dword ptr OutputData psrad xmm3,15 movdqa xmm1,xmm2 pslld xmm6,16 pmullw xmm2,dqword ptr [esp+256+_vy_1_] pmulhw xmm1,dqword ptr [esp+256+_vy_1_] pslld xmm3,16 psrad xmm6,16 psrad xmm3,16 movdqa xmm0,xmm2 punpcklwd xmm0,xmm1 packssdw xmm3,xmm6 movdqa xmm6,dqword ptr [esp+256+_c_] paddsw xmm3,xmm5 paddd xmm0,xmm6 xorps xmm5,xmm5 psrad xmm0,15 pslld xmm0,16 psrad xmm0,16 punpckhwd xmm2,xmm1 mov ecx,OFFSET PostScaleArray+16 paddd xmm2,xmm6 psrad xmm2,15 pslld xmm2,16 psrad xmm2,16 packssdw xmm0,xmm2 paddsw xmm0,xmm5 movdqu dqword ptr [eax],xmm0 movdqu xmm2,dqword ptr [ecx] mov ecx,OFFSET PostScaleArray+32 movdqa xmm0,xmm2 pmullw xmm2,xmm4 pmulhw xmm0,xmm4 movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 psrad xmm1,15 paddd xmm2,xmm6 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+16],xmm1 movdqu xmm2,dqword ptr [ecx] mov ecx,OFFSET PostScaleArray+48 movdqa xmm0,xmm2 pmullw xmm2,dqword ptr [esp+256+_vy_9_] pmulhw xmm0,dqword ptr [esp+256+_vy_9_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 paddd xmm2,xmm6 psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+32],xmm1 movdqu xmm2,dqword ptr [ecx] mov ecx,OFFSET PostScaleArray+64 movdqa xmm0,xmm2 pmullw xmm2,xmm3 pmulhw xmm0,xmm3 movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 paddd xmm2,xmm6 psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+48],xmm1 movdqu xmm2,dqword ptr [ecx] movdqa xmm0,xmm2 pmullw xmm2,dqword ptr [esp+256+_vy_15_] pmulhw xmm0,dqword ptr [esp+256+_vy_15_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 paddd xmm2,xmm6 psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 mov ecx,OFFSET PostScaleArray+80 paddsw xmm1,xmm5 movdqu dqword ptr [eax+64],xmm1 movdqu xmm2,dqword ptr [ecx] mov ecx,OFFSET PostScaleArray+96 movdqa xmm0,xmm2 pmullw xmm2,xmm7 pmulhw xmm0,xmm7 movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 psrad xmm1,15 paddd xmm2,xmm6 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+80],xmm1 movdqu xmm2,dqword ptr [ecx] mov ecx,OFFSET PostScaleArray+112 movdqa xmm0,xmm2 pmullw xmm2,dqword ptr [esp+256+_vy_21_] pmulhw xmm0,dqword ptr [esp+256+_vy_21_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 psrad xmm1,15 paddd xmm2,xmm6 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+96],xmm1 movdqu xmm2,dqword ptr [ecx] movdqa xmm0,xmm2 pmullw xmm2,dqword ptr [esp+256+_vy_24_] pmulhw xmm0,dqword ptr [esp+256+_vy_24_] movdqa xmm1,xmm2 punpcklwd xmm1,xmm0 punpckhwd xmm2,xmm0 paddd xmm1,xmm6 paddd xmm2,xmm6 psrad xmm1,15 psrad xmm2,15 pslld xmm1,16 pslld xmm2,16 psrad xmm1,16 psrad xmm2,16 packssdw xmm1,xmm2 paddsw xmm1,xmm5 movdqu dqword ptr [eax+112],xmm1 mov esp,edx end; {$endif} {$endif} {$endif} {$endif} procedure TpvJPEGEncoder.DCT2D; const CONST_BITS=13; ROW_BITS=2; SHIFT0=CONST_BITS-ROW_BITS; SHIFT0ADD=1 shl (SHIFT0-1); SHIFT1=ROW_BITS+3; SHIFT1ADD=1 shl (SHIFT1-1); SHIFT2=CONST_BITS+ROW_BITS+3; SHIFT2ADD=1 shl (SHIFT2-1); var s0,s1,s2,s3,s4,s5,s6,s7,t0,t1,t2,t3,t4,t5,t6,t7,t10,t13,t11,t12,u1,u2,u3,u4,z5,c:TpvInt32; b:PpvJPEGEncoderUInt8Array; q:PpvJPEGEncoderInt32Array; s:PpvJPEGEncoderInt16Array; begin b:=TpvPointer(@fSamples8Bit); q:=TpvPointer(@fSamples32Bit); for c:=0 to 7 do begin s0:=TpvInt32(b^[0])-128; s1:=TpvInt32(b^[1])-128; s2:=TpvInt32(b^[2])-128; s3:=TpvInt32(b^[3])-128; s4:=TpvInt32(b^[4])-128; s5:=TpvInt32(b^[5])-128; s6:=TpvInt32(b^[6])-128; s7:=TpvInt32(b^[7])-128; b:=TpvPointer(@b[8]); t0:=s0+s7; t7:=s0-s7; t1:=s1+s6; t6:=s1-s6; t2:=s2+s5; t5:=s2-s5; t3:=s3+s4; t4:=s3-s4; t10:=t0+t3; t13:=t0-t3; t11:=t1+t2; t12:=t1-t2; u1:=TpvInt16(t12+t13)*TpvInt32(4433); s2:=u1+(TpvInt16(t13)*TpvInt32(6270)); s6:=u1+(TpvInt16(t12)*TpvInt32(-15137)); u1:=t4+t7; u2:=t5+t6; u3:=t4+t6; u4:=t5+t7; z5:=TpvInt16(u3+u4)*TpvInt32(9633); t4:=TpvInt16(t4)*TpvInt32(2446); t5:=TpvInt16(t5)*TpvInt32(16819); t6:=TpvInt16(t6)*TpvInt32(25172); t7:=TpvInt16(t7)*TpvInt32(12299); u1:=TpvInt16(u1)*TpvInt32(-7373); u2:=TpvInt16(u2)*TpvInt32(-20995); u3:=(TpvInt16(u3)*TpvInt32(-16069))+z5; u4:=(TpvInt16(u4)*TpvInt32(-3196))+z5; s0:=t10+t11; s1:=t7+u1+u4; s3:=t6+u2+u3; s4:=t10-t11; s5:=t5+u2+u4; s7:=t4+u1+u3; q^[0]:=s0 shl ROW_BITS; q^[1]:=SARLongint(s1+SHIFT0ADD,SHIFT0); q^[2]:=SARLongint(s2+SHIFT0ADD,SHIFT0); q^[3]:=SARLongint(s3+SHIFT0ADD,SHIFT0); q^[4]:=s4 shl ROW_BITS; q^[5]:=SARLongint(s5+SHIFT0ADD,SHIFT0); q^[6]:=SARLongint(s6+SHIFT0ADD,SHIFT0); q^[7]:=SARLongint(s7+SHIFT0ADD,SHIFT0); q:=TpvPointer(@q[8]); end; q:=TpvPointer(@fSamples32Bit); s:=TpvPointer(@fSamples16Bit); for c:=0 to 7 do begin s0:=q^[0*8]; s1:=q^[1*8]; s2:=q^[2*8]; s3:=q^[3*8]; s4:=q^[4*8]; s5:=q^[5*8]; s6:=q^[6*8]; s7:=q^[7*8]; q:=TpvPointer(@q[1]); t0:=s0+s7; t7:=s0-s7; t1:=s1+s6; t6:=s1-s6; t2:=s2+s5; t5:=s2-s5; t3:=s3+s4; t4:=s3-s4; t10:=t0+t3; t13:=t0-t3; t11:=t1+t2; t12:=t1-t2; u1:=TpvInt16(t12+t13)*TpvInt32(4433); s2:=u1+(TpvInt16(t13)*TpvInt32(6270)); s6:=u1+(TpvInt16(t12)*TpvInt32(-15137)); u1:=t4+t7; u2:=t5+t6; u3:=t4+t6; u4:=t5+t7; z5:=TpvInt16(u3+u4)*TpvInt32(9633); t4:=TpvInt16(t4)*TpvInt32(2446); t5:=TpvInt16(t5)*TpvInt32(16819); t6:=TpvInt16(t6)*TpvInt32(25172); t7:=TpvInt16(t7)*TpvInt32(12299); u1:=TpvInt16(u1)*TpvInt32(-7373); u2:=TpvInt16(u2)*TpvInt32(-20995); u3:=(TpvInt16(u3)*TpvInt32(-16069))+z5; u4:=(TpvInt16(u4)*TpvInt32(-3196))+z5; s0:=t10+t11; s1:=t7+u1+u4; s3:=t6+u2+u3; s4:=t10-t11; s5:=t5+u2+u4; s7:=t4+u1+u3; s^[0*8]:=SARLongint(s0+SHIFT1ADD,SHIFT1); s^[1*8]:=SARLongint(s1+SHIFT2ADD,SHIFT2); s^[2*8]:=SARLongint(s2+SHIFT2ADD,SHIFT2); s^[3*8]:=SARLongint(s3+SHIFT2ADD,SHIFT2); s^[4*8]:=SARLongint(s4+SHIFT1ADD,SHIFT1); s^[5*8]:=SARLongint(s5+SHIFT2ADD,SHIFT2); s^[6*8]:=SARLongint(s6+SHIFT2ADD,SHIFT2); s^[7*8]:=SARLongint(s7+SHIFT2ADD,SHIFT2); s:=TpvPointer(@s[1]); end; end; procedure TpvJPEGEncoder.LoadQuantizedCoefficients(ComponentIndex:TpvInt32); const ZigZagTable:array[0..63] of TpvUInt8=(0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63); var q:PpvInt32; pDst:PpvInt16; i,j:TpvInt32; begin if ComponentIndex>0 then begin q:=TpvPointer(@fQuantizationTables[1]); end else begin q:=TpvPointer(@fQuantizationTables[0]); end; pDst:=TpvPointer(@fCoefficients[0]); for i:=0 to 63 do begin j:=fSamples16Bit[ZigZagTable[i]]; if j<0 then begin j:=SARLongint(q^,1)-j; if j<q^ then begin pDst^:=0; end else begin pDst^:=-(j div q^); end; end else begin inc(j,SARLongint(q^,1)); if j<q^ then begin pDst^:=0; end else begin pDst^:=j div q^; end; end; inc(pDst); inc(q); end; end; procedure TpvJPEGEncoder.CodeCoefficientsPassOne(ComponentIndex:TpvInt32); var i,RunLen,CountBits,t1:TpvInt32; src:PpvJPEGEncoderInt16Array; DCCounts,ACCounts:PpvJPEGEncoderUInt32Array; begin src:=TpvPointer(@fCoefficients[0]); if ComponentIndex<>0 then begin DCCounts:=TpvPointer(@fHuffmanCounts[0+1]); ACCounts:=TpvPointer(@fHuffmanCounts[2+1]); end else begin DCCounts:=TpvPointer(@fHuffmanCounts[0+0]); ACCounts:=TpvPointer(@fHuffmanCounts[2+0]); end; t1:=src^[0]-fLastDCValues[ComponentIndex]; fLastDCValues[ComponentIndex]:=src^[0]; if t1<0 then begin t1:=-t1; end; CountBits:=0; while t1<>0 do begin inc(CountBits); t1:=t1 shr 1; end; inc(DCCounts[CountBits]); RunLen:=0; for i:=1 to 63 do begin t1:=fCoefficients[i]; if t1=0 then begin inc(RunLen); end else begin while RunLen>=16 do begin inc(ACCounts^[$f0]); dec(RunLen,16); end; if t1<0 then begin t1:=-t1; end; CountBits:=1; repeat t1:=t1 shr 1; if t1<>0 then begin inc(CountBits); end else begin break; end; until false; inc(ACCounts^[(RunLen shl 4)+CountBits]); RunLen:=0; end; end; if RunLen<>0 then begin inc(ACCounts^[0]); end; end; procedure TpvJPEGEncoder.CodeCoefficientsPassTwo(ComponentIndex:TpvInt32); var i,j,RunLen,CountBits,t1,t2:TpvInt32; pSrc:PpvJPEGEncoderInt16Array; Codes:array[0..1] of PpvJPEGEncoderUInt32Array; CodeSizes:array[0..1] of PpvJPEGEncoderUInt8Array; begin if ComponentIndex=0 then begin Codes[0]:=TpvPointer(@fHuffmanCodes[0+0]); Codes[1]:=TpvPointer(@fHuffmanCodes[2+0]); CodeSizes[0]:=TpvPointer(@fHuffmanCodeSizes[0+0]); CodeSizes[1]:=TpvPointer(@fHuffmanCodeSizes[2+0]); end else begin Codes[0]:=TpvPointer(@fHuffmanCodes[0+1]); Codes[1]:=TpvPointer(@fHuffmanCodes[2+1]); CodeSizes[0]:=TpvPointer(@fHuffmanCodeSizes[0+1]); CodeSizes[1]:=TpvPointer(@fHuffmanCodeSizes[2+1]); end; pSrc:=TpvPointer(@fCoefficients[0]); t1:=pSrc^[0]-fLastDCValues[ComponentIndex]; t2:=t1; fLastDCValues[ComponentIndex]:=pSrc^[0]; if t1<0 then begin t1:=-t1; dec(t2); end; CountBits:=0; while t1<>0 do begin inc(CountBits); t1:=t1 shr 1; end; PutBits(Codes[0]^[CountBits],CodeSizes[0]^[CountBits]); if CountBits<>0 then begin PutBits(t2 and ((1 shl CountBits)-1),CountBits); end; RunLen:=0; for i:=1 to 63 do begin t1:=fCoefficients[i]; if t1=0 then begin inc(RunLen); end else begin while RunLen>=16 do begin PutBits(Codes[1]^[$f0],CodeSizes[1]^[$f0]); dec(RunLen,16); end; t2:=t1; if t2<0 then begin t1:=-t1; dec(t2); end; CountBits:=1; repeat t1:=t1 shr 1; if t1<>0 then begin inc(CountBits); end else begin break; end; until false; j:=(RunLen shl 4)+CountBits; PutBits(Codes[1]^[j],CodeSizes[1]^[j]); PutBits(t2 and ((1 shl CountBits)-1),CountBits); RunLen:=0; end; end; if RunLen<>0 then begin PutBits(Codes[1]^[0],CodeSizes[1]^[0]); end; end; procedure TpvJPEGEncoder.CodeBlock(ComponentIndex:TpvInt32); begin {$ifdef PurePascal} DCT2D; {$else} {$ifdef cpu386} DCT2DSSE(@fSamples8Bit,@fSamples16Bit); {$else} DCT2D; {$endif} {$endif} LoadQuantizedCoefficients(ComponentIndex); if fPassIndex=1 then begin CodeCoefficientsPassOne(ComponentIndex); end else begin CodeCoefficientsPassTwo(ComponentIndex); end; end; procedure TpvJPEGEncoder.ProcessMCURow; var i:TpvInt32; begin if fCountComponents=1 then begin for i:=0 to fMCUsPerRow-1 do begin LoadBlock8x8(i,0,0); CodeBlock(0); end; end else if (fComponentHSamples[0]=1) and (fComponentVSamples[0]=1) then begin for i:=0 to fMCUsPerRow-1 do begin LoadBlock8x8(i,0,0); CodeBlock(0); LoadBlock8x8(i,0,1); CodeBlock(1); LoadBlock8x8(i,0,2); CodeBlock(2); end; end else if (fComponentHSamples[0]=2) and (fComponentVSamples[0]=1) then begin for i:=0 to fMCUsPerRow-1 do begin LoadBlock8x8((i*2)+0,0,0); CodeBlock(0); LoadBlock8x8((i*2)+1,0,0); CodeBlock(0); LoadBlock16x8x8(i,1); CodeBlock(1); LoadBlock16x8x8(i,2); CodeBlock(2); end; end else if (fComponentHSamples[0]=2) and (fComponentVSamples[0]=2) then begin for i:=0 to fMCUsPerRow-1 do begin LoadBlock8x8((i*2)+0,0,0); CodeBlock(0); LoadBlock8x8((i*2)+1,0,0); CodeBlock(0); LoadBlock8x8((i*2)+0,1,0); CodeBlock(0); LoadBlock8x8((i*2)+1,1,0); CodeBlock(0); LoadBlock16x8(i,1); CodeBlock(1); LoadBlock16x8(i,2); CodeBlock(2); end; end; end; procedure TpvJPEGEncoder.LoadMCU(p:TpvPointer); var pDst:PpvJPEGEncoderUInt8Array; c:TpvInt32; begin if fCountComponents=1 then begin ConvertRGBAToY(TpvPointer(@fMCUChannels[0]^[fMCUYOffset*fImageWidthMCU]),TpvPointer(p),fImageWidth); end else begin ConvertRGBAToYCbCr(TpvPointer(@fMCUChannels[0]^[fMCUYOffset*fImageWidthMCU]),TpvPointer(@fMCUChannels[1]^[fMCUYOffset*fImageWidthMCU]),TpvPointer(@fMCUChannels[2]^[fMCUYOffset*fImageWidthMCU]),TpvPointer(p),fImageWidth); end; if fImageWidth<fImageWidthMCU then begin for c:=0 to fCountComponents-1 do begin pDst:=TpvPointer(@fMCUChannels[c]^[fMCUYOffset*fImageWidthMCU]); FillChar(pDst^[fImageWidth],fImageWidthMCU-fImageWidth,AnsiChar(TpvUInt8(pDst^[fImageWidth-1]))); end; end; inc(fMCUYOffset); if fMCUYOffset=fMCUHeight then begin ProcessMCURow; fMCUYOffset:=0; end; end; function TpvJPEGEncoder.RadixSortSymbols(CountSymbols:TpvUInt32;SymbolsA,SymbolsB:PpvJPEGHuffmanSymbolFrequencies):PpvJPEGHuffmanSymbolFrequency; const MaxPasses=4; var i,freq,TotalPasses,CurrentOffset:TpvUInt32; PassShift,Pass:TpvInt32; CurrentSymbols,NewSymbols,t:PpvJPEGHuffmanSymbolFrequencies; Histogramm:array[0..(256*MaxPasses)-1] of TpvUInt32; Offsets:array[0..255] of TpvUInt32; pHistogramm:PpvJPEGEncoderUInt32Array; begin FillChar(Histogramm,SizeOf(Histogramm),#0); for i:=1 to CountSymbols do begin freq:=SymbolsA^[i-1].key; inc(Histogramm[freq and $ff]); inc(Histogramm[256+((freq shr 8) and $ff)]); inc(Histogramm[(256*2)+((freq shr 16) and $ff)]); inc(Histogramm[(256*3)+((freq shr 24) and $ff)]); end; CurrentSymbols:=SymbolsA; NewSymbols:=SymbolsB; TotalPasses:=MaxPasses; while (TotalPasses>1) and (CountSymbols=Histogramm[(TotalPasses-1)*256]) do begin dec(TotalPasses); end; PassShift:=0; for Pass:=0 to TpvInt32(TotalPasses)-1 do begin pHistogramm:=@Histogramm[Pass shl 8]; CurrentOffset:=0; for i:=0 to 255 do begin Offsets[i]:=CurrentOffset; inc(CurrentOffset,pHistogramm^[i]); end; for i:=1 to CountSymbols do begin NewSymbols^[Offsets[(CurrentSymbols^[i-1].key shr PassShift) and $ff]]:=CurrentSymbols^[i-1]; inc(Offsets[(CurrentSymbols^[i-1].key shr PassShift) and $ff]); end; t:=CurrentSymbols; CurrentSymbols:=NewSymbols; NewSymbols:=t; inc(PassShift,8); end; result:=TpvPointer(CurrentSymbols); end; procedure TpvJPEGEncoder.CalculateMinimumRedundancy(a:PpvJPEGHuffmanSymbolFrequencies;n:TpvInt32); var Root,Leaf,Next,Avaliable,Used,Depth:TpvInt32; begin if n=0 then begin exit; end else if n=1 then begin A^[0].key:=1; exit; end; inc(A^[0].key,A^[1].key); Root:=0; Leaf:=2; for Next:=1 to n-2 do begin if (Leaf>=n) or (A^[Root].key<A^[Leaf].key) then begin A^[Next].key:=A^[Root].key; A^[Root].key:=Next; inc(Root); end else begin A^[Next].key:=A^[Leaf].key; inc(Leaf); end; if (Leaf>=n) or ((Root<Next) and (A^[Root].key<A^[Leaf].key)) then begin inc(A^[Next].key,A^[Root].key); A^[Root].key:=Next; inc(Root); end else begin inc(A^[Next].key,A^[Leaf].key); inc(Leaf); end; end; A^[n-2].key:=0; for Next:=n-3 downto 0 do begin A^[Next].key:=A^[A^[Next].key].key+1; end; Avaliable:=1; Used:=0; Depth:=0; Root:=n-2; Next:=n-1; while Avaliable>0 do begin while (Root>=0) and (TpvUInt32(A^[Root].key)=TpvUInt32(Depth)) do begin inc(Used); dec(Root); end; while Avaliable>Used do begin A^[Next].key:=Depth; dec(Next); dec(Avaliable); end; Avaliable:=2*Used; inc(Depth); Used:=0; end; end; procedure TpvJPEGEncoder.HuffmanEnforceMaxCodeSize(CountCodes:PpvJPEGEncoderInt32Array;CodeListLen,MaxCodeSize:TpvInt32); var i:TpvInt32; Total:TpvUInt32; begin if CodeListLen<=1 then begin exit; end; for i:=MaxCodeSize+1 to JPEG_MAX_HUFFMAN_CODE_SIZE do begin inc(CountCodes^[MaxCodeSize],CountCodes^[i]); end; Total:=0; for i:=MaxCodeSize downto 1 do begin inc(Total,TpvUInt32(CountCodes[i]) shl (MaxCodeSize - i)); end; while Total<>(1 shl MaxCodeSize) do begin dec(CountCodes[MaxCodeSize]); for i:=MaxCodeSize-1 downto 1 do begin if CountCodes[i]<>0 then begin dec(CountCodes[i]); inc(CountCodes[i+1],2); break; end; end; dec(Total); end; end; procedure TpvJPEGEncoder.OptimizeHuffmanTable(TableIndex,TableLen:TpvInt32); const CODE_SIZE_LIMIT=16; var CountUsedSymbols,i:TpvInt32; CountSymbols:PpvJPEGEncoderUInt32Array; SymbolFreqs:PpvJPEGHuffmanSymbolFrequency; SymbolsA,SymbolsB:array[0..JPEG_MAX_HUFFMAN_SYMBOLS] of TpvJPEGHuffmanSymbolFrequency; CountCodes:array[0..JPEG_MAX_HUFFMAN_CODE_SIZE] of TpvInt32; begin SymbolsA[0].key:=1; SymbolsA[0].Index:=0; CountUsedSymbols:=1; CountSymbols:=TpvPointer(@fHuffmanCounts[TableIndex,0]); for i:=1 to TableLen do begin if CountSymbols^[i-1]>0 then begin SymbolsA[CountUsedSymbols].key:=CountSymbols^[i-1]; SymbolsA[CountUsedSymbols].Index:=i; inc(CountUsedSymbols); end; end; SymbolFreqs:=RadixSortSymbols(CountUsedSymbols,TpvPointer(@SymbolsA[0]),TpvPointer(@SymbolsB[0])); CalculateMinimumRedundancy(TpvPointer(SymbolFreqs),CountUsedSymbols); FillChar(CountCodes,SizeOf(CountCodes),#0); for i:=1 to CountUsedSymbols do begin inc(CountCodes[PpvJPEGHuffmanSymbolFrequencies(SymbolFreqs)^[i-1].key]); end; HuffmanEnforceMaxCodeSize(TpvPointer(@CountCodes),CountUsedSymbols,CODE_SIZE_LIMIT); FillChar(fHuffmanBits[TableIndex],SizeOf(fHuffmanBits[TableIndex]),#0); for i:=1 to CODE_SIZE_LIMIT do begin fHuffmanBits[TableIndex,i]:=CountCodes[i]; end; for i:=CODE_SIZE_LIMIT downto 1 do begin if fHuffmanBits[TableIndex,i]<>0 then begin dec(fHuffmanBits[TableIndex,i]); break; end; end; for i:=CountUsedSymbols-1 downto 1 do begin fHuffmanValues[TableIndex, CountUsedSymbols-(i+1)]:=PpvJPEGHuffmanSymbolFrequencies(SymbolFreqs)^[i].Index-1; end; end; function TpvJPEGEncoder.TerminatePassOne:boolean; begin OptimizeHuffmanTable(0+0,JPEG_DC_LUMA_CODES); OptimizeHuffmanTable(2+0,JPEG_AC_LUMA_CODES); if fCountComponents>1 then begin OptimizeHuffmanTable(0+1,JPEG_DC_CHROMA_CODES); OptimizeHuffmanTable(2+1,JPEG_AC_CHROMA_CODES); end; result:=InitSecondPass; end; function TpvJPEGEncoder.TerminatePassTwo:boolean; const M_EOI=$d9; begin PutBits($7f,7); FlushOutputBuffer; EmitMarker(M_EOI); inc(fPassIndex); result:=true; end; function TpvJPEGEncoder.ProcessEndOfImage:boolean; var i,c:TpvInt32; begin if fMCUYOffset<>0 then begin if fMCUYOffset<16 then begin for c:=0 to fCountComponents-1 do begin for i:=fMCUYOffset to fMCUHeight-1 do begin Move(fMCUChannels[c]^[(fMCUYOffset-1)*fImageWidthMCU],fMCUChannels[c]^[i*fImageWidthMCU],fImageWidthMCU); end; end; end; ProcessMCURow; end; if fPassIndex=1 then begin result:=TerminatePassOne; end else begin result:=TerminatePassTwo; end; end; function TpvJPEGEncoder.ProcessScanline(pScanline:TpvPointer):boolean; begin result:=false; if (fPassIndex<1) or (fPassIndex>2) then begin exit; end; if assigned(pScanline) then begin LoadMCU(pScanline); end else begin if not ProcessEndOfImage then begin exit; end; end; result:=true; end; function TpvJPEGEncoder.Encode(const FrameData:TpvPointer;var CompressedData:TpvPointer;Width,Height:TpvInt32;Quality,MaxCompressedDataSize:TpvUInt32;const Fast:boolean=false;const ChromaSubsampling:TpvInt32=-1):TpvUInt32; type PPixel=^TPixel; TPixel=packed record r,g,b,a:TpvUInt8; end; var PassIndex,Passes,x,y:TpvInt32; Pixel:PPixel; OK,HasColor:LongBool; begin result:=0; fCompressedData:=CompressedData; fCompressedDataPosition:=0; fCompressedDataAllocated:=0; fMaxCompressedDataSize:=MaxCompressedDataSize; fQuality:=Quality; fTwoPass:=not Fast; fNoChromaDiscrimination:=false; fMCUChannels[0]:=nil; fMCUChannels[1]:=nil; fMCUChannels[2]:=nil; fPassIndex:=0; case ChromaSubsampling of 0:begin fBlockEncodingMode:=1; // H1V1 4:4:4 (common for the most high-end digital cameras and professional image editing software) end; 1:begin fBlockEncodingMode:=2; // H2V1 4:2:2 (common for the most mid-range digital cameras and consumer image editing software) end; 2:begin fBlockEncodingMode:=3; // H2V2 4:2:0 (common for the most cheap digital cameras and other cheap stuff) end; else {-1:}begin if fQuality>=95 then begin fBlockEncodingMode:=1; // H1V1 4:4:4 (common for the most high-end digital cameras and professional image editing software) end else if fQuality>=50 then begin fBlockEncodingMode:=2; // H2V1 4:2:2 (common for the most mid-range digital cameras and consumer image editing software) end else begin fBlockEncodingMode:=3; // H2V2 4:2:0 (common for the most cheap digital cameras and other cheap stuff) end; end; end; if assigned(FrameData) and not Fast then begin HasColor:=false; Pixel:=FrameData; for y:=0 to Height-1 do begin for x:=0 to Width-1 do begin if (Pixel^.r<>Pixel^.g) or (Pixel^.r<>Pixel^.b) or (Pixel^.g<>Pixel^.b) then begin HasColor:=true; break; end; inc(Pixel); end; if HasColor then begin break; end; end; if not HasColor then begin fBlockEncodingMode:=0; // Greyscale end; end; try if Setup(Width,Height) then begin OK:=true; if fTwoPass then begin Passes:=2; end else begin Passes:=1; end; for PassIndex:=0 to Passes-1 do begin for y:=0 to Height-1 do begin OK:=ProcessScanline(TpvPointer(@PpvJPEGEncoderUInt8Array(FrameData)^[(y*Width) shl 2])); if not OK then begin break; end; end; if OK then begin OK:=ProcessScanline(nil); end; if not OK then begin break; end; end; if OK then begin result:=fCompressedDataPosition; end; end; finally fMCUChannels[0]:=nil; fMCUChannels[1]:=nil; fMCUChannels[2]:=nil; if result>0 then begin ReallocMem(fCompressedData,fCompressedDataPosition); end else if assigned(fCompressedData) then begin FreeMem(fCompressedData); fCompressedData:=nil; end; CompressedData:=fCompressedData; end; end; function SaveJPEGImage(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;out aDestData:TpvPointer;out aDestDataSize:TpvUInt32;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; var JPEGEncoder:TpvJPEGEncoder; begin JPEGEncoder:=TpvJPEGEncoder.Create; try aDestData:=nil; aDestDataSize:=JPEGEncoder.Encode(aImageData,aDestData,aImageWidth,aImageHeight,aQuality,0,aFast,aChromaSubsampling); result:=aDestDataSize>0; finally JPEGEncoder.Free; end; end; function SaveJPEGImageAsStream(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aStream:TStream;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; var Data:TpvPointer; DataSize:TpvUInt32; begin result:=SaveJPEGImage(aImageData,aImageWidth,aImageHeight,Data,DataSize,aQuality,aFast,aChromaSubsampling); if assigned(Data) then begin try aStream.Write(Data^,DataSize); finally FreeMem(Data); end; end; end; function SaveJPEGImageAsFile(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aFileName:string;const aQuality:TpvInt32=99;const aFast:boolean=false;const aChromaSubsampling:TpvInt32=-1):boolean; var FileStream:TFileStream; begin FileStream:=TFileStream.Create(aFileName,fmCreate); try result:=SaveJPEGImageAsStream(aImageData,aImageWidth,aImageHeight,FileStream,aQuality,aFast,aChromaSubsampling); finally FileStream.Free; end; end; {$if false} // C sources of the DCT functions: inline __m128i _mm_mr_epi16(__m128i x, __m128i y, __m128i c){ __m128i h = _mm_mulhi_epi16(x, y), l = _mm_mullo_epi16(x, y); return _mm_packs_epi32(_mm_srai_epi32(_mm_slli_epi32(_mm_srai_epi32(_mm_add_epi32(_mm_unpacklo_epi16(l, h), c), 15), 16), 16), _mm_srai_epi32(_mm_slli_epi32(_mm_srai_epi32(_mm_add_epi32(_mm_unpackhi_epi16(l, h), c), 15), 16), 16)); } #define _mm_mradds_epi16(x, y, z) _mm_adds_epi16(_mm_mr_epi16(x, y, c), z) __declspec(dllexport) void __stdcall DCT2DSlow(uint8_t *input, int16_t *output) { __m128i x0, x1, x2, x3, x4, x5, x6, x7, y0, y1, y2, y3, y4, y5, y6, y7; const __m128i k_ZERO = _mm_setzero_si128(); { // Load unsigned bytes as signed words by subtracting by 128 as offset const __m128i k_128 = _mm_set1_epi16(128); y0 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (0 * 8))), k_ZERO), k_128); y1 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (1 * 8))), k_ZERO), k_128); y2 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (2 * 8))), k_ZERO), k_128); y3 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (3 * 8))), k_ZERO), k_128); y4 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (4 * 8))), k_ZERO), k_128); y5 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (5 * 8))), k_ZERO), k_128); y6 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (6 * 8))), k_ZERO), k_128); y7 = _mm_sub_epi16(_mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)(input + (7 * 8))), k_ZERO), k_128); } const __m128i c = _mm_set1_epi32(1 << 14); for(int32_t pass = 0; pass < 2; pass++){ { // Transpose __m128i a0, a1, a2, a3, a4, a5, a6, a7, b0, b1, b2, b3, b4, b5, b6, b7; b0 = _mm_unpacklo_epi16(y0, y4); // [ 00 40 01 41 02 42 03 43 ] b1 = _mm_unpackhi_epi16(y0, y4); // [ 04 44 05 45 06 46 07 47 ] b2 = _mm_unpacklo_epi16(y1, y5); // [ 10 50 11 51 12 52 13 53 ] b3 = _mm_unpackhi_epi16(y1, y5); // [ 14 54 15 55 16 56 17 57 ] b4 = _mm_unpacklo_epi16(y2, y6); // [ 20 60 21 61 22 62 23 63 ] b5 = _mm_unpackhi_epi16(y2, y6); // [ 24 64 25 65 26 66 27 67 ] b6 = _mm_unpacklo_epi16(y3, y7); // [ 30 70 31 71 32 72 33 73 ] b7 = _mm_unpackhi_epi16(y3, y7); // [ 34 74 35 75 36 76 37 77 ] a0 = _mm_unpacklo_epi16(b0, b4); // [ 00 20 40 60 01 21 41 61 ] a1 = _mm_unpackhi_epi16(b0, b4); // [ 02 22 42 62 03 23 43 63 ] a2 = _mm_unpacklo_epi16(b1, b5); // [ 04 24 44 64 05 25 45 65 ] a3 = _mm_unpackhi_epi16(b1, b5); // [ 06 26 46 66 07 27 47 67 ] a4 = _mm_unpacklo_epi16(b2, b6); // [ 10 30 50 70 11 31 51 71 ] a5 = _mm_unpackhi_epi16(b2, b6); // [ 12 32 52 72 13 33 53 73 ] a6 = _mm_unpacklo_epi16(b3, b7); // [ 14 34 54 74 15 35 55 75 ] a7 = _mm_unpackhi_epi16(b3, b7); // [ 16 36 56 76 17 37 57 77 ] x0 = _mm_unpacklo_epi16(a0, a4); // [ 00 10 20 30 40 50 60 70 ] x1 = _mm_unpackhi_epi16(a0, a4); // [ 01 11 21 31 41 51 61 71 ] x2 = _mm_unpacklo_epi16(a1, a5); // [ 02 12 22 32 42 52 62 72 ] x3 = _mm_unpackhi_epi16(a1, a5); // [ 03 13 23 33 43 53 63 73 ] x4 = _mm_unpacklo_epi16(a2, a6); // [ 04 14 24 34 44 54 64 74 ] x5 = _mm_unpackhi_epi16(a2, a6); // [ 05 15 25 35 45 55 65 75 ] x6 = _mm_unpacklo_epi16(a3, a7); // [ 06 16 26 36 46 56 66 76 ] x7 = _mm_unpackhi_epi16(a3, a7); // [ 07 17 27 37 47 57 67 77 ] } { // Transform __m128i t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10; t8 = _mm_adds_epi16(x0, x7); t9 = _mm_subs_epi16(x0, x7); t0 = _mm_adds_epi16(x1, x6); t7 = _mm_subs_epi16(x1, x6); t1 = _mm_adds_epi16(x2, x5); t6 = _mm_subs_epi16(x2, x5); t2 = _mm_adds_epi16(x3, x4); t5 = _mm_subs_epi16(x3, x4); t3 = _mm_adds_epi16(t8, t2); t4 = _mm_subs_epi16(t8, t2); t2 = _mm_adds_epi16(t0, t1); t8 = _mm_subs_epi16(t0, t1); t1 = _mm_adds_epi16(t7, t6); t0 = _mm_subs_epi16(t7, t6); y0 = _mm_adds_epi16(t3, t2); y4 = _mm_subs_epi16(t3, t2); const __m128i c13573 = _mm_set1_epi16(13573); const __m128i c21895 = _mm_set1_epi16(21895); const __m128i cNeg21895 = _mm_set1_epi16(-21895); const __m128i c23170 = _mm_set1_epi16(23170); const __m128i cNeg23170 = _mm_set1_epi16(-23170); const __m128i c6518 = _mm_set1_epi16(6518); y2 = _mm_mradds_epi16(t8, c13573, t4); t10 = _mm_mr_epi16(t4, c13573, c); y6 = _mm_subs_epi16(t10, t8); t6 = _mm_mradds_epi16(t0, c23170, t5); t7 = _mm_mradds_epi16(t0, cNeg23170, t5); t2 = _mm_mradds_epi16(t1, cNeg23170, t9); t3 = _mm_mradds_epi16(t1, c23170, t9); y1 = _mm_mradds_epi16(t6, c6518, t3); t9 = _mm_mr_epi16(t3, c6518, c); y7 = _mm_subs_epi16(t9, t6); y5 = _mm_mradds_epi16(t2, c21895, t7); y3 = _mm_mradds_epi16(t7, cNeg21895, t2); } } { // Post scale and store const __m128i k_B = _mm_set_epi16(7880, 7422, 6680, 5681, 6680, 7422, 7880, 5681); const __m128i k_C = _mm_set_epi16(7422, 6992, 6292, 5351, 6292, 6992, 7422, 5351); const __m128i k_D = _mm_set_epi16(6680, 6292, 5663, 4816, 5663, 6292, 6680, 4816); _mm_storeu_si128((__m128i *)(&output[0 * 8]), _mm_mradds_epi16(_mm_set_epi16(5681, 5351, 4816, 4095, 4816, 5351, 5681, 4095), y0, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[1 * 8]), _mm_mradds_epi16(k_B, y1, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[2 * 8]), _mm_mradds_epi16(k_C, y2, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[3 * 8]), _mm_mradds_epi16(k_D, y3, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[4 * 8]), _mm_mradds_epi16(_mm_set_epi16(5681, 5351, 4816, 4095, 4816, 5351, 5681, 4095), y4, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[5 * 8]), _mm_mradds_epi16(k_D, y5, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[6 * 8]), _mm_mradds_epi16(k_C, y6, k_ZERO)); _mm_storeu_si128((__m128i *)(&output[7 * 8]), _mm_mradds_epi16(k_B, y7, k_ZERO)); } } __declspec(dllexport) void __stdcall DCT2DFast(uint8_t *input, int16_t *output){ const int32_t CONST_BITS = 13; const int32_t ROW_BITS = 2; const int32_t SHIFT0 = CONST_BITS - ROW_BITS; const int32_t SHIFT0ADD = 1 << (SHIFT0 - 1); const int32_t SHIFT1 = ROW_BITS + 3; const int32_t SHIFT1ADD = 1 << (SHIFT1 - 1); const int32_t SHIFT2 = CONST_BITS + ROW_BITS + 3; const int32_t SHIFT2ADD = 1 << (SHIFT2 - 1); const __m128i rounder_11 = _mm_set1_epi32(SHIFT0ADD); const __m128i rounder_18 = _mm_set1_epi32(SHIFT2ADD + 16384); const __m128i rounder_5 = _mm_set1_epi16(SHIFT1ADD + 2); const __m128i FIX_1 = _mm_set_epi16(4433, 10703, 4433, 10703, 4433, 10703, 4433, 10703); const __m128i FIX_2 = _mm_set_epi16(-10704, 4433, -10704, 4433, -10704, 4433, -10704, 4433); const __m128i FIX_3a = _mm_set_epi16(2260, 6437, 2260, 6437, 2260, 6437, 2260, 6437); const __m128i FIX_3b = _mm_set_epi16(9633, 11363, 9633, 11363, 9633, 11363, 9633, 11363); const __m128i FIX_4a = _mm_set_epi16(-6436, -11362, -6436, -11362, -6436, -11362, -6436, -11362); const __m128i FIX_4b = _mm_set_epi16(-2259, 9633, -2259, 9633, -2259, 9633, -2259, 9633); const __m128i FIX_5a = _mm_set_epi16(9633, 2261, 9633, 2261, 9633, 2261, 9633, 2261); const __m128i FIX_5b = _mm_set_epi16(-11362, 6437, -11362, 6437, -11362, 6437, -11362, 6437); const __m128i FIX_6a = _mm_set_epi16(-11363, 9633, -11363, 9633, -11363, 9633, -11363, 9633); const __m128i FIX_6b = _mm_set_epi16(-6436, 2260, -6436, 2260, -6436, 2260, -6436, 2260); const __m128i k_128 = _mm_set1_epi16(128); __m128i data[8]; __m128i buffer[8]; __asm { push eax push edx lea eax,dword ptr [data] mov edx,dword ptr [input] // Load unsigned bytes as signed words by subtracting by 128 as offset pxor xmm7,xmm7 movdqa xmm6,xmmword ptr [k_128] movq xmm0,qword ptr [edx+0] movq xmm1,qword ptr [edx+8] movq xmm2,qword ptr [edx+16] movq xmm3,qword ptr [edx+24] movq xmm4,qword ptr [edx+32] movq xmm5,qword ptr [edx+40] punpcklbw xmm0,xmm7 punpcklbw xmm1,xmm7 punpcklbw xmm2,xmm7 punpcklbw xmm3,xmm7 punpcklbw xmm4,xmm7 punpcklbw xmm5,xmm7 psubw xmm0,xmm6 psubw xmm1,xmm6 psubw xmm2,xmm6 psubw xmm3,xmm6 psubw xmm4,xmm6 psubw xmm5,xmm6 movdqa xmmword ptr [eax+0],xmm0 movdqa xmmword ptr [eax+16],xmm1 movq xmm0,qword ptr [edx+48] movq xmm1,qword ptr [edx+56] punpcklbw xmm0,xmm7 punpcklbw xmm1,xmm7 psubw xmm0,xmm6 psubw xmm1,xmm6 movdqa xmmword ptr [eax+32],xmm2 movdqa xmmword ptr [eax+48],xmm3 movdqa xmmword ptr [eax+64],xmm4 movdqa xmmword ptr [eax+80],xmm5 movdqa xmmword ptr [eax+96],xmm0 movdqa xmmword ptr [eax+112],xmm1 lea edx,dword ptr [buffer] prefetchnta [FIX_1] prefetchnta [FIX_3a] prefetchnta [FIX_5a] // First we transpose last 4 rows movdqa xmm0,xmmword ptr [eax+0*16] // 07 06 05 04 03 02 01 00 movdqa xmm6,xmmword ptr [eax+2*16] // 27 26 25 24 23 22 21 20 movdqa xmm4,xmmword ptr [eax+4*16] // 47 46 45 44 43 42 41 40 movdqa xmm7,xmmword ptr [eax+6*16] // 67 66 65 64 63 62 61 60 punpckhwd xmm0,xmmword ptr [eax+1*16] movdqa xmm2,xmm0 punpckhwd xmm6,xmmword ptr [eax+3*16] punpckhwd xmm4,xmmword ptr [eax+5*16] movdqa xmm5,xmm4 punpckhwd xmm7,xmmword ptr [eax+7*16] punpckldq xmm0,xmm6 // 31 21 11 01 30 20 10 00 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 // 71 61 51 41 70 60 50 40 punpckhdq xmm2,xmm6 // 33 23 13 03 32 22 12 02 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 // 73 63 53 43 72 62 52 42 punpcklqdq xmm0,xmm4 // 70 60 50 40 30 20 10 00 punpcklqdq xmm2,xmm5 // 72 62 52 42 32 22 21 02 punpckhqdq xmm1,xmm4 // 71 61 51 41 31 21 11 01 punpckhqdq xmm3,xmm5 // 73 63 53 43 33 23 13 03 movdqa xmmword ptr [edx+4*16],xmm0 movdqa xmmword ptr [edx+5*16],xmm1 movdqa xmmword ptr [edx+6*16],xmm2 movdqa xmmword ptr [edx+7*16],xmm3 // Then we transpose first 4 rows movdqa xmm0,xmmword ptr [eax+0*16] // 07 06 05 04 03 02 01 00 movdqa xmm6,xmmword ptr [eax+2*16] // 27 26 25 24 23 22 21 20 movdqa xmm4,xmmword ptr [eax+4*16] // 47 46 45 44 43 42 41 40 movdqa xmm7,xmmword ptr [eax+6*16] // 67 66 65 64 63 62 61 60 punpcklwd xmm0,xmmword ptr [eax+1*16] // 13 03 12 02 11 01 10 00 movdqa xmm2,xmm0 punpcklwd xmm6,xmmword ptr [eax+3*16] // 33 23 32 22 31 21 30 20 punpcklwd xmm4,xmmword ptr [eax+5*16] // 53 43 52 42 51 41 50 40 movdqa xmm5,xmm4 punpcklwd xmm7,xmmword ptr [eax+7*16] // 73 63 72 62 71 61 70 60 punpckldq xmm0,xmm6 // 31 21 11 01 30 20 10 00 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 // 71 61 51 41 70 60 50 40 punpckhdq xmm2,xmm6 // 33 23 13 03 32 22 12 02 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 // 73 63 53 43 72 62 52 42 punpcklqdq xmm0,xmm4 // 70 60 50 40 30 20 10 00 punpcklqdq xmm2,xmm5 // 72 62 52 42 32 22 21 02 punpckhqdq xmm1,xmm4 // 71 61 51 41 31 21 11 01 punpckhqdq xmm3,xmm5 // 73 63 53 43 33 23 13 03 movdqa xmmword ptr [edx+0*16],xmm0 movdqa xmmword ptr [edx+1*16],xmm1 movdqa xmmword ptr [edx+2*16],xmm2 movdqa xmmword ptr [edx+3*16],xmm3 // DCT 1D paddsw xmm0,xmmword ptr [edx+16*7] // tmp0 movdqa xmm4,xmm0 paddsw xmm1,xmmword ptr [edx+16*6] // tmp1 movdqa xmm5,xmm1 paddsw xmm2,xmmword ptr [edx+16*5] // tmp2 paddsw xmm3,xmmword ptr [edx+16*4] // tmp3 paddsw xmm0,xmm3 // tmp10 movdqa xmm6,xmm0 // tmp10 paddsw xmm1,xmm2 // tmp11 psubsw xmm4,xmm3 // tmp13 psubsw xmm5,xmm2 // tmp12 paddsw xmm0,xmm1 psubsw xmm6,xmm1 psllw xmm0,2 psllw xmm6,2 movdqa xmm1,xmm4 movdqa xmm2,xmm4 movdqa xmmword ptr [eax+16*0],xmm0 movdqa xmmword ptr [eax+16*4],xmm6 movdqa xmm7,xmmword ptr [FIX_1] punpckhwd xmm1,xmm5 // 12 13 12 13 12 13 12 13 high part movdqa xmm6,xmm1 // high punpcklwd xmm2,xmm5 // 12 13 12 13 12 13 12 13 low part movdqa xmm0,xmm2 // low movdqa xmm4,xmmword ptr [FIX_2] movdqa xmm5,xmmword ptr [rounder_11] pmaddwd xmm2,xmm7 // [FIX_1] pmaddwd xmm1,xmm7 // [FIX_1] pmaddwd xmm0,xmm4 // [FIX_2] pmaddwd xmm6,xmm4 // [FIX_2] paddd xmm2,xmm5 // rounder paddd xmm1,xmm5 // rounder psrad xmm2,11 psrad xmm1,11 packssdw xmm2,xmm1 movdqa xmmword ptr [eax+16*2],xmm2 paddd xmm0,xmm5 // rounder paddd xmm6,xmm5 // rounder psrad xmm0,11 psrad xmm6,11 packssdw xmm0,xmm6 movdqa xmmword ptr [eax+16*6],xmm0 movdqa xmm0,xmmword ptr [edx+16*0] movdqa xmm1,xmmword ptr [edx+16*1] movdqa xmm2,xmmword ptr [edx+16*2] movdqa xmm3,xmmword ptr [edx+16*3] psubsw xmm0,xmmword ptr [edx+16*7] // tmp7 movdqa xmm4,xmm0 psubsw xmm1,xmmword ptr [edx+16*6] // tmp6 psubsw xmm2,xmmword ptr [edx+16*5] // tmp5 movdqa xmm6,xmm2 psubsw xmm3,xmmword ptr [edx+16*4] // tmp4 punpckhwd xmm4,xmm1 // 6 7 6 7 6 7 6 7 high part punpcklwd xmm0,xmm1 // 6 7 6 7 6 7 6 7 low part punpckhwd xmm6,xmm3 // 4 5 4 5 4 5 4 5 high part punpcklwd xmm2,xmm3 // 4 5 4 5 4 5 4 5 low part movdqa xmm1,xmmword ptr [FIX_3a] movdqa xmm5,xmmword ptr [FIX_3b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_11] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+16*1],xmm1 movdqa xmm1,xmmword ptr [FIX_4a] movdqa xmm5,xmmword ptr [FIX_4b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_11] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+16*3],xmm1 movdqa xmm1,xmmword ptr [FIX_5a] movdqa xmm5,xmmword ptr [FIX_5b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_11] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,11 psrad xmm3,11 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+16*5],xmm1 pmaddwd xmm2,xmmword ptr [FIX_6a] pmaddwd xmm0,xmmword ptr [FIX_6b] paddd xmm2,xmm0 pmaddwd xmm6,xmmword ptr [FIX_6a] pmaddwd xmm4,xmmword ptr [FIX_6b] paddd xmm6,xmm4 paddd xmm2,xmm5 // rounder paddd xmm6,xmm5 // rounder psrad xmm2,11 psrad xmm6,11 packssdw xmm2,xmm6 movdqa xmmword ptr [eax+16*7],xmm2 // First we transpose last 4 rows movdqa xmm0,xmmword ptr [eax+0*16] // 07 06 05 04 03 02 01 00 movdqa xmm6,xmmword ptr [eax+2*16] // 27 26 25 24 23 22 21 20 movdqa xmm4,xmmword ptr [eax+4*16] // 47 46 45 44 43 42 41 40 movdqa xmm7,xmmword ptr [eax+6*16] // 67 66 65 64 63 62 61 60 punpckhwd xmm0,xmmword ptr [eax+1*16] movdqa xmm2,xmm0 punpckhwd xmm6,xmmword ptr [eax+3*16] punpckhwd xmm4,xmmword ptr [eax+5*16] movdqa xmm5,xmm4 punpckhwd xmm7,xmmword ptr [eax+7*16] punpckldq xmm0,xmm6 // 31 21 11 01 30 20 10 00 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 // 71 61 51 41 70 60 50 40 punpckhdq xmm2,xmm6 // 33 23 13 03 32 22 12 02 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 // 73 63 53 43 72 62 52 42 punpcklqdq xmm0,xmm4 // 70 60 50 40 30 20 10 00 punpcklqdq xmm2,xmm5 // 72 62 52 42 32 22 21 02 punpckhqdq xmm1,xmm4 // 71 61 51 41 31 21 11 01 punpckhqdq xmm3,xmm5 // 73 63 53 43 33 23 13 03 movdqa xmmword ptr [edx+4*16],xmm0 movdqa xmmword ptr [edx+5*16],xmm1 movdqa xmmword ptr [edx+6*16],xmm2 movdqa xmmword ptr [edx+7*16],xmm3 // Then we transpose first 4 rows movdqa xmm0,xmmword ptr [eax+0*16] // 07 06 05 04 03 02 01 00 movdqa xmm6,xmmword ptr [eax+2*16] // 27 26 25 24 23 22 21 20 movdqa xmm4,xmmword ptr [eax+4*16] // 47 46 45 44 43 42 41 40 movdqa xmm7,xmmword ptr [eax+6*16] // 67 66 65 64 63 62 61 60 punpcklwd xmm0,xmmword ptr [eax+1*16] // 13 03 12 02 11 01 10 00 movdqa xmm2,xmm0 punpcklwd xmm6,xmmword ptr [eax+3*16] // 33 23 32 22 31 21 30 20 punpcklwd xmm4,xmmword ptr [eax+5*16] // 53 43 52 42 51 41 50 40 movdqa xmm5,xmm4 punpcklwd xmm7,xmmword ptr [eax+7*16] // 73 63 72 62 71 61 70 60 punpckldq xmm0,xmm6 // 31 21 11 01 30 20 10 00 movdqa xmm1,xmm0 punpckldq xmm4,xmm7 // 71 61 51 41 70 60 50 40 punpckhdq xmm2,xmm6 // 33 23 13 03 32 22 12 02 movdqa xmm3,xmm2 punpckhdq xmm5,xmm7 // 73 63 53 43 72 62 52 42 punpcklqdq xmm0,xmm4 // 70 60 50 40 30 20 10 00 punpcklqdq xmm2,xmm5 // 72 62 52 42 32 22 21 02 punpckhqdq xmm1,xmm4 // 71 61 51 41 31 21 11 01 punpckhqdq xmm3,xmm5 // 73 63 53 43 33 23 13 03 movdqa xmmword ptr [edx+0*16],xmm0 movdqa xmmword ptr [edx+1*16],xmm1 movdqa xmmword ptr [edx+2*16],xmm2 movdqa xmmword ptr [edx+3*16],xmm3 movdqa xmm7,xmmword ptr [rounder_5] paddsw xmm0,xmmword ptr [edx+16*7] //tmp0 movdqa xmm4,xmm0 paddsw xmm1,xmmword ptr [edx+16*6] // tmp1 movdqa xmm5,xmm1 paddsw xmm2,xmmword ptr [edx+16*5] // tmp2 paddsw xmm3,xmmword ptr [edx+16*4] // tmp3 paddsw xmm0,xmm3 // tmp10 // In the second pass we must round and shift before // the tmp10+tmp11 and tmp10-tmp11 calculation // or the overflow will happen. paddsw xmm0,xmm7 // [rounder_5] psraw xmm0,5 movdqa xmm6,xmm0 // tmp10 paddsw xmm1,xmm2 // tmp11 psubsw xmm4,xmm3 // tmp13 psubsw xmm5,xmm2 // tmp12 paddsw xmm1,xmm7 // [rounder_5] psraw xmm1,5 paddsw xmm0,xmm1 psubsw xmm6,xmm1 movdqa xmm1,xmm4 movdqa xmm2,xmm4 movdqa xmmword ptr [eax+16*0],xmm0 movdqa xmmword ptr [eax+16*4],xmm6 movdqa xmm7,xmmword ptr [FIX_1] punpckhwd xmm1,xmm5 // 12 13 12 13 12 13 12 13 high part movdqa xmm6,xmm1 // high punpcklwd xmm2,xmm5 // 12 13 12 13 12 13 12 13 low part movdqa xmm0,xmm2 // low movdqa xmm4,xmmword ptr [FIX_2] movdqa xmm5,xmmword ptr [rounder_18] pmaddwd xmm2,xmm7 // [FIX_1] pmaddwd xmm1,xmm7 // [FIX_1] pmaddwd xmm0,xmm4 // [FIX_2] pmaddwd xmm6,xmm4 // [FIX_2] paddd xmm2,xmm5 // rounder paddd xmm1,xmm5 // rounder psrad xmm2,18 psrad xmm1,18 packssdw xmm2,xmm1 movdqa xmmword ptr [eax+16*2],xmm2 paddd xmm0,xmm5 // rounder paddd xmm6,xmm5 // rounder psrad xmm0,18 psrad xmm6,18 packssdw xmm0,xmm6 movdqa xmmword ptr [eax+16*6],xmm0 movdqa xmm0,xmmword ptr [edx+16*0] movdqa xmm1,xmmword ptr [edx+16*1] movdqa xmm2,xmmword ptr [edx+16*2] movdqa xmm3,xmmword ptr [edx+16*3] psubsw xmm0,xmmword ptr [edx+16*7] // tmp7 movdqa xmm4,xmm0 psubsw xmm1,xmmword ptr [edx+16*6] // tmp6 psubsw xmm2,xmmword ptr [edx+16*5] // tmp5 movdqa xmm6,xmm2 psubsw xmm3,xmmword ptr [edx+16*4] // tmp4 punpckhwd xmm4,xmm1 // 6 7 6 7 6 7 6 7 high part punpcklwd xmm0,xmm1 // 6 7 6 7 6 7 6 7 low part punpckhwd xmm6,xmm3 // 4 5 4 5 4 5 4 5 high part punpcklwd xmm2,xmm3 // 4 5 4 5 4 5 4 5 low part movdqa xmm1,xmmword ptr [FIX_3a] movdqa xmm5,xmmword ptr [FIX_3b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_18] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+16],xmm1 movdqa xmm1,xmmword ptr [FIX_4a] movdqa xmm5,xmmword ptr [FIX_4b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_18] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+48],xmm1 movdqa xmm1,xmmword ptr [FIX_5a] movdqa xmm5,xmmword ptr [FIX_5b] movdqa xmm3,xmm1 movdqa xmm7,xmm5 pmaddwd xmm1,xmm2 pmaddwd xmm5,xmm0 paddd xmm1,xmm5 movdqa xmm5,xmmword ptr [rounder_18] pmaddwd xmm3,xmm6 pmaddwd xmm7,xmm4 paddd xmm3,xmm7 paddd xmm1,xmm5 paddd xmm3,xmm5 psrad xmm1,18 psrad xmm3,18 packssdw xmm1,xmm3 movdqa xmmword ptr [eax+80],xmm1 pmaddwd xmm2,xmmword ptr [FIX_6a] pmaddwd xmm0,xmmword ptr [FIX_6b] paddd xmm2,xmm0 pmaddwd xmm6,xmmword ptr [FIX_6a] pmaddwd xmm4,xmmword ptr [FIX_6b] paddd xmm6,xmm4 paddd xmm2,xmm5 // rounder paddd xmm6,xmm5 // rounder psrad xmm2,18 psrad xmm6,18 packssdw xmm2,xmm6 movdqa xmmword ptr [eax+112],xmm2 // Store result mov edx,dword ptr [output] movdqa xmm0,xmmword ptr [eax+0] movdqa xmm1,xmmword ptr [eax+16] movdqa xmm2,xmmword ptr [eax+32] movdqa xmm3,xmmword ptr [eax+48] movdqa xmm4,xmmword ptr [eax+64] movdqa xmm5,xmmword ptr [eax+80] movdqa xmm6,xmmword ptr [eax+96] movdqa xmm7,xmmword ptr [eax+112] movdqu xmmword ptr [edx+0],xmm0 movdqu xmmword ptr [edx+16],xmm1 movdqu xmmword ptr [edx+32],xmm2 movdqu xmmword ptr [edx+48],xmm3 movdqu xmmword ptr [edx+64],xmm4 movdqu xmmword ptr [edx+80],xmm5 movdqu xmmword ptr [edx+96],xmm6 movdqu xmmword ptr [edx+112],xmm7 pop edx pop eax } } // and for Delphi 7: inline __m128i _mm_mr_epi16(__m128i x, __m128i y, __m128i c) { __m128i h = _mm_mulhi_epi16(x, y), l = _mm_mullo_epi16(x, y); return _mm_packs_epi32( _mm_srai_epi32( _mm_slli_epi32((_mm_srai_epi32(_mm_add_epi32(_mm_unpacklo_epi16(l, h), c), 15), 16), 16), _mm_srai_epi32( _mm_slli_epi32(_mm_srai_epi32(_mm_add_epi32(_mm_unpackhi_epi16(l, h), c), 15), 16), 16) ) } #define _mm_mradds_epi16(x, y, z) _mm_adds_epi16(_mm_mr_epi16(x, y, *((__m128i*)(&c))), z) __declspec(dllexport) void __stdcall dct_vector(uint8_t *input, int16_t *output) { static int16_t PostScaleArray[64] = { 4095, 5681, 5351, 4816, 4095, 4816, 5351, 5681, 5681, 7880, 7422, 6680, 5681, 6680, 7422, 7880, 5351, 7422, 6992, 6292, 5351, 6292, 6992, 7422, 4816, 6680, 6292, 5663, 4816, 5663, 6292, 6680, 4095, 5681, 5351, 4816, 4095, 4816, 5351, 5681, 4816, 6680, 6292, 5663, 4816, 5663, 6292, 6680, 5351, 7422, 6992, 6292, 5351, 6292, 6992, 7422, 5681, 7880, 7422, 6680, 5681, 6680, 7422, 7880 }; __m128i t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10; __m128i a0, a1, a2, a3, a4, a5, a6, a7; __m128i b0, b1, b2, b3, b4, b5, b6, b7; volatile __m128i c13573 = _mm_set1_epi16(13573); volatile __m128i c21895 = _mm_set1_epi16(21895); volatile __m128i cNeg21895 = _mm_set1_epi16(-21895); volatile __m128i c23170 = _mm_set1_epi16(23170); volatile __m128i cNeg23170 = _mm_set1_epi16(-23170); volatile __m128i c6518 = _mm_set1_epi16(6518); volatile __m128i c = _mm_set1_epi32(1 << 14); __m128i vx[8], vy[8]; const __m128i k__ZERO = _mm_setzero_si128(); volatile __m128i k__128 = _mm_set1_epi16(128); __m128i in0 = _mm_loadl_epi64((const __m128i *)(input + (0 * 8))); __m128i in1 = _mm_loadl_epi64((const __m128i *)(input + (1 * 8))); __m128i in2 = _mm_loadl_epi64((const __m128i *)(input + (2 * 8))); __m128i in3 = _mm_loadl_epi64((const __m128i *)(input + (3 * 8))); __m128i in4 = _mm_loadl_epi64((const __m128i *)(input + (4 * 8))); __m128i in5 = _mm_loadl_epi64((const __m128i *)(input + (5 * 8))); __m128i in6 = _mm_loadl_epi64((const __m128i *)(input + (6 * 8))); __m128i in7 = _mm_loadl_epi64((const __m128i *)(input + (7 * 8))); // Convert bytes to words in0 = _mm_unpacklo_epi8(in0, k__ZERO); in1 = _mm_unpacklo_epi8(in1, k__ZERO); in2 = _mm_unpacklo_epi8(in2, k__ZERO); in3 = _mm_unpacklo_epi8(in3, k__ZERO); in4 = _mm_unpacklo_epi8(in4, k__ZERO); in5 = _mm_unpacklo_epi8(in5, k__ZERO); in6 = _mm_unpacklo_epi8(in6, k__ZERO); in7 = _mm_unpacklo_epi8(in7, k__ZERO); // Convert unsigned words to signed words (subtracting by 128) vy[0] = _mm_sub_epi16(in0, *((__m128i*)(&k__128))); vy[1] = _mm_sub_epi16(in1, *((__m128i*)(&k__128))); vy[2] = _mm_sub_epi16(in2, *((__m128i*)(&k__128))); vy[3] = _mm_sub_epi16(in3, *((__m128i*)(&k__128))); vy[4] = _mm_sub_epi16(in4, *((__m128i*)(&k__128))); vy[5] = _mm_sub_epi16(in5, *((__m128i*)(&k__128))); vy[6] = _mm_sub_epi16(in6, *((__m128i*)(&k__128))); vy[7] = _mm_sub_epi16(in7, *((__m128i*)(&k__128))); { // Transpose b0 = _mm_unpacklo_epi16(vy[0], vy[4]); /* [ 00 40 01 41 02 42 03 43 ]*/ b1 = _mm_unpackhi_epi16(vy[0], vy[4]); /* [ 04 44 05 45 06 46 07 47 ]*/ b2 = _mm_unpacklo_epi16(vy[1], vy[5]); /* [ 10 50 11 51 12 52 13 53 ]*/ b3 = _mm_unpackhi_epi16(vy[1], vy[5]); /* [ 14 54 15 55 16 56 17 57 ]*/ b4 = _mm_unpacklo_epi16(vy[2], vy[6]); /* [ 20 60 21 61 22 62 23 63 ]*/ b5 = _mm_unpackhi_epi16(vy[2], vy[6]); /* [ 24 64 25 65 26 66 27 67 ]*/ b6 = _mm_unpacklo_epi16(vy[3], vy[7]); /* [ 30 70 31 71 32 72 33 73 ]*/ b7 = _mm_unpackhi_epi16(vy[3], vy[7]); /* [ 34 74 35 75 36 76 37 77 ]*/ a0 = _mm_unpacklo_epi16(b0, b4); /* [ 00 20 40 60 01 21 41 61 ]*/ a1 = _mm_unpackhi_epi16(b0, b4); /* [ 02 22 42 62 03 23 43 63 ]*/ a2 = _mm_unpacklo_epi16(b1, b5); /* [ 04 24 44 64 05 25 45 65 ]*/ a3 = _mm_unpackhi_epi16(b1, b5); /* [ 06 26 46 66 07 27 47 67 ]*/ a4 = _mm_unpacklo_epi16(b2, b6); /* [ 10 30 50 70 11 31 51 71 ]*/ a5 = _mm_unpackhi_epi16(b2, b6); /* [ 12 32 52 72 13 33 53 73 ]*/ a6 = _mm_unpacklo_epi16(b3, b7); /* [ 14 34 54 74 15 35 55 75 ]*/ a7 = _mm_unpackhi_epi16(b3, b7); /* [ 16 36 56 76 17 37 57 77 ]*/ vx[0] = _mm_unpacklo_epi16(a0, a4); /* [ 00 10 20 30 40 50 60 70 ]*/ vx[1] = _mm_unpackhi_epi16(a0, a4); /* [ 01 11 21 31 41 51 61 71 ]*/ vx[2] = _mm_unpacklo_epi16(a1, a5); /* [ 02 12 22 32 42 52 62 72 ]*/ vx[3] = _mm_unpackhi_epi16(a1, a5); /* [ 03 13 23 33 43 53 63 73 ]*/ vx[4] = _mm_unpacklo_epi16(a2, a6); /* [ 04 14 24 34 44 54 64 74 ]*/ vx[5] = _mm_unpackhi_epi16(a2, a6); /* [ 05 15 25 35 45 55 65 75 ]*/ vx[6] = _mm_unpacklo_epi16(a3, a7); /* [ 06 16 26 36 46 56 66 76 ]*/ vx[7] = _mm_unpackhi_epi16(a3, a7); /* [ 07 17 27 37 47 57 67 77 ]*/ } { // Transform t8 = _mm_adds_epi16(vx[0], vx[7]); t9 = _mm_subs_epi16(vx[0], vx[7]); t0 = _mm_adds_epi16(vx[1], vx[6]); t7 = _mm_subs_epi16(vx[1], vx[6]); t1 = _mm_adds_epi16(vx[2], vx[5]); t6 = _mm_subs_epi16(vx[2], vx[5]); t2 = _mm_adds_epi16(vx[3], vx[4]); t5 = _mm_subs_epi16(vx[3], vx[4]); t3 = _mm_adds_epi16(t8, t2); t4 = _mm_subs_epi16(t8, t2); t2 = _mm_adds_epi16(t0, t1); t8 = _mm_subs_epi16(t0, t1); t1 = _mm_adds_epi16(t7, t6); t0 = _mm_subs_epi16(t7, t6); vy[0] = _mm_adds_epi16(t3, t2); vy[4] = _mm_subs_epi16(t3, t2); vy[2] = _mm_mradds_epi16(t8, *((__m128i*)(&c13573)), t4); t10 = _mm_mr_epi16(t4, *((__m128i*)(&c13573)), *((__m128i*)(&c))); vy[6] = _mm_subs_epi16(t10, t8); t6 = _mm_mradds_epi16(t0, *((__m128i*)(&c23170)), t5); t7 = _mm_mradds_epi16(t0, *((__m128i*)(&cNeg23170)), t5); t2 = _mm_mradds_epi16(t1, *((__m128i*)(&cNeg23170)), t9); t3 = _mm_mradds_epi16(t1, *((__m128i*)(&c23170)), t9); vy[1] = _mm_mradds_epi16(t6, *((__m128i*)(&c6518)), t3); t9 = _mm_mr_epi16(t3, *((__m128i*)(&c6518)), *((__m128i*)(&c))); vy[7] = _mm_subs_epi16(t9, t6); vy[5] = _mm_mradds_epi16(t2, *((__m128i*)(&c21895)), t7); vy[3] = _mm_mradds_epi16(t7, *((__m128i*)(&cNeg21895)), t2); } { // Transpose b0 = _mm_unpacklo_epi16(vy[0], vy[4]); /* [ 00 40 01 41 02 42 03 43 ]*/ b1 = _mm_unpackhi_epi16(vy[0], vy[4]); /* [ 04 44 05 45 06 46 07 47 ]*/ b2 = _mm_unpacklo_epi16(vy[1], vy[5]); /* [ 10 50 11 51 12 52 13 53 ]*/ b3 = _mm_unpackhi_epi16(vy[1], vy[5]); /* [ 14 54 15 55 16 56 17 57 ]*/ b4 = _mm_unpacklo_epi16(vy[2], vy[6]); /* [ 20 60 21 61 22 62 23 63 ]*/ b5 = _mm_unpackhi_epi16(vy[2], vy[6]); /* [ 24 64 25 65 26 66 27 67 ]*/ b6 = _mm_unpacklo_epi16(vy[3], vy[7]); /* [ 30 70 31 71 32 72 33 73 ]*/ b7 = _mm_unpackhi_epi16(vy[3], vy[7]); /* [ 34 74 35 75 36 76 37 77 ]*/ a0 = _mm_unpacklo_epi16(b0, b4); /* [ 00 20 40 60 01 21 41 61 ]*/ a1 = _mm_unpackhi_epi16(b0, b4); /* [ 02 22 42 62 03 23 43 63 ]*/ a2 = _mm_unpacklo_epi16(b1, b5); /* [ 04 24 44 64 05 25 45 65 ]*/ a3 = _mm_unpackhi_epi16(b1, b5); /* [ 06 26 46 66 07 27 47 67 ]*/ a4 = _mm_unpacklo_epi16(b2, b6); /* [ 10 30 50 70 11 31 51 71 ]*/ a5 = _mm_unpackhi_epi16(b2, b6); /* [ 12 32 52 72 13 33 53 73 ]*/ a6 = _mm_unpacklo_epi16(b3, b7); /* [ 14 34 54 74 15 35 55 75 ]*/ a7 = _mm_unpackhi_epi16(b3, b7); /* [ 16 36 56 76 17 37 57 77 ]*/ vx[0] = _mm_unpacklo_epi16(a0, a4); /* [ 00 10 20 30 40 50 60 70 ]*/ vx[1] = _mm_unpackhi_epi16(a0, a4); /* [ 01 11 21 31 41 51 61 71 ]*/ vx[2] = _mm_unpacklo_epi16(a1, a5); /* [ 02 12 22 32 42 52 62 72 ]*/ vx[3] = _mm_unpackhi_epi16(a1, a5); /* [ 03 13 23 33 43 53 63 73 ]*/ vx[4] = _mm_unpacklo_epi16(a2, a6); /* [ 04 14 24 34 44 54 64 74 ]*/ vx[5] = _mm_unpackhi_epi16(a2, a6); /* [ 05 15 25 35 45 55 65 75 ]*/ vx[6] = _mm_unpacklo_epi16(a3, a7); /* [ 06 16 26 36 46 56 66 76 ]*/ vx[7] = _mm_unpackhi_epi16(a3, a7); /* [ 07 17 27 37 47 57 67 77 ]*/ } { // Transform t8 = _mm_adds_epi16(vx[0], vx[7]); t9 = _mm_subs_epi16(vx[0], vx[7]); t0 = _mm_adds_epi16(vx[1], vx[6]); t7 = _mm_subs_epi16(vx[1], vx[6]); t1 = _mm_adds_epi16(vx[2], vx[5]); t6 = _mm_subs_epi16(vx[2], vx[5]); t2 = _mm_adds_epi16(vx[3], vx[4]); t5 = _mm_subs_epi16(vx[3], vx[4]); t3 = _mm_adds_epi16(t8, t2); t4 = _mm_subs_epi16(t8, t2); t2 = _mm_adds_epi16(t0, t1); t8 = _mm_subs_epi16(t0, t1); t1 = _mm_adds_epi16(t7, t6); t0 = _mm_subs_epi16(t7, t6); vy[0] = _mm_adds_epi16(t3, t2); vy[4] = _mm_subs_epi16(t3, t2); vy[2] = _mm_mradds_epi16(t8, *((__m128i*)(&c13573)), t4); t10 = _mm_mr_epi16(t4, *((__m128i*)(&c13573)), *((__m128i*)(&c))); vy[6] = _mm_subs_epi16(t10, t8); t6 = _mm_mradds_epi16(t0, *((__m128i*)(&c23170)), t5); t7 = _mm_mradds_epi16(t0, *((__m128i*)(&cNeg23170)), t5); t2 = _mm_mradds_epi16(t1, *((__m128i*)(&cNeg23170)), t9); t3 = _mm_mradds_epi16(t1, *((__m128i*)(&c23170)), t9); vy[1] = _mm_mradds_epi16(t6, *((__m128i*)(&c6518)), t3); t9 = _mm_mr_epi16(t3, *((__m128i*)(&c6518)), *((__m128i*)(&c))); vy[7] = _mm_subs_epi16(t9, t6); vy[5] = _mm_mradds_epi16(t2, *((__m128i*)(&c21895)), t7); vy[3] = _mm_mradds_epi16(t7, *((__m128i*)(&cNeg21895)), t2); } { volatile __m128i *PostScalev = (__m128i*)&PostScaleArray; __m128i *v = (__m128i*) output; { static const int32_t i = 0; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 1; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 2; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 3; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 4; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 5; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 6; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } { static const int32_t i = 7; __m128i t = _mm_loadu_si128((const __m128i *)(&PostScalev[i])); _mm_storeu_si128((__m128i *)(&v[i]), _mm_mradds_epi16(t, vy[i], _mm_set1_epi16(0))); } } } {$ifend} procedure LoadTurboJPEG; begin TurboJpegLibrary:=LoadLibrary({$ifdef Windows}{$ifdef cpu386}'turbojpeg32.dll'{$else}'turbojpeg64.dll'{$endif}{$else}'turbojpeg.so'{$endif}); if TurboJpegLibrary<>NilLibHandle then begin tjInitCompress:=GetProcAddress(TurboJpegLibrary,'tjInitCompress'); tjInitDecompress:=GetProcAddress(TurboJpegLibrary,'tjInitDecompress'); tjDestroy:=GetProcAddress(TurboJpegLibrary,'tjDestroy'); tjAlloc:=GetProcAddress(TurboJpegLibrary,'tjAlloc'); tjFree:=GetProcAddress(TurboJpegLibrary,'tjFree'); tjCompress2:=GetProcAddress(TurboJpegLibrary,'tjCompress2'); tjDecompressHeader:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader'); tjDecompressHeader2:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader2'); tjDecompressHeader3:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader3'); tjDecompress2:=GetProcAddress(TurboJpegLibrary,'tjDecompress2'); end; end; procedure UnloadTurboJPEG; begin if TurboJpegLibrary<>NilLibHandle then begin FreeLibrary(TurboJpegLibrary); TurboJpegLibrary:=NilLibHandle; end; end; initialization LoadTurboJPEG; finalization UnloadTurboJPEG; end.