text stringlengths 14 6.51M |
|---|
{*******************************************************************************
Title: iTEC-SOFTWARE
Description: VO relational the table [TERMINAL]
The MIT License
Copyright: Copyright (C) 2010 www.itecsoftware.com.br
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, sub license, 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:
william@itecsoftware.com.br
@author William (william_mk@hotmail.com)
@version 1.0
*******************************************************************************}
unit TerminalVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils,
ImpressoraVO;
type
[TEntity]
[TTable('TERMINAL')]
TTerminalVO = class(TVO)
private
FID: Integer;
FID_CAIXA: Integer;
FID_IMPRESSORA: Integer;
FIDENTIFICADOR: String;
FTERMINAL_SOMENTE_PREVENDA: String;
FINFORMAR_ATENDENTE_PREVENDA: String;
FBALANCA: String;
FBALANCA_CONFIGURACAO: String;
FNFCE_EMITIR: String;
FNFCE_EMITIR_PERGUNTAR: String;
FNFCE_AUTO_VENDA_CARTAO: String;
FNFCE_PRINT: String;
FNFCE_PRINT_PERGUNTAR: String;
FNFCE_LOCAL_PRINT: String;
FMOVIMENTO_OPEN_PRINT: String;
FMOVIMENTO_OPEN_PRINT_PERGUNTAR: String;
FMOVIMENTO_CLOSE_PRINT: String;
FMOVIMENTO_CLOSE_PRINT_PERGUNTAR: String;
FSUPRIMENTO_PRINT: String;
FSUPRIMENTO_PRINT_PERGUNTAR: String;
FSANGRIA_PRINT: String;
FSANGRIA_PRINT_PERGUNTAR: String;
FVENDA_PRINT: String;
FVENDA_PRINT_PERGUNTAR: String;
FVENDA_ITEM_PRINT: String;
FDEBITO_CONTA_PRINT: String;
FDEBITO_CONTA_PRINT_PERGUNTAR: String;
FCREDITO_CONTA_PRINT: String;
FCREDITO_CONTA_PRINT_PERGUNTAR: String;
FFECHAMENTO_SANGRIA_PRINT: String;
FFECHAMENTO_DEBITO_CONTA_PRINT: String;
FFECHAMENTO_CREDITO_CONTA_PRINT: String;
FFECHAMENTO_CARTAO_PRINT: String;
FFECHAMENTO_PRODUTO_PRINT: String;
FFECHAMENTO_SUBGRUPO_PRINT: String;
FFECHAMENTO_PRODUTO_MODULO_PRINT: String;
FFECHAMENTO_ATENDENTE_PRINT: String;
FFECHAMENTO_DELIVERYMAN_PRINT: String;
FRECEBIMENTO01: Integer;
FRECEBIMENTO02: Integer;
FRECEBIMENTO03: Integer;
FRECEBIMENTO04: Integer;
FRECEBIMENTO05: Integer;
FIMAGEM_REPOSITORIO: String;
FCONSULTA: Integer;
FCOBRAR_SERVICO: String;
FSERVICO_OPCIONAL: String;
FINFORMAR_PESSOAS: String;
FLAYOUT: String;
FCAIXA_GAVETA: String;
FCONTROLA_MESAS: String;
FMOBILE_PREVENDA_FECHAMENTO: String;
FDELIVERYMAN_AFTER_RECEBER: String;
FIMPRESSORA: TImpressoraVO;
public
destructor Destroy; override;
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_CAIXA','Id Caixa',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdCaixa: Integer read FID_CAIXA write FID_CAIXA;
[TColumn('ID_IMPRESSORA','Id Impressora',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdImpressora: Integer read FID_IMPRESSORA write FID_IMPRESSORA;
[TColumn('IDENTIFICADOR','Identificador',256,[ldGrid, ldLookup, ldCombobox], False)]
property Identificador: String read FIDENTIFICADOR write FIDENTIFICADOR;
[TColumn('TERMINAL_SOMENTE_PREVENDA','Terminal Somente Prevenda',8,[ldGrid, ldLookup, ldCombobox], False)]
property TerminalSomentePrevenda: String read FTERMINAL_SOMENTE_PREVENDA write FTERMINAL_SOMENTE_PREVENDA;
[TColumn('INFORMAR_ATENDENTE_PREVENDA','Informar Atendente Prevenda',8,[ldGrid, ldLookup, ldCombobox], False)]
property InformarAtendentePrevenda: String read FINFORMAR_ATENDENTE_PREVENDA write FINFORMAR_ATENDENTE_PREVENDA;
[TColumn('BALANCA','Balanca',8,[ldGrid, ldLookup, ldCombobox], False)]
property Balanca: String read FBALANCA write FBALANCA;
[TColumn('BALANCA_CONFIGURACAO','Balanca Configuracao',160,[ldGrid, ldLookup, ldCombobox], False)]
property BalancaConfiguracao: String read FBALANCA_CONFIGURACAO write FBALANCA_CONFIGURACAO;
[TColumn('NFCE_EMITIR','Nfce Emitir',8,[ldGrid, ldLookup, ldCombobox], False)]
property NfceEmitir: String read FNFCE_EMITIR write FNFCE_EMITIR;
[TColumn('NFCE_EMITIR_PERGUNTAR','Nfce Emitir Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property NfceEmitirPerguntar: String read FNFCE_EMITIR_PERGUNTAR write FNFCE_EMITIR_PERGUNTAR;
[TColumn('NFCE_AUTO_VENDA_CARTAO','Nfce Auto Venda Cartao',8,[ldGrid, ldLookup, ldCombobox], False)]
property NfceAutoVendaCartao: String read FNFCE_AUTO_VENDA_CARTAO write FNFCE_AUTO_VENDA_CARTAO;
[TColumn('NFCE_PRINT','Nfce Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property NfcePrint: String read FNFCE_PRINT write FNFCE_PRINT;
[TColumn('NFCE_PRINT_PERGUNTAR','Nfce Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property NfcePrintPerguntar: String read FNFCE_PRINT_PERGUNTAR write FNFCE_PRINT_PERGUNTAR;
[TColumn('NFCE_LOCAL_PRINT','Nfce Local Print',160,[ldGrid, ldLookup, ldCombobox], False)]
property NfceLocalPrint: String read FNFCE_LOCAL_PRINT write FNFCE_LOCAL_PRINT;
[TColumn('MOVIMENTO_OPEN_PRINT','Movimento Open Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property MovimentoOpenPrint: String read FMOVIMENTO_OPEN_PRINT write FMOVIMENTO_OPEN_PRINT;
[TColumn('MOVIMENTO_OPEN_PRINT_PERGUNTAR','Movimento Open Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property MovimentoOpenPrintPerguntar: String read FMOVIMENTO_OPEN_PRINT_PERGUNTAR write FMOVIMENTO_OPEN_PRINT_PERGUNTAR;
[TColumn('MOVIMENTO_CLOSE_PRINT','Movimento Close Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property MovimentoClosePrint: String read FMOVIMENTO_CLOSE_PRINT write FMOVIMENTO_CLOSE_PRINT;
[TColumn('MOVIMENTO_CLOSE_PRINT_PERGUNTAR','Movimento Close Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property MovimentoClosePrintPerguntar: String read FMOVIMENTO_CLOSE_PRINT_PERGUNTAR write FMOVIMENTO_CLOSE_PRINT_PERGUNTAR;
[TColumn('SUPRIMENTO_PRINT','Suprimento Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property SuprimentoPrint: String read FSUPRIMENTO_PRINT write FSUPRIMENTO_PRINT;
[TColumn('SUPRIMENTO_PRINT_PERGUNTAR','Suprimento Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property SuprimentoPrintPerguntar: String read FSUPRIMENTO_PRINT_PERGUNTAR write FSUPRIMENTO_PRINT_PERGUNTAR;
[TColumn('SANGRIA_PRINT','Sangria Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property SangriaPrint: String read FSANGRIA_PRINT write FSANGRIA_PRINT;
[TColumn('SANGRIA_PRINT_PERGUNTAR','Sangria Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property SangriaPrintPerguntar: String read FSANGRIA_PRINT_PERGUNTAR write FSANGRIA_PRINT_PERGUNTAR;
[TColumn('VENDA_PRINT','Venda Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property VendaPrint: String read FVENDA_PRINT write FVENDA_PRINT;
[TColumn('VENDA_PRINT_PERGUNTAR','Venda Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property VendaPrintPerguntar: String read FVENDA_PRINT_PERGUNTAR write FVENDA_PRINT_PERGUNTAR;
[TColumn('VENDA_ITEM_PRINT','Venda Item Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property VendaItemPrint: String read FVENDA_ITEM_PRINT write FVENDA_ITEM_PRINT;
[TColumn('DEBITO_CONTA_PRINT','Debito Conta Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property DebitoContaPrint: String read FDEBITO_CONTA_PRINT write FDEBITO_CONTA_PRINT;
[TColumn('DEBITO_CONTA_PRINT_PERGUNTAR','Debito Conta Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property DebitoContaPrintPerguntar: String read FDEBITO_CONTA_PRINT_PERGUNTAR write FDEBITO_CONTA_PRINT_PERGUNTAR;
[TColumn('CREDITO_CONTA_PRINT','Credito Conta Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property CreditoContaPrint: String read FCREDITO_CONTA_PRINT write FCREDITO_CONTA_PRINT;
[TColumn('CREDITO_CONTA_PRINT_PERGUNTAR','Credito Conta Print Perguntar',8,[ldGrid, ldLookup, ldCombobox], False)]
property CreditoContaPrintPerguntar: String read FCREDITO_CONTA_PRINT_PERGUNTAR write FCREDITO_CONTA_PRINT_PERGUNTAR;
[TColumn('FECHAMENTO_SANGRIA_PRINT','Fechamento Sangria Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoSangriaPrint: String read FFECHAMENTO_SANGRIA_PRINT write FFECHAMENTO_SANGRIA_PRINT;
[TColumn('FECHAMENTO_DEBITO_CONTA_PRINT','Fechamento Debito Conta Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoDebitoContaPrint: String read FFECHAMENTO_DEBITO_CONTA_PRINT write FFECHAMENTO_DEBITO_CONTA_PRINT;
[TColumn('FECHAMENTO_CREDITO_CONTA_PRINT','Fechamento Credito Conta Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoCreditoContaPrint: String read FFECHAMENTO_CREDITO_CONTA_PRINT write FFECHAMENTO_CREDITO_CONTA_PRINT;
[TColumn('FECHAMENTO_CARTAO_PRINT','Fechamento Cartao Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoCartaoPrint: String read FFECHAMENTO_CARTAO_PRINT write FFECHAMENTO_CARTAO_PRINT;
[TColumn('FECHAMENTO_PRODUTO_PRINT','Fechamento Produto Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoProdutoPrint: String read FFECHAMENTO_PRODUTO_PRINT write FFECHAMENTO_PRODUTO_PRINT;
[TColumn('FECHAMENTO_SUBGRUPO_PRINT','Fechamento Subgrupo Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoSubgrupoPrint: String read FFECHAMENTO_SUBGRUPO_PRINT write FFECHAMENTO_SUBGRUPO_PRINT;
[TColumn('FECHAMENTO_PRODUTO_MODULO_PRINT','Fechamento Produto Modulo Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoProdutoModuloPrint: String read FFECHAMENTO_PRODUTO_MODULO_PRINT write FFECHAMENTO_PRODUTO_MODULO_PRINT;
[TColumn('FECHAMENTO_ATENDENTE_PRINT','Fechamento Atendente Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoAtendentePrint: String read FFECHAMENTO_ATENDENTE_PRINT write FFECHAMENTO_ATENDENTE_PRINT;
[TColumn('FECHAMENTO_DELIVERYMAN_PRINT','Fechamento Deliveryman Print',8,[ldGrid, ldLookup, ldCombobox], False)]
property FechamentoDeliverymanPrint: String read FFECHAMENTO_DELIVERYMAN_PRINT write FFECHAMENTO_DELIVERYMAN_PRINT;
[TColumn('RECEBIMENTO01','Recebimento01',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Recebimento01: Integer read FRECEBIMENTO01 write FRECEBIMENTO01;
[TColumn('RECEBIMENTO02','Recebimento02',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Recebimento02: Integer read FRECEBIMENTO02 write FRECEBIMENTO02;
[TColumn('RECEBIMENTO03','Recebimento03',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Recebimento03: Integer read FRECEBIMENTO03 write FRECEBIMENTO03;
[TColumn('RECEBIMENTO04','Recebimento04',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Recebimento04: Integer read FRECEBIMENTO04 write FRECEBIMENTO04;
[TColumn('RECEBIMENTO05','Recebimento05',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Recebimento05: Integer read FRECEBIMENTO05 write FRECEBIMENTO05;
[TColumn('IMAGEM_REPOSITORIO','Imagem Repositorio',400,[ldGrid, ldLookup, ldCombobox], False)]
property ImagemRepositorio: String read FIMAGEM_REPOSITORIO write FIMAGEM_REPOSITORIO;
[TColumn('CONSULTA','Consulta',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Consulta: Integer read FCONSULTA write FCONSULTA;
[TColumn('COBRAR_SERVICO','Cobrar Servico',8,[ldGrid, ldLookup, ldCombobox], False)]
property CobrarServico: String read FCOBRAR_SERVICO write FCOBRAR_SERVICO;
[TColumn('SERVICO_OPCIONAL','Servico Opcional',8,[ldGrid, ldLookup, ldCombobox], False)]
property ServicoOpcional: String read FSERVICO_OPCIONAL write FSERVICO_OPCIONAL;
[TColumn('INFORMAR_PESSOAS','Informar Pessoas',8,[ldGrid, ldLookup, ldCombobox], False)]
property InformarPessoas: String read FINFORMAR_PESSOAS write FINFORMAR_PESSOAS;
[TColumn('LAYOUT','Layout',160,[ldGrid, ldLookup, ldCombobox], False)]
property Layout: String read FLAYOUT write FLAYOUT;
[TColumn('CAIXA_GAVETA','Caixa Gaveta',8,[ldGrid, ldLookup, ldCombobox], False)]
property CaixaGaveta: String read FCAIXA_GAVETA write FCAIXA_GAVETA;
[TColumn('CONTROLA_MESAS','Controla Mesas',8,[ldGrid, ldLookup, ldCombobox], False)]
property ControlaMesas: String read FCONTROLA_MESAS write FCONTROLA_MESAS;
[TColumn('MOBILE_PREVENDA_FECHAMENTO','Mobile Prevenda Fechamento',8,[ldGrid, ldLookup, ldCombobox], False)]
property MobilePrevendaFechamento: String read FMOBILE_PREVENDA_FECHAMENTO write FMOBILE_PREVENDA_FECHAMENTO;
[TColumn('DELIVERYMAN_AFTER_RECEBER','Deliveryman After Receber',8,[ldGrid, ldLookup, ldCombobox], False)]
property DeliverymanAfterReceber: String read FDELIVERYMAN_AFTER_RECEBER write FDELIVERYMAN_AFTER_RECEBER;
[TAssociation(True,'ID','ID_IMPRESSORA')]
property Impressora: TImpressoraVO read FIMPRESSORA write FIMPRESSORA;
end;
implementation
{ TTerminalVO }
destructor TTerminalVO.Destroy;
begin
if Assigned(FIMPRESSORA) then
FreeAndNil(FIMPRESSORA);
inherited;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.ExtCtrls,
System.ImageList, Vcl.ImgList, Vcl.StdCtrls, Vcl.Imaging.pngimage, DateUtils;
type
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Image1: TImage;
Label3: TLabel;
lblQtdeAvioesDesativados: TLabel;
Panel2: TPanel;
Panel3: TPanel;
Label6: TLabel;
lblTotalViagensRealizadas: TLabel;
Panel4: TPanel;
Label8: TLabel;
lblQtdeRetornosHoje: TLabel;
Panel5: TPanel;
Label1: TLabel;
lblQtdeAvioesAtivos: TLabel;
Panel6: TPanel;
Label5: TLabel;
lblQtdeAgendadas: TLabel;
Panel7: TPanel;
Label11: TLabel;
lblQtdePartidasHoje: TLabel;
Button5: TButton;
procedure AtualizaTela(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Unit2, Unit3, Unit5, Unit4, Unit7, Unit8, Unit9;
procedure TForm1.Button1Click(Sender: TObject);
begin
Form5.Show;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Form8.ShowModal;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Form9.Show;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
Form3.Show;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Form7.ShowModal;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
Form1.AtualizaTela(Sender);
end;
procedure TForm1.AtualizaTela(Sender: TObject);
begin
// Realiza a Busca
dtmPrincipal.qyrBuscaQtdeAvioesAtivos.Active := false;
dtmPrincipal.qyrBuscaQtdeAvioesAtivos.Active := true;
// Atualiza a tela
lblQtdeAvioesAtivos.Caption := dtmPrincipal.qyrBuscaQtdeAvioesAtivosTOTAL_ATIVOS.AsString;
// Realiza a Busca
dtmPrincipal.qryBuscaQtdeAvioesDesativados.Active := false;
dtmPrincipal.qryBuscaQtdeAvioesDesativados.Active := true;
// Atualiza a tela
lblQtdeAvioesDesativados.Caption := dtmPrincipal.qryBuscaQtdeAvioesDesativadosTOTAL_DESATIVADOS.AsString;
// Realiza a Busca
dtmPrincipal.qyrBuscaQtdeViagensRealizadas.Active := false;
dtmPrincipal.qyrBuscaQtdeViagensRealizadas.Active := true;
// Atualiza a tela
lblTotalViagensRealizadas.Caption := dtmPrincipal.qyrBuscaQtdeViagensRealizadasCOUNT.AsString;
// Realiza a Busca
dtmPrincipal.qryBuscaQtdeViagensAgendadas.Active := false;
dtmPrincipal.qryBuscaQtdeViagensAgendadas.Active := true;
// Atualiza a tela
lblQtdeAgendadas.Caption := dtmPrincipal.qryBuscaQtdeViagensAgendadasCOUNT.AsString;
// Realiza a Busca
dtmPrincipal.qyrQtdePartidasHoje.Active := false;
dtmPrincipal.qyrQtdePartidasHoje.Active := true;
// Atualiza a tela
lblQtdePartidasHoje.Caption := dtmPrincipal.qyrQtdePartidasHojeCOUNT.AsString;
// Realiza a Busca
dtmPrincipal.qryBuscaQtdeRetornoHoje.Active := false;
dtmPrincipal.qryBuscaQtdeRetornoHoje.Active := true;
// Atualiza a tela
lblQtdeRetornosHoje.Caption := dtmPrincipal.qryBuscaQtdeRetornoHojeCOUNT.AsString;
end;
end.
|
object Form4: TForm4
Left = 465
Top = 229
BiDiMode = bdLeftToRight
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
ClientHeight = 365
ClientWidth = 695
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsStayOnTop
KeyPreview = True
OldCreateOrder = False
ParentBiDiMode = False
OnClose = FormClose
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object Edit1: TadLabelEdit
Left = 1
Top = 18
Width = 308
Height = 19
LabelDefs.Width = 31
LabelDefs.Height = 13
LabelDefs.Caption = 'Nome '
Colors.WhenEnterFocus.BackColor = clInfoBk
Ctl3D = False
ParentCtl3D = False
CharCase = ecUpperCase
MaxLength = 40
TabOrder = 0
OnKeyDown = Edit1KeyDown
end
object CBox2: TadLabelComboBox
Left = 126
Top = 334
Width = 110
Height = 21
BevelKind = bkSoft
Style = csDropDownList
ItemHeight = 13
ItemIndex = 0
TabOrder = 1
Text = 'Descricao'
Visible = False
Items.Strings = (
'Descricao'
'Codigo'
'Nenhum')
LabelDefs.Width = 111
LabelDefs.Height = 13
LabelDefs.Caption = 'Organizar os itens por...'
Colors.WhenEnterFocus.BackColor = clInfoBk
end
object cbox1: TadLabelComboBox
Left = 1
Top = 334
Width = 117
Height = 21
BevelKind = bkSoft
Style = csDropDownList
ItemHeight = 13
ItemIndex = 0
TabOrder = 2
Text = 'N'#227'o comprados'
Visible = False
Items.Strings = (
'N'#227'o comprados'
'Todos'
'Somente Comprados')
LabelDefs.Width = 74
LabelDefs.Height = 13
LabelDefs.Caption = 'Imprimir os itens'
Colors.WhenEnterFocus.BackColor = clInfoBk
end
object BitBtn1: TFlatButton
Left = 603
Top = 14
Width = 88
Height = 25
Default = True
Caption = '&Procurar'
Glyph.Data = {
76010000424D7601000000000000760000002800000020000000100000000100
04000000000000010000130B0000130B00001000000000000000000000000000
800000800000008080008000000080008000808000007F7F7F00BFBFBF000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
33033333333333333F7F3333333333333000333333333333F777333333333333
000333333333333F777333333333333000333333333333F77733333333333300
033333333FFF3F777333333700073B703333333F7773F77733333307777700B3
33333377333777733333307F8F8F7033333337F333F337F3333377F8F9F8F773
3333373337F3373F3333078F898F870333337F33F7FFF37F333307F99999F703
33337F377777337F3333078F898F8703333373F337F33373333377F8F9F8F773
333337F3373337F33333307F8F8F70333333373FF333F7333333330777770333
333333773FF77333333333370007333333333333777333333333}
Layout = blGlyphLeft
NumGlyphs = 2
TabOrder = 3
OnClick = BitBtn1Click
end
object BitBtn2: TFlatButton
Left = 532
Top = 318
Width = 75
Height = 29
Caption = '&OK'
Glyph.Data = {
DE010000424DDE01000000000000760000002800000024000000120000000100
0400000000006801000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
3333333333333333333333330000333333333333333333333333F33333333333
00003333344333333333333333388F3333333333000033334224333333333333
338338F3333333330000333422224333333333333833338F3333333300003342
222224333333333383333338F3333333000034222A22224333333338F338F333
8F33333300003222A3A2224333333338F3838F338F33333300003A2A333A2224
33333338F83338F338F33333000033A33333A222433333338333338F338F3333
0000333333333A222433333333333338F338F33300003333333333A222433333
333333338F338F33000033333333333A222433333333333338F338F300003333
33333333A222433333333333338F338F00003333333333333A22433333333333
3338F38F000033333333333333A223333333333333338F830000333333333333
333A333333333333333338330000333333333333333333333333333333333333
0000}
Layout = blGlyphLeft
NumGlyphs = 2
TabOrder = 4
OnClick = BitBtn2Click
end
object btCancela: TFlatButton
Left = 614
Top = 318
Width = 75
Height = 29
Caption = '&Cancelar'
Glyph.Data = {
DE010000424DDE01000000000000760000002800000024000000120000000100
0400000000006801000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
333333333333333333333333000033338833333333333333333F333333333333
0000333911833333983333333388F333333F3333000033391118333911833333
38F38F333F88F33300003339111183911118333338F338F3F8338F3300003333
911118111118333338F3338F833338F3000033333911111111833333338F3338
3333F8330000333333911111183333333338F333333F83330000333333311111
8333333333338F3333383333000033333339111183333333333338F333833333
00003333339111118333333333333833338F3333000033333911181118333333
33338333338F333300003333911183911183333333383338F338F33300003333
9118333911183333338F33838F338F33000033333913333391113333338FF833
38F338F300003333333333333919333333388333338FFF830000333333333333
3333333333333333333888330000333333333333333333333333333333333333
0000}
Layout = blGlyphLeft
NumGlyphs = 2
TabOrder = 5
OnClick = btCancelaClick
end
object CB1: TadLabelComboBox
Left = 458
Top = 17
Width = 141
Height = 21
BevelKind = bkSoft
Style = csDropDownList
ItemHeight = 13
TabOrder = 6
LabelDefs.Width = 57
LabelDefs.Height = 13
LabelDefs.Caption = 'Tipo de lista'
Colors.WhenDisabled.TextColor = clWindow
Colors.WhenEnterFocus.BackColor = clInfoBk
end
object DBGrid1: TSoftDBGrid
Left = 0
Top = 44
Width = 690
Height = 269
Ctl3D = False
DataSource = DataSource1
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentCtl3D = False
ParentFont = False
TabOrder = 7
TitleFont.Charset = DEFAULT_CHARSET
TitleFont.Color = clWindowText
TitleFont.Height = -11
TitleFont.Name = 'MS Sans Serif'
TitleFont.Style = [fsBold]
OnDblClick = DBGrid1DblClick
OnTitleClick = DBGrid1TitleClick
AlternateColor = True
ColorLow = clWindow
ColorHigh = clInfoBk
Columns = <
item
Expanded = False
FieldName = 'NumLista'
Title.Caption = 'N'#250'mero'
Width = 48
Visible = True
end
item
Expanded = False
FieldName = 'Descricao'
Width = 134
Visible = True
end
item
Expanded = False
FieldName = 'noiva'
Title.Caption = 'Noiva'
Width = 195
Visible = True
end
item
Expanded = False
FieldName = 'noivo'
Title.Caption = 'Noivo'
Width = 231
Visible = True
end
item
Expanded = False
FieldName = 'Loja'
Width = 30
Visible = True
end
item
Expanded = False
FieldName = 'EndEntrega'
Title.Caption = 'Endere'#231'o de entrega'
Width = 180
Visible = True
end
item
Expanded = False
FieldName = 'dataCasamento'
ImeName = 'DataCasamento'
Title.Caption = 'Data evento'
Width = 81
Visible = True
end>
end
object cbBuscaNum: TfsCheckBox
Left = 317
Top = 19
Width = 132
Height = 17
Caption = 'Procure pelo n'#250'mero'
TabOrder = 8
FlatFont.Charset = DEFAULT_CHARSET
FlatFont.Color = clWindowText
FlatFont.Height = -11
FlatFont.Name = 'MS Sans Serif'
FlatFont.Style = []
end
object DataSource1: TDataSource
DataSet = QueryImpressao
Left = 19
Top = 125
end
object query2: TADOQuery
Connection = Form1.ADOConnection1
CursorType = ctStatic
Parameters = <>
SQL.Strings = (
'select * from PRODUTOS where numlista =7')
Left = 16
Top = 192
end
object Export1: TmxDataSetExport
DateFormat = 'dd/MM/yyyy'
TimeFormat = 'hh:mm'
DateTimeFormat = 'hh:mm dd/MM/yyyy'
ExportType = xtTXT
ExportTypes = [xtTXT, xtClipboard]
ExportStyle = xsFile
FileName = 'c:\Zteste.txt'
HTML.CustomColors.Background = clWhite
HTML.CustomColors.DefaultLink = clRed
HTML.CustomColors.DefaultFontFace = 'Arial,Helvetica'
HTML.CustomColors.VisitedLink = clAqua
HTML.CustomColors.ActiveLink = clBlue
HTML.CustomColors.DefaultText = clBlack
HTML.CustomColors.TableFontColor = clBlack
HTML.CustomColors.TableFontFace = 'Arial,Helvetica'
HTML.CustomColors.TableBackground = 16777167
HTML.CustomColors.TableOddBackground = clWhite
HTML.CustomColors.HeaderBackground = 3368601
HTML.CustomColors.HeadersFontColor = clWhite
HTML.Options = [hoShowGridLines, hoBoldHeaders, hoAutoLink, hoOddRowColoring, hoDisplayTitle]
HTML.Template = ctStandard
Messages.Caption = 'Montando Relat'#243'rio...'
Messages.CopiedToClipboard = 'Data was copied to clipboard!'
Messages.CancelCaption = '&Cancel'
Messages.CreatedText = 'Created:'
Messages.DocumentFilter.HTML = 'HTML Documents'
Messages.DocumentFilter.Excel = 'Excel Files'
Messages.DocumentFilter.Word = 'Word Documents'
Messages.DocumentFilter.Text = 'Text Files'
Messages.DocumentFilter.Comma = 'CSV (Comma delimited)'
Messages.DocumentFilter.Tab = 'Text (Tab delimited)'
Messages.DocumentFilter.RTF = 'Rich Text Format'
Messages.DocumentFilter.DIF = 'Data Interchange Format'
Messages.DocumentFilter.SYLK = 'SYLK Files'
Messages.ExportCaption = '&Export'
Messages.ExportToFile = 'Export &to file'
Messages.FalseText = 'False'
Messages.Height = 80
Messages.SaveTitle = 'Save document'
Messages.SelectFormat = 'E&xport formats:'
Messages.Text = 'Processing...'
Messages.TrueText = 'True'
Messages.Width = 300
Messages.ViewOnly = '&View only'
TruncateSymbol = '...'
RowNumberFormat = '%d'
DOC_RTF.Template = rtStandard
DOC_RTF.Options = [roShowGridLines, roOddRowColoring]
DOC_RTF.CustomSettings.TableBackground = 16777167
DOC_RTF.CustomSettings.TableOddBackground = clWhite
DOC_RTF.CustomSettings.HeaderBackground = 3368601
DOC_RTF.CustomSettings.DefaultFont.Charset = DEFAULT_CHARSET
DOC_RTF.CustomSettings.DefaultFont.Color = clWindowText
DOC_RTF.CustomSettings.DefaultFont.Height = -11
DOC_RTF.CustomSettings.DefaultFont.Name = 'MS Sans Serif'
DOC_RTF.CustomSettings.DefaultFont.Style = []
DOC_RTF.CustomSettings.HeaderFont.Charset = DEFAULT_CHARSET
DOC_RTF.CustomSettings.HeaderFont.Color = clWindowText
DOC_RTF.CustomSettings.HeaderFont.Height = -11
DOC_RTF.CustomSettings.HeaderFont.Name = 'MS Sans Serif'
DOC_RTF.CustomSettings.HeaderFont.Style = [fsBold]
DOC_RTF.CustomSettings.TableFont.Charset = DEFAULT_CHARSET
DOC_RTF.CustomSettings.TableFont.Color = clWindowText
DOC_RTF.CustomSettings.TableFont.Height = -11
DOC_RTF.CustomSettings.TableFont.Name = 'MS Sans Serif'
DOC_RTF.CustomSettings.TableFont.Style = []
DOC_RTF.CellWidth = 1400
DOC_RTF.TopMargin = 101
DOC_RTF.BottomMargin = 101
DOC_RTF.LeftMargin = 461
DOC_RTF.RightMargin = 562
EXCEL.Options = [reSetMargins, reUseBorders]
EXCEL.ColumnWidth = 20
EXCEL.Protected = False
EXCEL.Footer = '&P'
EXCEL.DefaultFont.Charset = DEFAULT_CHARSET
EXCEL.DefaultFont.Color = clWindowText
EXCEL.DefaultFont.Height = -11
EXCEL.DefaultFont.Name = 'MS Sans Serif'
EXCEL.DefaultFont.Style = []
EXCEL.HeaderFont.Charset = DEFAULT_CHARSET
EXCEL.HeaderFont.Color = clWindowText
EXCEL.HeaderFont.Height = -11
EXCEL.HeaderFont.Name = 'MS Sans Serif'
EXCEL.HeaderFont.Style = [fsBold]
EXCEL.TableFont.Charset = DEFAULT_CHARSET
EXCEL.TableFont.Color = clWindowText
EXCEL.TableFont.Height = -11
EXCEL.TableFont.Name = 'MS Sans Serif'
EXCEL.TableFont.Style = []
EXCEL.TopMargin = 0.300000000000000000
EXCEL.BottomMargin = 0.300000000000000000
EXCEL.LeftMargin = 0.300000000000000000
EXCEL.RightMargin = 0.300000000000000000
Options = [xoUseAlignments]
Version = '2.37'
Left = 80
Top = 192
end
object Query3: TADOQuery
Connection = Form1.ADOConnection1
CursorType = ctStatic
Parameters = <>
SQL.Strings = (
'select * from listas where numlista =7')
Left = 15
Top = 224
end
object RvSystem1: TRvSystem
TitleSetup = 'Impress'#227'o de lista'
TitleStatus = 'Pr'#233'via de impress'#227'o'
TitlePreview = 'Espelho de lista '
SystemSetups = [ssAllowSetup, ssAllowCopies, ssAllowCollate, ssAllowDuplex, ssAllowDestPreview, ssAllowDestPrinter, ssAllowPrinterSetup, ssAllowPreviewSetup]
DefaultDest = rdPrinter
SystemFiler.StatusFormat = 'Generating page %p'
SystemPreview.FormHeight = 500
SystemPreview.FormState = wsMaximized
SystemPreview.ZoomFactor = 75.000000000000000000
SystemPrinter.ScaleX = 100.000000000000000000
SystemPrinter.ScaleY = 100.000000000000000000
SystemPrinter.StatusFormat = 'Printing page %p'
SystemPrinter.Title = 'Espelho de lista '
SystemPrinter.UnitsFactor = 1.000000000000000000
Left = 18
Top = 160
end
object RvProject1: TRvProject
Engine = RvSystem1
ProjectFile = 'C:\Listas\EspelhoLista.rav'
Left = 50
Top = 160
end
object RvDataSetConnection1: TRvDataSetConnection
RuntimeVisibility = rtDeveloper
DataSet = Query3
Left = 47
Top = 224
end
object RvDataSetConnection2: TRvDataSetConnection
RuntimeVisibility = rtDeveloper
DataSet = query2
Left = 48
Top = 192
end
object QueryImpressao: TADOQuery
Connection = Form1.ADOConnection1
CursorType = ctStatic
LockType = ltBatchOptimistic
Parameters = <>
SQL.Strings = (
'Exec stoObterCadastroDeListasResumo @dtinicio = '#39'01/01/2000'#39' , @' +
'dtFim = '#39'12/31/2029'#39' , @loja = '#39'00'#39' , @tipo = '#39#39' , @nome = '#39'mari' +
'a'#39)
Left = 20
Top = 88
end
end
|
unit GLDAboutForm;
interface
uses
Windows, Classes, Graphics, Controls, Forms, StdCtrls;
type
TGLDAboutForm = class(TForm)
L_GLDraw: TLabel;
L_GLDrawVersion: TLabel;
L_Author: TLabel;
L_Year: TLabel;
L_Platform: TLabel;
L_PlatformVersion: TLabel;
L_Update: TLabel;
L_GLVersion: TLabel;
L_Renderer: TLabel;
L_Vendor: TLabel;
B_Ok: TButton;
procedure FormCreate(Sender: TObject);
procedure B_OkClick(Sender: TObject);
private
public
end;
function GLDGetAboutForm: TGLDAboutForm;
procedure GLDReleaseAboutForm;
implementation
{$R *.dfm}
uses
SysUtils, GL;
var
vAboutForm: TGLDAboutForm = nil;
function GLDGetAboutForm: TGLDAboutForm;
begin
if not Assigned(vAboutForm) then
vAboutForm := TGLDAboutForm.Create(nil);
Result := vAboutForm;
end;
procedure GLDReleaseAboutForm;
begin
if Assigned(vAboutForm) then
begin
vAboutForm.Free;
vAboutForm := nil;
end;
end;
procedure TGLDAboutForm.FormCreate(Sender: TObject);
begin
case Win32Platform of
VER_PLATFORM_WIN32_WINDOWS:
L_Platform.Caption := 'Platform: Windows 95';
VER_PLATFORM_WIN32_NT:
L_Platform.Caption := 'Platform: Windows NT';
end;
L_PlatformVersion.Caption := 'Platform verzió: ' +
IntToStr(Win32MajorVersion) + '.' +
IntToStr(Win32MinorVersion) + ' (' +
IntToStr(Win32BuildNumber) + ')';
L_UpDate.Caption := 'Frissítés: ' + Win32CSDVersion;
L_GLVersion.Caption := 'OpenGL verzió: ' + glGetString(GL_VERSION);
L_Renderer.Caption := 'Grafikus eszköz: ' + glGetString(GL_RENDERER);
L_Vendor.Caption := 'Gyártó: ' + glGetString(GL_VENDOR);
end;
procedure TGLDAboutForm.B_OkClick(Sender: TObject);
begin
Close;
end;
initialization
finalization
GLDReleaseAboutForm;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Objects that get rendered in 2D coordinates
}
unit VXS.HUDObjects;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.OpenGL,
VXS.VectorTypes,
VXS.XOpenGL,
VXS.PersistentClasses,
VXS.Scene,
VXS.Coordinates,
VXS.VectorGeometry,
VXS.Objects,
VXS.BitmapFont,
VXS.CrossPlatform,
VXS.Color,
VXS.RenderContextInfo,
VXS.Context,
VXS.State;
type
{ A rectangular area, NOT perspective projected.
(x, y) coordinates map directly to the viewport (in pixels) and refer
the center of the area.
The coordinate system is that of an equivalent TCanvas, ie. top-left
point is the origin (0, 0).
The z component is ignored and Z-Buffer is disabled when rendering.
Using TVXHUDSprite in 2D only scenes :
The most convenient way to use a TVXHUDSprite as a simple 2D sprite with
blending capabilities (transparency or additive), is to set the texture
mode to tmModulate, in FrontProperties, to use the Emission color to
control coloring/intensity, and finally use the Diffuse color's alpha
to control transparency (while setting the other RGB components to 0).
You can also control aplha-blending by defining a <1 value in the sprite's
AlphaChannel field. This provides you with hardware accelerated,
alpha-blended blitting.
Note : since TVXHUDSprite works in absolute coordinates, TVXProxyObject
can't be used to duplicate an hud sprite. }
TVXHUDSprite = class(TVXSprite)
private
FXTiles, FYTiles: Integer;
function StoreWidth: Boolean;
function StoreHeight: Boolean;
protected
procedure SetXTiles(const val: Integer);
procedure SetYTiles(const val: Integer);
public
constructor Create(AOwner: TComponent); override;
procedure DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean); override;
published
property XTiles: Integer read FXTiles write SetXTiles default 1;
property YTiles: Integer read FYTiles write SetYTiles default 1;
// Redeclare them with new default values.
property Width stored StoreWidth;
property Height stored StoreHeight;
end;
{ A 2D text displayed and positionned in 2D coordinates.
The HUDText uses a character font defined and stored by a TVXBitmapFont
component. The text can be scaled and rotated (2D), the layout and
alignment can also be controled. }
TVXHUDText = class(TVXImmaterialSceneObject)
private
FBitmapFont: TVXCustomBitmapFont;
FText: UnicodeString;
FRotation: Single;
FAlignment: TAlignment;
FLayout: TVXTextLayout;
FModulateColor: TVXColor;
protected
procedure SetBitmapFont(const val: TVXCustomBitmapFont);
procedure SetText(const val: UnicodeString);
procedure SetRotation(const val: Single);
procedure SetAlignment(const val: TAlignment);
procedure SetLayout(const val: TVXTextLayout);
procedure SetModulateColor(const val: TVXColor);
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure RenderTextAtPosition(const X, Y, Z: Single;
var rci: TVXRenderContextInfo);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean); override;
published
{ Refers the bitmap font to use.
The referred bitmap font component stores and allows access to
individual character bitmaps. }
property BitmapFont: TVXCustomBitmapFont read FBitmapFont
write SetBitmapFont;
{ Text to render.
Be aware that only the characters available in the bitmap font will
be rendered. CR LF sequences are allowed. }
property Text: UnicodeString read FText write SetText;
{ Rotation angle in degrees (2d). }
property Rotation: Single read FRotation write SetRotation;
{ Controls the text alignment (horizontal).
Possible values : taLeftJustify, taRightJustify, taCenter }
property Alignment: TAlignment read FAlignment write SetAlignment
default taLeftJustify;
{ Controls the text layout (vertical).
Possible values : tlTop, tlCenter, tlBottom }
property Layout: TVXTextLayout read FLayout write SetLayout default tlTop;
{ Color modulation, can be used for fade in/out too. }
property ModulateColor: TVXColor read FModulateColor write SetModulateColor;
end;
{ Position (X, Y and X) is in absolute coordinates. This component converts
them to screen coordinates and renderes text there. }
TVXAbsoluteHUDText = class(TVXHUDText)
public
procedure DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean); override;
end;
{ Position (X and Y) is expected in a [0..1] range (from Screen size)
This component converts this position to the actual screen position and
renders the text there. This way a HUD text always appears to be in the
the same place, regardless of the currect screen resolution.
Note: this still does not solve the font scaling problem. }
TVXResolutionIndependantHUDText = class(TVXHUDText)
public
procedure DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean); override;
constructor Create(AOwner: TComponent); override;
end;
//=====================================================================
implementation
//=====================================================================
// ------------------
// ------------------ TVXHUDSprite ------------------
// ------------------
constructor TVXHUDSprite.Create(AOwner: TComponent);
begin
inherited;
ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling];
Width := 16;
Height := 16;
FXTiles := 1;
FYTiles := 1;
end;
procedure TVXHUDSprite.SetXTiles(const val: Integer);
begin
if val <> FXTiles then
begin
FXTiles := val;
StructureChanged;
end;
end;
procedure TVXHUDSprite.SetYTiles(const val: Integer);
begin
if val <> FYTiles then
begin
FYTiles := val;
StructureChanged;
end;
end;
procedure TVXHUDSprite.DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean);
var
vx, vy, vx1, vy1, f: Single;
u0, v0, u1, v1: Integer;
begin
if rci.ignoreMaterials then
Exit;
Material.Apply(rci);
repeat
if AlphaChannel <> 1 then
begin
if stLighting in rci.VXStates.States then
rci.VXStates.SetMaterialAlphaChannel(GL_FRONT, AlphaChannel)
else
with Material.GetActualPrimaryMaterial.FrontProperties.Diffuse do
glColor4f(Red, Green, Blue, AlphaChannel);
end;
// Prepare matrices
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadMatrixf(@TVXSceneBuffer(rci.buffer).BaseProjectionMatrix);
if rci.renderDPI = 96 then
f := 1
else
f := rci.renderDPI / 96;
glScalef(2 / rci.viewPortSize.cx, 2 / rci.viewPortSize.cy, 1);
glTranslatef(f * Position.X - rci.viewPortSize.cx * 0.5,
rci.viewPortSize.cy * 0.5 - f * Position.Y, Position.Z);
if Rotation <> 0 then
glRotatef(Rotation, 0, 0, 1);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
rci.VXStates.Disable(stDepthTest);
rci.VXStates.DepthWriteMask := False;
// precalc coordinates
vx := -Width * 0.5 * f;
vx1 := vx + Width * f;
vy := +Height * 0.5 * f;
vy1 := vy - Height * f;
// Texture coordinates
if MirrorU then
begin
u0 := FXTiles;
u1 := 0;
end
else
begin
u0 := 0;
u1 := FXTiles;
end;
if MirrorV then
begin
v0 := FYTiles;
v1 := 0;
end
else
begin
v0 := 0;
v1 := FYTiles;
end;
// issue quad
glBegin(GL_QUADS);
glNormal3fv(@YVector);
glTexCoord2f(u0, v0);
glVertex2f(vx, vy1);
glTexCoord2f(u1, v0);
glVertex2f(vx1, vy1);
glTexCoord2f(u1, v1);
glVertex2f(vx1, vy);
glTexCoord2f(u0, v1);
glVertex2f(vx, vy);
glEnd;
// restore state
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
until not Material.UnApply(rci);
if Count > 0 then
Self.renderChildren(0, Count - 1, rci);
end;
// StoreHeight
//
function TVXHUDSprite.StoreHeight: Boolean;
begin
Result := Abs(Height - 16) > 0.001;
end;
// StoreWidth
//
function TVXHUDSprite.StoreWidth: Boolean;
begin
Result := Abs(Height - 16) > 0.001;
end;
// ------------------
// ------------------ TVXHUDText ------------------
// ------------------
constructor TVXHUDText.Create(AOwner: TComponent);
begin
inherited;
ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling];
FModulateColor := TVXColor.CreateInitialized(Self, clrWhite);
end;
destructor TVXHUDText.Destroy;
begin
FModulateColor.Free;
BitmapFont := nil;
inherited;
end;
procedure TVXHUDText.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FBitmapFont) then
BitmapFont := nil;
inherited;
end;
procedure TVXHUDText.SetBitmapFont(const val: TVXCustomBitmapFont);
begin
if val <> FBitmapFont then
begin
if Assigned(FBitmapFont) then
FBitmapFont.UnRegisterUser(Self);
FBitmapFont := val;
if Assigned(FBitmapFont) then
begin
FBitmapFont.RegisterUser(Self);
FBitmapFont.FreeNotification(Self);
end;
StructureChanged;
end;
end;
procedure TVXHUDText.SetText(const val: UnicodeString);
begin
FText := val;
StructureChanged;
end;
procedure TVXHUDText.SetRotation(const val: Single);
begin
FRotation := val;
StructureChanged;
end;
procedure TVXHUDText.SetAlignment(const val: TAlignment);
begin
FAlignment := val;
StructureChanged;
end;
procedure TVXHUDText.SetLayout(const val: TVXTextLayout);
begin
FLayout := val;
StructureChanged;
end;
procedure TVXHUDText.SetModulateColor(const val: TVXColor);
begin
FModulateColor.Assign(val);
end;
procedure TVXHUDText.RenderTextAtPosition(const X, Y, Z: Single;
var rci: TVXRenderContextInfo);
var
f: Single;
begin
if Assigned(FBitmapFont) and (Text <> '') then
begin
rci.VXStates.PolygonMode := pmFill;
// Prepare matrices
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadMatrixf(@TVXSceneBuffer(rci.buffer).BaseProjectionMatrix);
f := rci.renderDPI / 96;
glScalef(2 / rci.viewPortSize.cx, 2 / rci.viewPortSize.cy, 1);
glTranslatef(X * f - rci.viewPortSize.cx / 2, rci.viewPortSize.cy / 2 -
Y * f, Z);
if FRotation <> 0 then
glRotatef(FRotation, 0, 0, 1);
glScalef(Scale.DirectX * f, Scale.DirectY * f, 1);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
rci.VXStates.Disable(stDepthTest);
// render text
FBitmapFont.RenderString(rci, Text, FAlignment, FLayout,
FModulateColor.Color);
// restore state
rci.VXStates.Enable(stDepthTest);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
end;
end;
procedure TVXHUDText.DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean);
begin
RenderTextAtPosition(Position.X, Position.Y, Position.Z, rci);
if Count > 0 then
Self.renderChildren(0, Count - 1, rci);
end;
// ------------------
// ------------------ TVXResolutionIndependantHUDText ------------------
// ------------------
constructor TVXResolutionIndependantHUDText.Create(AOwner: TComponent);
begin
inherited;
Position.X := 0.5;
Position.Y := 0.5;
end;
procedure TVXResolutionIndependantHUDText.DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean);
begin
RenderTextAtPosition(Position.X * rci.viewPortSize.cx,
Position.Y * rci.viewPortSize.cy, Position.Z, rci);
if Count > 0 then
Self.renderChildren(0, Count - 1, rci);
end;
// ------------------
// ------------------ TVXAbsoluteHUDText ------------------
// ------------------
procedure TVXAbsoluteHUDText.DoRender(var rci: TVXRenderContextInfo;
renderSelf, renderChildren: Boolean);
var
Temp: TAffineVector;
begin
Temp := TVXSceneBuffer(rci.buffer).WorldToScreen(Self.AbsoluteAffinePosition);
Temp.Y := rci.viewPortSize.cy - Temp.Y;
RenderTextAtPosition(Temp.X, Temp.Y, Temp.Z, rci);
if Count > 0 then
Self.renderChildren(0, Count - 1, rci);
end;
//=======================================================================
initialization
//=======================================================================
// class registrations
RegisterClasses([TVXHUDText, TVXHUDSprite, TVXResolutionIndependantHUDText,
TVXAbsoluteHUDText]);
end.
|
{-----------------------------------------------------------------------------
Unit Name: frmCallStack
Author: Kiriakos Vlahos
Purpose: Call Stack Window
History:
-----------------------------------------------------------------------------}
unit frmCallStack;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, JvDockControlForm, JvComponent, cPyBaseDebugger, frmIDEDockWin,
Contnrs, ExtCtrls, TBX, TBXThemes, VirtualTrees, JvComponentBase;
type
TCallStackWindow = class(TIDEDockWindow)
CallStackView: TVirtualStringTree;
procedure CallStackViewDblClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure CallStackViewGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure CallStackViewInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure CallStackViewChange(Sender: TBaseVirtualTree;
Node: PVirtualNode);
private
{ Private declarations }
SelectedNode: PVirtualNode;
fCallStackList : TObjectList;
protected
procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE;
public
{ Public declarations }
procedure ClearAll;
function GetSelectedStackFrame : TBaseFrameInfo;
procedure UpdateWindow(DebuggerState : TDebuggerState);
end;
var
CallStackWindow: TCallStackWindow = nil;
implementation
uses frmPyIDEMain, VarPyth, frmVariables, PythonEngine, uCommonFunctions,
dmCommands, JvDockGlobals;
{$R *.dfm}
Type
PCallStackRec = ^TCallStackRec;
TCallStackRec = record
FrameInfo : TBaseFrameInfo;
end;
{ TCallStackWindow }
procedure TCallStackWindow.UpdateWindow(DebuggerState : TDebuggerState);
begin
// Do not update anything if the debugger just entered running state
// The callstack and the variables window will be updated when the
// Debugger becomes Paused or Inactive
if (DebuggerState = dsRunning) then Exit;
ClearAll;
// if Assigned(VariablesWindow) then
// VariablesWindow.ClearAll;
if (DebuggerState = dsPaused) then begin
PyIDEMainForm.PyDebugger.GetCallStack(fCallStackList);
CallStackView.RootNodeCount := fCallStackList.Count; // Fills the View
CallStackView.ReinitNode(CallStackView.RootNode, True);
// The following statement updates the Variables Window as well
if Assigned(CallStackView.RootNode.FirstChild) then
CallStackView.Selected[CallStackView.RootNode.FirstChild] := True;
end else begin
if Assigned(VariablesWindow) then
VariablesWindow.UpdateWindow;
end;
end;
procedure TCallStackWindow.ClearAll;
begin
CallStackView.Clear;
fCallStackList.Clear;
SelectedNode := nil;
end;
procedure TCallStackWindow.CallStackViewChange(Sender: TBaseVirtualTree;
Node: PVirtualNode);
begin
if Assigned(Node) and CallStackView.Selected[Node] and
(Node <> SelectedNode) then
begin
// Update the Variables Window
SelectedNode := Node;
if Assigned(VariablesWindow) then
VariablesWindow.UpdateWindow;
end;
end;
procedure TCallStackWindow.CallStackViewDblClick(Sender: TObject);
begin
if Assigned(SelectedNode) then
with PCallStackRec(CallStackView.GetNodeData(SelectedNode))^.FrameInfo do
if FileName <> '' then
PyIDEMainForm.ShowFilePosition(FileName, Line, 1);
end;
procedure TCallStackWindow.FormActivate(Sender: TObject);
begin
inherited;
if not HasFocus then begin
FGPanelEnter(Self);
PostMessage(CallStackView.Handle, WM_SETFOCUS, 0, 0);
end;
end;
procedure TCallStackWindow.TBMThemeChange(var Message: TMessage);
begin
inherited;
if Message.WParam = TSC_VIEWCHANGE then begin
CallStackView.Header.Invalidate(nil, True);
CallStackView.Colors.HeaderHotColor :=
CurrentTheme.GetItemTextColor(GetItemInfo('active'));
end;
end;
procedure TCallStackWindow.FormCreate(Sender: TObject);
begin
inherited;
fCallStackList := TObjectList.Create(True); // Onwns objects
// Let the tree know how much data space we need.
CallStackView.NodeDataSize := SizeOf(TCallStackRec);
CallStackView.OnAdvancedHeaderDraw :=
CommandsDataModule.VirtualStringTreeAdvancedHeaderDraw;
CallStackView.OnHeaderDrawQueryElements :=
CommandsDataModule.VirtualStringTreeDrawQueryElements;
end;
procedure TCallStackWindow.FormDestroy(Sender: TObject);
begin
fCallStackList.Free;
CallStackWindow := nil;
inherited;
end;
procedure TCallStackWindow.CallStackViewInitNode(Sender: TBaseVirtualTree;
ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
begin
Assert(CallStackView.GetNodeLevel(Node) = 0);
Assert(Integer(Node.Index) < fCallStackList.Count);
PCallStackRec(CallStackView.GetNodeData(Node))^.FrameInfo :=
fCallStackList[Node.Index] as TBaseFrameInfo;
end;
procedure TCallStackWindow.CallStackViewGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
begin
Assert(CallStackView.GetNodeLevel(Node) = 0);
Assert(Integer(Node.Index) < fCallStackList.Count);
with PCallStackRec(CallStackView.GetNodeData(Node))^.FrameInfo do
case Column of
0: CellText := FunctionName;
1: CellText := FileName;
2: if Line > 0
then CellText := IntToStr(Line)
else
CellText := '';
end;
end;
function TCallStackWindow.GetSelectedStackFrame: TBaseFrameInfo;
begin
Result := nil;
if Assigned(SelectedNode) then
Result :=
PCallStackRec(CallStackView.GetNodeData(SelectedNode))^.FrameInfo;
end;
end.
|
unit TestUTemplateDreVO;
interface
uses
TestFramework, SysUtils, Atributos, UCondominioVO, Generics.Collections, UGenericVO,
Classes, Constantes, UTemplateDreVO;
type
TestTTemplateDreVO = class(TTestCase)
strict private
FTemplateDreVO: TTemplateDreVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCamposObrigatorios;
procedure TestValidarCamposObrigatoriosErro;
end;
implementation
procedure TestTTemplateDreVO.SetUp;
begin
FTemplateDreVO := TTemplateDreVO.Create;
end;
procedure TestTTemplateDreVO.TearDown;
begin
FTemplateDreVO.Free;
FTemplateDreVO := nil;
end;
procedure TestTTemplateDreVO.TestValidarCamposObrigatorios;
var
TemplateDre: TTemplateDreVO;
begin
TemplateDre := TTemplateDreVO.Create;
TemplateDre.idTemplate:= StrToInt('1');
TemplateDre.Classificacao := '3.1';
TemplateDre.descricao := 'Receitas Operacionais';
TemplateDre.flTipo := '0';
TemplateDre.ordem := '1';
Try
TemplateDre.ValidarCamposObrigatorios;
check(true,'Sucesso');
except on E: Exception do
Check(false,'Erro');
end;
end;
procedure TestTTemplateDreVO.TestValidarCamposObrigatoriosErro;
var
TemplateDre: TTemplateDreVO;
begin
TemplateDre := TTemplateDreVO.Create;
TemplateDre.idTemplate:= StrToInt('1');
TemplateDre.Classificacao := '';
TemplateDre.descricao := 'Receitas Operacionais';
TemplateDre.flTipo := '0';
TemplateDre.ordem := '1';
Try
TemplateDre.ValidarCamposObrigatorios;
check(false,'Erro');
except on E: Exception do
Check(true,'Sucesso');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTTemplateDreVO.Suite);
end.
|
unit ufrmPopupDetailCashback;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
StdCtrls, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxLabel, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView,
cxGrid;
type
TfrmPopupDetailCashback = class(TForm)
pnl1: TPanel;
pnl2: TPanel;
pnl3: TPanel;
lblClose: TcxLabel;
cxGrid: TcxGrid;
cxGridView: TcxGridDBTableView;
cxlvMaster: TcxGridLevel;
cxcolTime: TcxGridDBColumn;
cxcolCard: TcxGridDBColumn;
cxcolTransaction: TcxGridDBColumn;
cxcolCashback: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure lblCloseClick(Sender: TObject);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
private
FBegBlcId : integer;
FUnitID : Integer;
procedure ParseHeaderGrid();
procedure ParseDataGrid();
public
{ Public declarations }
procedure ShowWithUserId(aUnitId: Integer; aBegBlcId: Integer);
end;
var
frmPopupDetailCashback: TfrmPopupDetailCashback;
implementation
{$R *.dfm}
const
_kolDateTime : Integer = 0;
_kolCardCode : Integer = 1;
_kolTransctNo : Integer = 2;
_kolCashBack : Integer = 3;
procedure TfrmPopupDetailCashback.ShowWithUserId(aUnitId: Integer; aBegBlcId:
Integer);
begin
FUnitId := aUnitId;
FbegBlcID := aBegBlcId;
// edtCashierID.Text := aCashierID;
// edtCashierNm.Text := aCashierNm;
// edtShift.Text := aShift;
ParseDataGrid;
Self.Show;
end;
procedure TfrmPopupDetailCashback.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmPopupDetailCashback.FormDestroy(Sender: TObject);
begin
frmPopupDetailCashback := nil;
end;
procedure TfrmPopupDetailCashback.ParseDataGrid;
var
sSQL : string;
// i, n : Integer;
begin
ParseHeaderGrid;
sSQL := 'select t.TRANS_DATE, CC.CARD_NAME, tc.TRANSC_TRANS_NO,'
+ ' tc.TRANSC_CHARGE + TRANSC_CASHBACK_CHARGE + tc.TRANSC_CASHBACK_NILAI'
+ ' from transaksi t '
+ ' inner join transaksi_card tc on tc.transc_trans_no = t.trans_no '
+ ' and tc.transc_trans_unt_id = t.trans_unt_id '
+ ' and t.trans_balance_id = ' + IntToStr(FBegBlcId)
+ ' and t.trans_balance_unt_id = ' + IntToStr(FUnitID)
+ ' and t.trans_bayar_card > 0 '
+ ' inner join ref$credit_card cc on cc.card_id = tc.transc_card_id '
+ ' and cc.card_unt_id = tc.transc_card_unt_id '
+ ' ORDER BY t.TRANS_DATE';
// + ' group by cc.card_is_credit ';
{
i := strgGrid.FixedRows;
n := 0;
with cOpenQuery(sSQL) do
begin
try
while not Eof do
begin
if n > 0 then
strgGrid.AddRow;
strgGrid.Cells[_kolDateTime, i + n] := FormatDateTime('HH:MM:SS', Fields[0].AsDateTime);
strgGrid.Cells[_kolCardCode, i + n] := Fields[1].AsString;
strgGrid.Cells[_kolTransctNo, i + n] := Fields[2].AsString;
strgGrid.Cells[_kolCashBack, i + n] := FloatToStr(Fields[3].asFloat);
Inc(n);
Next;
end;
finally
Free;
end;
end;
strgGrid.FloatingFooter.ColumnCalc[_kolCashBack] := acSUM;
strgGrid.AutoSize := True;
}
end;
procedure TfrmPopupDetailCashback.ParseHeaderGrid;
begin
{with strgGrid do
begin
Clear;
ColCount := 4;
RowCount := 3;
Cells[_kolDateTime,0] := 'TIME';
Cells[_kolCardCode,0] := 'CARD CODE';
Cells[_kolTransctNo,0] := 'TRANSACTION NO.';
Cells[_kolCashBack,0] := 'CASHBACK';
FixedRows := 1;
end;
}
end;
procedure TfrmPopupDetailCashback.lblCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPopupDetailCashback.strgGridGetFloatFormat(Sender: TObject;
ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
if ACol in [_kolDateTime.._kolTransctNo] then
IsFloat := False;
if IsFloat then
FloatFormat := '%.2n';
end;
end.
|
unit UDPrinter;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpePrinterDlg = class(TForm)
pnlPrinter1: TPanel;
lblPrinterNames: TLabel;
lblPrinterDriver: TLabel;
lblPrinterName: TLabel;
lblPrinterPort: TLabel;
lblPMode: TLabel;
lblMode: TLabel;
lbPrinterNames: TListBox;
editPrinterName: TEdit;
editPrinterDriver: TEdit;
editPrinterPort: TEdit;
editPrinterPMode: TEdit;
btnPrompt: TButton;
editPrinterMode: TEdit;
rgOrientation: TRadioGroup;
gbPreserveRpt: TGroupBox;
cbOrientation: TCheckBox;
cbPaperSize: TCheckBox;
cbPaperSource: TCheckBox;
btnOk: TButton;
btnCancel: TButton;
btnPrint: TButton;
btnClear: TButton;
btnRetrieve: TButton;
btnSend: TButton;
btnPrintOptions: TButton;
btnFreeDevMode: TButton;
cbProgressDialog: TCheckBox;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lbPrinterNamesClick(Sender: TObject);
procedure editPrinterNameChange(Sender: TObject);
procedure editPrinterDriverChange(Sender: TObject);
procedure editPrinterPortChange(Sender: TObject);
procedure btnPromptClick(Sender: TObject);
procedure rgOrientationClick(Sender: TObject);
procedure cbOrientationClick(Sender: TObject);
procedure cbPaperSizeClick(Sender: TObject);
procedure cbPaperSourceClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnRetrieveClick(Sender: TObject);
procedure UpdatePrinter;
procedure btnSendClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnPrintOptionsClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure btnFreeDevModeClick(Sender: TObject);
procedure cbProgressDialogClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rName : string;
rDriver : string;
rPort : string;
rIsNil : boolean;
rDevMode : TDevMode;
rOrientation : smallint;
rPrOrientation : boolean;
rPrPaperSize : boolean;
rPrPaperSource : boolean;
end;
var
CrpePrinterDlg: TCrpePrinterDlg;
bPrinter : boolean;
implementation
{$R *.DFM}
uses Printers, UCrpeUtl, UDPrintOptions;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.FormCreate(Sender: TObject);
begin
bPrinter := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
rName := '';
rDriver := '';
rPort := '';
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.FormShow(Sender: TObject);
begin
{Store Original Settings}
rName := Cr.Printer.Name;
rDriver := Cr.Printer.Driver;
rPort := Cr.Printer.Port;
{DevMode}
rIsNil := False;
if Cr.Printer.PMode <> nil then
CopyDevMode(Cr.Printer.PMode^, rDevMode)
else
rIsNil := True;
rOrientation := Ord(Cr.Printer.Orientation);
rPrOrientation := prOrientation in Cr.Printer.PreserveRptSettings;
rPrPaperSize := prPaperSize in Cr.Printer.PreserveRptSettings;
rPrPaperSource := prPaperSource in Cr.Printer.PreserveRptSettings;
cbProgressDialog.Checked := Cr.ProgressDialog;
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ UpdatePrinter procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.UpdatePrinter;
var
i : integer;
OnOff : Boolean;
begin
{Enable/Disable controls}
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
if OnOff then
begin
{SetUp Printer list}
Cr.Printer.GetPrinterNames(lbPrinterNames.Items);
i := lbPrinterNames.Items.IndexOf(Cr.Printer.Name);
if i > -1 then
lbPrinterNames.ItemIndex := i;
{Printer Name}
editPrinterName.Text := Cr.Printer.Name;
{Printer Driver}
editPrinterDriver.Text := Cr.Printer.Driver;
{Printer Port}
editPrinterPort.Text := Cr.Printer.Port;
{Printer PMode}
editPrinterPMode.Text := IntToStr(Integer(Cr.Printer.PMode));
{Printer Mode}
editPrinterMode.Text := IntToStr(Cr.Printer.Mode);
{Orientation}
rgOrientation.ItemIndex := Integer(Ord(Cr.Printer.Orientation));
{PreserveRptSettings}
cbOrientation.Checked := (prOrientation in Cr.Printer.PreserveRptSettings);
cbPaperSize.Checked := (prPaperSize in Cr.Printer.PreserveRptSettings);
cbPaperSource.Checked := (prPaperSource in Cr.Printer.PreserveRptSettings);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbProgressDialogClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.cbProgressDialogClick(Sender: TObject);
begin
Cr.ProgressDialog := cbProgressDialog.Checked;
end;
{------------------------------------------------------------------------------}
{ btnShowPrintDlgClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnPromptClick(Sender: TObject);
begin
if Cr.Printer.Prompt then
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ btnPrintOptionsClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnPrintOptionsClick(Sender: TObject);
begin
if not bPrintOptions then
begin
CrpePrintOptionsDlg := TCrpePrintOptionsDlg.Create(Application);
CrpePrintOptionsDlg.Cr := Cr;
end;
CrpePrintOptionsDlg.Show;
end;
{------------------------------------------------------------------------------}
{ lbPrinterNamesClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.lbPrinterNamesClick(Sender: TObject);
begin
Printer.PrinterIndex := lbPrinterNames.ItemIndex;
Cr.Printer.GetCurrent(False);
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ editPrinterNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.editPrinterNameChange(Sender: TObject);
begin
Cr.Printer.Name := editPrinterName.Text;
end;
{------------------------------------------------------------------------------}
{ editPrinterDriverChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.editPrinterDriverChange(Sender: TObject);
begin
Cr.Printer.Driver := editPrinterDriver.Text;
end;
{------------------------------------------------------------------------------}
{ editPrinterPortChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.editPrinterPortChange(Sender: TObject);
begin
Cr.Printer.Port := editPrinterPort.Text;
end;
{------------------------------------------------------------------------------}
{ rgOrientationClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.rgOrientationClick(Sender: TObject);
begin
Cr.Printer.Orientation := TCrOrientation(rgOrientation.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ cbOrientationClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.cbOrientationClick(Sender: TObject);
begin
if cbOrientation.Checked then
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings + [prOrientation]
else
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings - [prOrientation];
end;
{------------------------------------------------------------------------------}
{ cbPaperSizeClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.cbPaperSizeClick(Sender: TObject);
begin
if cbPaperSize.Checked then
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings + [prPaperSize]
else
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings - [prPaperSize];
end;
{------------------------------------------------------------------------------}
{ cbPaperSourceClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.cbPaperSourceClick(Sender: TObject);
begin
if cbPaperSource.Checked then
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings + [prPaperSource]
else
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings - [prPaperSource];
end;
{------------------------------------------------------------------------------}
{ btnRetrieveClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnRetrieveClick(Sender: TObject);
begin
Screen.Cursor := crHourglass;
try
Cr.Printer.Retrieve;
finally
Screen.Cursor := crDefault;
end;
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ btnSendClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnSendClick(Sender: TObject);
begin
Cr.Printer.Send;
end;
{------------------------------------------------------------------------------}
{ btnPrintClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnPrintClick(Sender: TObject);
var
prevOut : TCrOutput;
begin
{Preserve previous Output setting}
prevOut := Cr.Output;
try
Screen.Cursor := crHourglass;
Cr.Output := toPrinter;
Cr.Execute;
finally
Screen.Cursor := crDefault;
Cr.Output := prevOut;
end;
end;
{------------------------------------------------------------------------------}
{ btnFreeDevModeClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnFreeDevModeClick(Sender: TObject);
begin
Cr.Printer.FreeDevmode;
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnClearClick(Sender: TObject);
begin
Cr.Printer.Clear;
UpdatePrinter;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpePrinterDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrCancel then
begin
{Restore Original Settings}
Cr.Printer.Name := rName;
Cr.Printer.Driver := rDriver;
Cr.Printer.Port := rPort;
if not rIsNil then
CopyDevMode(rDevMode, Cr.Printer.PMode^)
else
Cr.Printer.PMode := nil;
Cr.Printer.Orientation := TCrOrientation(rOrientation);
Cr.Printer.PreserveRptSettings := [];
if rPrOrientation then
Cr.Printer.PreserveRptSettings := [prOrientation];
if rPrPaperSize then
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings + [prOrientation];
if rPrPaperSource then
Cr.Printer.PreserveRptSettings := Cr.Printer.PreserveRptSettings + [prPaperSource];
end;
bPrinter := False;
Release;
end;
end.
|
unit FontCtls;
{
Two controls for choosing installed fonts for Delphi 2, 32-bit.
Slight adjustments necessary for use under Delphi 1.
They show TTF, Type1 and bitmap fonts with individual bitmaps.
No more fuss with FontDialog!
Suggestions/improvements welcome.
-----------------------------------------------------------------------
Quality freeware from Sight&Sound, Slovenia : http://www.sight-sound.si
Version 1.0: release date 15.11.1996
}
interface
uses
Windows, Messages, Classes, Graphics, Controls, StdCtrls;
type
FontTypes = (PS, TTF, RASTER, UNKNOWN);
TFontClass = Class
FntName : String;
FntType : FontTypes;
Fixed : boolean;
End;
TFontStrList = Class(TStringList)
Destructor Destroy; Override;
End;
TBitmapArray = array [0..3] of TBitmap;
TFilterOption = (ShowTrueType, ShowPostScript, ShowRaster, ShowFixedOnly);
TFilterOptions = Set of TFilterOption;
EValidateFont = procedure (Sender: TObject; Font: TFontClass; var accept:Boolean) of object;
TFontListBox = Class(TCustomListBox)
private
{ Private declarations }
FFilterOptions : TFilterOptions;
FontStringList : TFontStrList;
FOnValidateFont : EValidateFont;
FBitmaps : TBitmapArray;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
protected
{ Protected declarations }
procedure CreateWnd; override;
procedure SetFilterOptions(Value : TFilterOptions);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
procedure ReBuild;
published
{ pusblish the TListBox properties }
property Align;
property BorderStyle;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property ExtendedSelect;
property FilterOptions: TFilterOptions
read FFilterOptions
write SetFilterOptions
default [ShowTrueType, ShowPostScript, ShowRaster];
property Font;
property IntegralHeight;
property ItemHeight;
property Items;
property MultiSelect;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabWidth;
property Visible;
{ pusblished the TListBox events }
property OnValidateFont:EValidateFont read FOnValidateFont write FOnValidateFont;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TFontComboBox = Class(TCustomComboBox)
private
{ Private declarations }
FFilterOptions : TFilterOptions;
FontStringList : TFontStrList;
FOnValidateFont : EValidateFont;
FBitmaps : TBitmapArray;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
protected
{ Protected declarations }
procedure CreateWnd; override;
procedure SetFilterOptions(Value : TFilterOptions);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
procedure ReBuild;
published
{ pusblish the TComboBox properties }
property Align;
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property DropDownCount;
property Enabled;
property FilterOptions: TFilterOptions
read FFilterOptions
write SetFilterOptions
default [ShowTrueType, ShowPostScript, ShowRaster];
property Font;
property ItemHeight;
property Items;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnValidateFont:EValidateFont read FOnValidateFont write FOnValidateFont;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnStartDrag;
end;
procedure Register;
{$R FONTSYMB.RES}
implementation
Destructor TFontStrList.Destroy;
(* User defined list destructor *)
Var
Temp : TObject;
Begin
While Count > 0 Do
Begin
Temp := Objects[0];
Temp.Free;
Delete(0);
End;
Inherited Destroy;
End;
function AddFontToList(Sender: TObject; FntClass : TFontClass):Boolean;
var
cont: Boolean;
begin
cont := true;
if Sender is TFontListBox then
with Sender as TFontListBox do
begin
if assigned(FOnValidateFont) then
FOnValidateFont(Sender,FntClass,cont);
if cont then
with FntClass do
if not ((ShowFixedOnly in FFilterOptions) and Fixed) then begin
Case FntType of
PS : if ShowPostScript in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
TTF : if ShowTrueType in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
RASTER : if ShowRaster in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
else
FontStringList.AddObject(FntName, FntClass);
end;
end;
end
else
with Sender as TFontComboBox do
begin
if assigned(FOnValidateFont) then
FOnValidateFont(Sender,FntClass,cont);
if cont then
with FntClass do
if not ((ShowFixedOnly in FFilterOptions) and Fixed) then begin
Case FntType of
PS : if ShowPostScript in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
TTF : if ShowTrueType in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
RASTER : if ShowRaster in FFilterOptions then
FontStringList.AddObject(FntName, fntClass);
else
FontStringList.AddObject(FntName, FntClass);
end;
end;
end;
Result := true;
end;
function EnumFontFamProc(var LogFont : TLogFont;
var TextMetric : TTextMetric;
FontType : Integer;
Data : Pointer): Integer; StdCall;
var
FontClass : TFontClass;
begin
FontClass := TFontClass.Create;
With FontClass Do
begin
FntName := LogFont.lfFaceName;
Case FontType of
1 : FntType := RASTER;
2 : FntType := PS;
4 : FntType := TTF;
else
FntType := UNKNOWN;
end;
Fixed:=(TextMetric.tmPitchAndFamily and TMPF_FIXED_PITCH)>0;
end;
result := 0;
if TObject(Data) is TFontListBox then
begin
if AddFontToList(TFontListBox(Data),FontClass) then
result := 1
else
result := 0;
end;
if TObject(Data) is TFontComboBox then
begin
if AddFontToList(TFontComboBox(Data),FontClass) then
result := 1
else
result := 0;
end
end;
procedure GetAllInstalledScreenFonts(Sender: TObject);
(* Returns list of all installed screen fonts *)
var
DC : HDC;
begin
DC := GetDC(0);
EnumFontFamilies(DC, nil, @EnumFontFamProc, LongInt(Pointer(Sender)));
ReleaseDC(0, DC);
end;
Constructor TFontListBox.Create(AOwner: TComponent);
var i : integer;
begin
inherited Create(AOwner);
Font.Name := 'MS Sans Serif';
Font.Size := 8;
Font.Style := Font.Style - [fsBold];
Sorted := True;
Style := lbOwnerDrawFixed;
ItemHeight := 16;
FontStringList := TFontStrList.Create;
FontStringList.Sorted := True;
FontStringList.Clear;
for i := 0 to 3 do
FBitmaps[i]:= TBitmap.Create;
FBitmaps[0].Handle := LoadBitmap(hinstance,'PS');
FBitmaps[1].Handle := LoadBitmap(hinstance,'TTF');
FBitmaps[2].Handle := LoadBitmap(hinstance,'RASTER');
FBitmaps[3].Handle := LoadBitmap(hinstance,'UNKNOWN');
FFilterOptions := [ShowTrueType, ShowPostScript, ShowRaster];
GetAllInstalledScreenFonts(Self);
end;
Constructor TFontComboBox.Create(AOwner: TComponent);
var i : integer;
begin
inherited Create(AOwner);
Font.Name := 'MS Sans Serif';
Font.Size := 8;
Font.Style := Font.Style - [fsBold];
Sorted := True;
Style := csOwnerDrawFixed;
ItemHeight := 16;
FontStringList := TFontStrList.Create;
FontStringList.Sorted := True;
FontStringList.Clear;
for i := 0 to 3 do
FBitmaps[i]:= TBitmap.Create;
FBitmaps[0].Handle := LoadBitmap(hinstance,'PS');
FBitmaps[1].Handle := LoadBitmap(hinstance,'TTF');
FBitmaps[2].Handle := LoadBitmap(hinstance,'RASTER');
FBitmaps[3].Handle := LoadBitmap(hinstance,'UNKNOWN');
FFilterOptions := [ShowTrueType, ShowPostScript, ShowRaster];
GetAllInstalledScreenFonts(Self);
end;
Destructor TFontListBox.Destroy;
var i : integer;
begin
for i := 0 to 3 do
FBitmaps[i].Free;
FontStringList.Destroy;
inherited Destroy;
end;
Destructor TFontComboBox.Destroy;
var i : integer;
begin
for i := 0 to 3 do
FBitmaps[i].Free;
FontStringList.Destroy;
inherited Destroy;
end;
procedure TFontListBox.CreateWnd;
begin
inherited CreateWnd;
Items.Assign(FontStringList);
ItemIndex := 0;
end;
procedure TFontComboBox.CreateWnd;
begin
inherited CreateWnd;
Items.Assign(FontStringList);
ItemIndex := 0;
end;
procedure TFontListBox.Rebuild;
begin
FontStringList.Clear;
GetAllInstalledScreenFonts(Self);
Items.Assign(FontStringList);
end;
procedure TFontComboBox.Rebuild;
begin
FontStringList.Clear;
GetAllInstalledScreenFonts(Self);
Items.Assign(FontStringList);
end;
procedure TFontListBox.SetFilterOptions(Value: TFilterOptions);
begin
if FFilterOptions <> Value then
begin
FFilterOptions := Value;
Rebuild;
end;
end;
procedure TFontComboBox.SetFilterOptions(Value: TFilterOptions);
begin
if FFilterOptions <> Value then
begin
FFilterOptions := Value;
Rebuild;
end;
end;
procedure TFontListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
tmpbitmap1,
tmpbitmap2 : TBitmap;
ARect,BRect : TRect;
TmpColor : TColor;
TmpFontClass : TFontClass;
begin
TmpFontClass := TFontClass(FontStringList.Objects[Index]);
tmpbitmap1 := TBitmap.Create;
tmpbitmap1.Assign(FBitmaps[ord(TmpFontClass.FntType)]);
if odSelected in State then
TmpColor := clHighLight
else
TmpColor := Color;
with arect do
begin
left := 0;
top := 0;
bottom := tmpbitmap1.Height;
right := tmpbitmap1.Width;
end;
Canvas.FillRect(Rect);
tmpbitmap2 := TBitmap.Create;
with tmpbitmap2, canvas do
begin
Height := tmpbitmap1.Height;
Width := tmpbitmap1.Width;
Brush.Color := TmpColor;
BrushCopy(ARect, tmpbitmap1, ARect, clWhite); // white is transparent in bitmap
end;
with brect do
begin
left := rect.left;
top := rect.top;
bottom := rect.bottom;
right := rect.bottom-rect.top;
end;
with canvas do
begin
copyrect(bRect, tmpbitmap2.Canvas, ARect);
TextOut(Rect.Left+brect.right+2, Rect.Top, TmpFontClass.FntName);
end;
tmpbitmap2.Free;
tmpbitmap1.Free;
end;
procedure TFontComboBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
tmpbitmap1,
tmpbitmap2 : TBitmap;
ARect,BRect : TRect;
TmpColor : TColor;
TmpFontClass : TFontClass;
begin
TmpFontClass := TFontClass(FontStringList.Objects[Index]);
tmpbitmap1 := TBitmap.Create;
tmpbitmap1.Assign(FBitmaps[ord(TmpFontClass.FntType)]);
if odSelected in State then
TmpColor := clHighLight
else
TmpColor := Color;
with arect do
begin
left := 0;
top := 0;
bottom := tmpbitmap1.Height;
right := tmpbitmap1.Width;
end;
Canvas.FillRect(Rect);
tmpbitmap2 := TBitmap.Create;
with tmpbitmap2, canvas do
begin
Height := tmpbitmap1.Height;
Width := tmpbitmap1.Width;
Brush.Color := TmpColor;
BrushCopy(ARect, tmpbitmap1, ARect, clWhite); // white is transparent in bitmap
end;
with brect do
begin
left := rect.left;
top := rect.top;
bottom := rect.bottom;
right := rect.bottom-rect.top+rect.left;
end;
with canvas do
begin
copyrect(bRect, tmpbitmap2.Canvas, ARect);
TextOut(Rect.Left+brect.right+2, Rect.Top, TmpFontClass.FntName);
end;
tmpbitmap2.Free;
tmpbitmap1.Free;
end;
procedure TFontListBox.CMFontChanged(var Message: TMessage);
begin
Canvas.Font := Font;
ItemHeight := Canvas.TextHeight(' ');
inherited;
end;
procedure TFontComboBox.CMFontChanged(var Message: TMessage);
begin
Style := csDropDownList;
inherited;
ItemHeight := ItemHeight;
Style := csOwnerDrawFixed;
end;
procedure Register;
begin
RegisterComponents('ConTEXT Components', [TFontListBox,TFontComboBox]);
end;
end.
|
unit EanDB;
interface
{$I ean.inc}
uses EanKod,
{$ifdef PSOFT_CLX}
QDBCtrls, QControls,
{$else}
Messages, DB,DbTables,DbCtrls, Controls,
{$endif}
Classes ;
type
TDBEan = class(TEan)
private
FDataLink: TFieldDataLink;
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
procedure SetDataField(const Value: string);
procedure SetDataSource(Value: TDataSource);
protected
procedure DataChange(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Field: TField read GetField;
published
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
implementation
constructor TDBEan.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataLink := TFieldDataLink.Create;
FDataLink.Control := Self;
FDataLink.OnDataChange := DataChange;
end;
destructor TDBEan.Destroy;
begin
FDataLink.OnDataChange := nil;
FDataLink.Free;
inherited Destroy;
end;
function TDBEan.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TDBEan.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource := Value;
end;
function TDBEan.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
procedure TDBEan.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
function TDBEan.GetField: TField;
begin
Result := FDataLink.Field;
end;
procedure TDBEan.DataChange(Sender: TObject);
begin
if FDataLink.Field<>nil then
BarCode:= FDataLink.Field.AsString;
end;
end.
|
unit FuncionarioDAO;
interface
uses
InterfaceFuncionarioModel;
type
TFuncionarioDAO = class(TObject)
public
class constructor Create();
class destructor Destroy();
function ObterFuncionarioPorNome(const pNome: String): IFuncionarioModel;
end;
implementation
uses
System.Generics.Collections, FuncionarioComissionadoModel,
FuncionarioAssalariadoModel, FuncionarioAssalariadoComComissaoModel;
var
FFuncionarios: TList<IFuncionarioModel>;
{ TFuncionarioDAO }
class constructor TFuncionarioDAO.Create;
begin
FFuncionarios := TList<IFuncionarioModel>.Create();
FFuncionarios.Add(TFuncionarioComissionadoModel.Create('Fulano da Silva', 5.5));
FFuncionarios.Add(TFuncionarioAssalariadoModel.Create('Beutrano Inácio', 1250.33));
FFuncionarios.Add(TFuncionarioAssalariadoComComissaoModel.Create('Cicrano Sauro', 1250.33, 2.3));
end;
class destructor TFuncionarioDAO.Destroy;
begin
FFuncionarios.Free();
end;
function TFuncionarioDAO.ObterFuncionarioPorNome(const pNome: String): IFuncionarioModel;
begin
for var i: Integer := 0 to FFuncionarios.Count -1 do
begin
if (FFuncionarios[i].Nome = pNome) then
Exit(FFuncionarios[i]);
end;
end;
end.
|
unit ABCNET_Time;
interface
uses
Global;
function SortingTime(Sort: TProc): longint;
implementation
uses
Utils, ArContain;
{*Функція SortTime.
*Викликає процедуру Sort для масиву А (оголошеного в Global) і вимірює
*конкретний час її виконання;
*ОТРИМУЄ: процедуру Sort типу TProc;
*ПОВЕРТАЄ: кількість затрачених на виконання процедури мілісекунд у вигляді
*цілого беззнакового типу Word;}
function SortTime(Sort: TProc): longint;
var
T1, T2: longint;
begin
T1 := Milliseconds; {Записує в змінну T1 час з початку виконнаня програми}
Sort(A); {Виконується сортування}
T2 := Milliseconds; {Записує в змінну T2 час з початку виконнаня програи}
SortTime := T2 - T1; {Повертає час виконання сортування}
end;
{*Функція ABCNETSortTime.
*Для врахування похибки рекомендується виконувати
вимірювання часу для кожного випадку 14 разів, перші два
значення відкинути, після цього відкинути максимальне та
мінімальне з 12 значень, що залишились, і
записати середнє арифметичне значення з решти;
*ОТРИМУЄ: процедуру Sort типу TProc;
*ПОВЕРТАЄ: середнє арифметичне значення затрачених на виконання процедури Sort
*в мілісекунд у вигляді цілого беззнакового типу Word}
function SortingTime(Sort: TProc): longint;
var
Znacenia: array [1..count] of longint;
i, min, max: word;
begin
Znacenia[1] := SortTime(Sort);
Znacenia[1] := SortTime(Sort); {Перші два значення відкидаються}
for i := 1 to count do {Записує в масив значення часу сортування }
Znacenia[i] := SortTime(Sort);
min := 1;
max := 1;
for i := 2 to count do
begin
if Znacenia[i] < Znacenia[min] then
min := i {Знаходить індекси мінімального та максимального часу сортування}
else
if Znacenia[i] > Znacenia[max] then
max := i;
end;
Znacenia[min] := 0; {Видаляє мінімальне та максимальне значення}
Znacenia[max] := 0;
for i := 2 to count do {Записує суму всіх значень в першу комірку}
Znacenia[1] := Znacenia[1] + Znacenia[i];
SortingTime := Znacenia[1] div (Count - 2); {Повертає середнє значення}
end;
end. |
unit pkcs11_object;
interface
uses
pkcs11t,
pkcs11_api,
pkcs11_attribute;
type
TPKCS11Object = class(TPKCS11API)
private
function GetSize(): integer;
public
FSessionHandle: CK_SESSION_HANDLE;
FHandle: CK_OBJECT_HANDLE;
property Size: integer read GetSize;
// Note: *Caller* is responsible for freeing returned attribute object
function GetAttribute(attrType: CK_ATTRIBUTE_TYPE): TPKCS11Attribute;
function SetAttribute(attrObj: TPKCS11Attribute): boolean;
end;
TPKCS11ObjectArray = array of TPKCS11Object;
implementation
// Returns -1 on failure
function TPKCS11Object.GetSize(): integer;
var
ulSize: CK_ULONG;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetObjectSize, FN_NAME_C_GetObjectSize);
Result := -1;
LastRV := LibraryFunctionList.CK_C_GetObjectSize(FSessionHandle, FHandle, @ulSize);
if RVSuccess(LastRV) then Result := ulSize;
end;
// Important: It is the CALLERS responsibility to free off the object returned
function TPKCS11Object.GetAttribute(attrType: CK_ATTRIBUTE_TYPE): TPKCS11Attribute;
const
BUFFER_SIZE = 1024;
var
attrStruct: CK_ATTRIBUTE;
bufferStr: string;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_GetAttributeValue, FN_NAME_C_GetAttributeValue);
Result := nil;
// Get attribute size (if attr present)
attrStruct.attrType := attrType;
attrStruct.pValue := nil;
attrStruct.ulValueLen := 0;
LastRV := LibraryFunctionList.CK_C_GetAttributeValue(
FSessionHandle,
FHandle,
@attrStruct,
1
);
if (
RVSuccess(LastRV) and
(CK_LONG(attrStruct.ulValueLen) > -1)
) then
begin
// Get attribute value
bufferStr := StringOfChar(#0, attrStruct.ulValueLen);
attrStruct.pValue := PChar(bufferStr);
LastRV := LibraryFunctionList.CK_C_GetAttributeValue(
FSessionHandle,
FHandle,
@attrStruct,
1
);
if RVSuccess(LastRV) then
begin
Result := TPKCS11Attribute.Create();
Result.LibraryFunctionList := LibraryFunctionList;
Result.AttrStruct := attrStruct;
end;
end;
end;
function TPKCS11Object.SetAttribute(attrObj: TPKCS11Attribute): boolean;
var
attrStruct: CK_ATTRIBUTE;
bufferStr: AnsiString;
begin
CheckFnAvailable(@LibraryFunctionList.CK_C_SetAttributeValue, FN_NAME_C_SetAttributeValue);
bufferStr := attrObj.ValueAsRawData;
attrStruct.attrType := attrObj.AttribType;
attrStruct.pValue := PAnsiChar(bufferStr);
attrStruct.ulValueLen := length(bufferStr);
LastRV := LibraryFunctionList.CK_C_SetAttributeValue(
FSessionHandle,
FHandle,
@attrStruct,
1
);
Result := RVSuccess(LastRV);
end;
END.
|
unit Roles;
{$mode objfpc}{$H+}
interface
uses DecConsts,Field;
type
TRoleFunc=procedure(num: integer);
//TODO:TAC create a new role for a second atacker to receive a pass at corner kicks
type
TRole=(roleIdle,
roleKeeper, roleKeeperDefendPenalty, roleKeeperPassive,
roleAtackerKicker, roleAtackerReceiver, roleReceivePass,
roleMamao, roleGoSearch1, roleGoSearch2, roleGoSearch3, roleGoSearch4,
roleAtackerSupporter,
roleLastDefender, roleOtherDefender, roleRoundLastDefender, roleRoundOtherDefender,
roleFreeKick,
roleKickOff,
rolePenaltyKick, roleScorePenaltyKick,
roleStayBack,
roleBarrierMain, roleBarrierAux, roleBarrierInterceptor,
roleWaitForKickOff,
roleRobotRobotDefender, roleDefend3,
roleTest, roleWingmanL, roleWingmanR ,
roleWaitForFreeKick,
roleWaitToThrowIn, roleThrowIn,
roleWaitForCornerKick, roleCornerKick,
roleWaitOurGoalKick,
roleWaitDroppedBall,
roleMidfield,
roleMidOfMidfield,roleMidOfMidfieldRight,roleMidOfMidfieldLeft,roleGoPosStart,
roleGoPosStop,
roleNavigateToLocalize,
roleFurtiveAtackerKicker,
//TIAGO TESE
roleGoSearch,
roleGoSearchFollower,
roleDoFormation
);
type
TRoleDef = record
name: string;
func: TRoleFunc;
is_keeper_role: boolean;
end;
var
deltadist,deltateta:double;
procedure RoleIdleRules(num: integer);
procedure RoleGoPosStartRules(num: integer);
procedure RoleGoPosStopRules(num: integer);
procedure RoleKeeperRules(num: integer);
procedure RoleKeeperDefendPenaltyRules(num: integer);
procedure RoleKeeperPassiveRules(num: integer);
procedure roleAtackerKickerRules(num: integer);
procedure roleAtackerKicker2Rules(num: integer);
procedure roleAtackerReceiverRules(num: integer);
procedure roleReceivePassRules(num: integer);
procedure roleLastDefenderRules(num: integer);
procedure RoleFreeKickRules(num: integer);
procedure RoleKickOffRules(num: integer);
procedure RolePenaltyKickRules(num: integer);
procedure RoleScorePenaltyKickRules(num: integer);
procedure RoleStayBackRules(num: integer);
procedure RoleMamaoRules(num: integer);
procedure RoleGoSearchRules1(num: integer);
procedure RoleGoSearchRules2(num: integer);
procedure RoleGoSearchRules3(num: integer);
procedure RoleGoSearchRules4(num: integer);
procedure roleBarrierMainRules(num: integer);
procedure roleWaitForKickOffRules(num: integer);
procedure RoleWaitForFreeKickRules(num: integer);
procedure RoleWaitToThrowInRules(num: integer);
procedure RoleThrowInRules(num: integer);
procedure RoleWaitForCornerKickRules(num: integer);
procedure RoleCornerKickRules(num: integer);
procedure RoleWaitOurGoalLickRules(num: integer);
procedure RoleOurGoalLickRules(num: integer);
procedure RoleWaitDroppedBallRules(num:integer);
procedure RoleMidfieldRules(num: integer);
procedure RoleMidOfMidfieldRules(num: integer);
procedure RoleMidOfMidfieldRightRules(num: integer);
procedure RoleMidOfMidfieldLeftRules(num: integer);
procedure RoleNavigateToLocalizeRules(num:integer);
procedure RoleFurtiveAtackerKickerRules(num:integer);
//////
procedure roleOtherDefenderRules(num: integer);
procedure RoleRoundLastDefenderRules(num: integer);
procedure RoleRoundOtherDefenderRules(num: integer);
procedure RoleAtackerSupporterRules(num: integer);
procedure roleBarrierAuxRules(num: integer);
procedure roleBarrierInterceptorRules(num: integer);
procedure roleRobotRobotDefenderRules(num: integer);
procedure RoleDefend3Rules(num: integer);
procedure RoleWingmanRRules(num: integer);
procedure RoleWingmanLRules(num: integer);
//TIAGO TESE
procedure RoleTestRules(num: integer);
procedure RoleDoFormationRules(num: integer);
procedure RoleGoSearchRules(num: integer);
procedure RoleGoSearchFollowerRules(num: integer);
const
RoleDefs: array[low(TRole) .. High(TRole)] of TRoleDef = (
( name:'roleIdle'; func: @RoleIdleRules ),
( name:'roleKeeper'; func: @RoleKeeperRules; is_keeper_role:true ),
( name:'roleKeeperDefendPenalty'; func: @roleKeeperDefendPenaltyRules; is_keeper_role:true ),
( name:'roleKeeperPassive'; func: @roleKeeperPassiveRules; is_keeper_role:true ),
( name:'roleAtackerKicker'; func: @roleAtackerKickerRules ),
( name:'roleAtackerReceiver'; func: @roleAtackerReceiverRules ),
( name:'roleReceivePass'; func: @roleReceivePassRules ),
( name:'roleMamao'; func: @roleMamaoRules ),
( name:'roleGoSearch1'; func: @roleGoSearchRules1 ),
( name:'roleGoSearch2'; func: @roleGoSearchRules2 ),
( name:'roleGoSearch3'; func: @roleGoSearchRules3 ),
( name:'roleGoSearch4'; func: @roleGoSearchRules4 ),
( name:'roleAtackerSupporter'; func: @roleAtackerSupporterRules ),
( name:'roleLastDefender'; func: @roleLastDefenderRules ),
( name:'roleOtherDefender'; func: @roleOtherDefenderRules ),
( name:'roleRoundLastDefender'; func: @roleRoundLastDefenderRules ),
( name:'roleRoundOtherDefender'; func: @roleRoundOtherDefenderRules ),
( name:'roleFreeKick'; func: @roleFreeKickRules ),
( name:'roleKickOff'; func: @roleKickOffRules ),
( name:'rolePenaltyKick'; func: @rolePenaltyKickRules ),
( name:'roleScorePenaltyKick'; func: @roleScorePenaltyKickRules ),
( name:'roleStayBack'; func: @roleStayBackRules ),
( name:'roleBarrierMain'; func: @roleBarrierMainRules ),
( name:'roleBarrierAux'; func: @roleBarrierAuxRules ),
( name:'roleBarrierInterceptor'; func: @roleBarrierInterceptorRules ),
( name:'roleWaitForKickOff'; func: @roleWaitForKickOffRules ),
( name:'roleRobotRobotDefender'; func: @roleRobotRobotDefenderRules ),
( name:'roleDefend3'; func: @roleDefend3Rules ),
( name:'roleTest'; func: @roleTestRules ),
( name:'roleWingmanR'; func: @roleWingmanRRules ),
( name:'roleWingmanL'; func: @roleWingmanLRules ),
( name:'roleWaitForFreeKick'; func: @roleWaitForFreeKickRules ),
( name:'roleWaitToThrowIn'; func: @roleWaitToThrowInRules ),
( name:'roleThrowIn'; func: @roleThrowInRules ),
( name:'roleWaitForCornerKick'; func: @roleWaitForCornerKickRules ),
( name:'roleCornerKick'; func: @roleCornerKickRules ),
( name:'roleWaitOurGoalKick'; func: @roleWaitOurGoalLickRules),
( name:'roleWaitDroppedBall'; func: @RoleWaitDroppedBallRules),
( name:'RoleMidfield'; func: @RoleMidfieldRules),
( name:'RoleMidOfMidfield'; func: @RoleMidOfMidfieldRules),
( name:'roleMidOfMidfieldLeft'; func: @RoleMidOfMidfieldLeftRules),
( name:'roleMidOfMidfieldRight'; func: @RoleMidOfMidfieldRightRules),
( name:'roleGoPosStart'; func: @RoleGoPosStartRules),
( name:'roleGoPosStop'; func: @RoleGoPosStopRules),
( name:'roleNavigateToLocalize'; func: @RoleNavigateToLocalizeRules),
( name:'roleFurtiveAtackerKicker'; func: @RoleFurtiveAtackerKickerRules),
//TIAGO TESE
( name:'roleGoSearchFollower'; func: @roleGoSearchFollowerRules ),
( name:'roleGoSearch'; func: @roleGoSearchRules ),
( name:'roleDoFormation'; func: @RoleDoFormationRules)
);
implementation
uses Coach, Tactic, Param, Utils{, Analyser}, Math, ObsAvoid;//, Unit_RolesAux;
//----------------------------------------------------------------------
// Role Rules
//----------------------------------------------------------------------
procedure RoleIdleRules(num: integer);
begin
end;
function BallNearCorner(c: double): boolean;
var ang: double;
begin
ang:=ATan2(Abs(BallState.y)-(-0.25),BallState.x-(-FieldLength*0.5));
result:=(Abs(BallState.y)>0.48-0.1*c) and (not (ang<0)) and (ang>(Pi/2-(30*Pi/180)*c));
end;
procedure RoleGoPosStartRules(num: integer);
begin
end;
procedure RoleGoPosStopRules(num: integer);
begin
end;
procedure RoleKeeperRules(num: integer);
begin
end;
procedure RoleKeeperDefendPenaltyRules(num: integer);
begin
end;
procedure RoleKeeperPassiveRules(num: integer);
begin
end;
procedure roleAtackerKicker2Rules(num: integer);
begin
end;
procedure roleAtackerKickerRules(num: integer);
begin
end;
procedure roleAtackerReceiverRules(num: integer);
begin
end;
procedure roleReceivePassRules(num: integer);
begin
end;
procedure roleLastDefenderRules(num: integer);
begin
end;
procedure roleOtherDefenderRules(num: integer);
begin
end;
procedure RoleRoundLastDefenderRules(num: integer);
begin
end;
procedure RoleRoundOtherDefenderRules(num: integer);
begin
end;
procedure RoleFreeKickRules(num: integer);
begin
end;
procedure RoleWaitForKickOffRules(num: integer);
begin
end;
procedure roleRobotRobotDefenderRules(num: integer);
begin
end;
procedure RoleScorePenaltyKickRules(num: integer);
begin
end;
procedure RolePenaltyKickRules(num: integer);
begin
end;
procedure RoleStayBackRules(num: integer);
begin
end;
procedure RoleMamaoRules(num: integer);
begin
end;
procedure RoleGoSearchRules1(num: integer);
begin
end;
procedure RoleGoSearchRules2(num: integer);
begin
end;
procedure RoleGoSearchRules3(num: integer);
begin
end;
procedure RoleGoSearchRules4(num: integer);
begin
end;
procedure RoleMamao2Rules(num: integer);
begin
end;
procedure RoleMidfieldRules(num: integer);
begin
end;
procedure RoleMidOfMidfieldRules(num: integer);
begin
end;
procedure RoleMidOfMidfieldRightRules(num: integer);
begin
end;
procedure RoleMidOfMidfieldLeftRules(num: integer);
begin
end;
procedure RoleNavigateToLocalizeRules(num: integer);
begin
end;
procedure RoleFurtiveAtackerKickerRules(num: integer);
begin
end;
procedure RoleAtackerSupporterRules(num: integer);
begin
end;
procedure RoleKickOffRules(num: integer);
begin
end;
procedure roleBarrierMainRules(num: integer);
begin
end;
procedure roleBarrierAuxRules(num: integer);
begin
end;
procedure roleBarrierInterceptorRules(num: integer);
begin
end;
procedure RoleAtacker2Rules(num: integer);
begin
end;
procedure RoleDefend3Rules(num: integer);
begin
end;
procedure RoleUnderStressRules(num: integer);
begin
end;
procedure RoleWingmanRRules(num: integer);
begin
end;
procedure RoleWingmanLRules(num: integer);
begin
end;
//Tiago Tese
procedure RoleTestRules(num: integer);
begin
end;
procedure RoleGoSearchFollowerRules(num: integer);
begin
end;
procedure RoleGoSearchRules(num: integer);
begin
end;
procedure RoleDoFormationRules(num: integer);
begin
end;
/////// End Tiago
procedure RoleWaitForFreeKickRules(num: integer);
begin
end;
procedure RoleWaitToThrowInRules(num: integer);
begin
end;
procedure RoleThrowInRules(num: integer);
begin
end;
procedure RoleWaitForCornerKickRules(num: integer);
begin
end;
procedure RoleCornerKickRules(num: integer);
begin
end;
procedure RoleWaitOurGoalLickRules(num: integer);
begin
end;
procedure RoleOurGoalLickRules(num: integer);
begin
end;
procedure RoleWaitDroppedBallRules(num: integer);
begin
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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 DPM.Console.Command.Info;
interface
uses
VSoft.CancellationToken,
DPM.Console.Writer,
DPM.Console.ExitCodes,
DPM.Console.Command,
DPM.Console.Command.Base,
DPM.Core.Configuration.Interfaces,
DPM.Core.Logging;
type
TInfoCommand = class(TBaseCommand)
private
//FConsole : IConsoleWriter;
protected
function Execute(const cancellationToken : ICancellationToken) : TExitCode; override;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager);reintroduce;
end;
implementation
uses
DPM.Console.Banner,
DPM.Core.Options.Common,
DPM.Core.Options.Info;
constructor TInfoCommand.Create(const logger: ILogger; const configurationManager: IConfigurationManager);
begin
inherited Create(logger, configurationManager);
end;
function TInfoCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode;
begin
TInfoOptions.Default.ApplyCommon(TCommonOptions.Default);
Logger.Information('DPM Config file : ' + TInfoOptions.Default.ConfigFile);
result := TExitCode.OK;
end;
end.
|
unit CFDateRang;
interface
uses
Windows, Classes, Controls, Graphics, Messages, CFControl, CFDateTimePicker,
CFPopupForm, CFCombobox, CFButton;
type
TRangCombobox = class(TCFCombobox);
TRangButton = class(TCFButton);
TDROwnerControl = class(TCFCustomControl)
protected
procedure DrawControl(ACanvas: TCanvas); override;
end;
TOnSelectDateTime = procedure(const ABeginDT, AEndDT: TDateTime) of object;
TRangPopup = class(TCFPopupForm)
private
FControlOwner: TDROwnerControl;
FSplitSize: Byte;
FMouseControl: TCFCustomControl;
FButton: TRangButton;
FYearComBox, FMonthComBox: TRangCombobox;
FOnSelectDateTime: TOnSelectDateTime;
procedure DoOnButtonClick(Sender: TObject);
procedure DoOnComboxCloseUp(const AItemIndex, AItemX, AItemY: Integer; var ACanCloseUp: Boolean);
procedure DoOnPopupClose(Sender: TObject);
protected
procedure Popup(const AControl: TControl); overload; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnSelectDateTime: TOnSelectDateTime read FOnSelectDateTime write FOnSelectDateTime;
end;
TPicker = class(TCFDateTimePicker);
TBeginPicker = class(TPicker)
protected
procedure DrawControl(ACanvas: TCanvas); override;
end;
TEndPicker = class(TPicker)
protected
procedure DrawControl(ACanvas: TCanvas); override;
end;
TCFDateRang = class(TCFTextControl)
private
FFocus: Boolean;
FSplitWidth: Byte;
FBeginPicker: TBeginPicker;
FEndPicker: TEndPicker;
procedure CalcPickerPosition;
procedure PopupRangSelect;
procedure DoOnPopupSelectDateTime(const ABeginDT, AEndDT: TDateTime);
protected
procedure DrawControl(ACanvas: TCanvas); override;
procedure AdjustBounds; override;
function GetBeginDate: TDateTime;
function GetEndDate: TDateTime;
function GetFormat: string;
procedure SetFormat(Value: string);
function GetReadOnly: Boolean;
procedure SetReadOnly(Value: Boolean);
function GetButtonVisible: Boolean;
procedure SetButtonVisible(Value: Boolean);
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE;
//
procedure WMCLBUTTONDOWN(var Message: TMessage); message WM_CF_LBUTTONDOWN;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property BeginDateTime: TDateTime read GetBeginDate;
property EndDateTime: TDateTime read GetEndDate;
published
property Format: string read GetFormat write SetFormat;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property ButtonVisible: Boolean read GetButtonVisible write SetButtonVisible;
end;
implementation
uses
SysUtils, DateUtils;
const
StartYear = 2019;
EndYear = 2099;
{ TCFDateRang }
procedure TCFDateRang.AdjustBounds;
var
vDC: HDC;
vWidth, vHeight: Integer;
begin
vDC := GetDC(0);
try
Canvas.Handle := vDC;
Canvas.Font := Font;
vWidth := Canvas.TextWidth(FormatDateTime('YYYY-MM-DD', Now)) * 2 + FSplitWidth + GetSystemMetrics(SM_CYBORDER) * 2;
if vWidth < Width then
vWidth := Width;
vHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth;;
if vHeight < Height then
vHeight := Height;
Canvas.Handle := 0;
finally
ReleaseDC(0, vDC);
end;
SetBounds(Left, Top, vWidth, vHeight);
end;
procedure TCFDateRang.CalcPickerPosition;
begin
if (not Assigned(FBeginPicker)) or (not Assigned(FEndPicker)) then Exit;
FBeginPicker.Left := 0;
FBeginPicker.Top := 0;
FEndPicker.Left := FBeginPicker.Left + FBeginPicker.Width + GetSystemMetrics(SM_CYBORDER) * 2 + FSplitWidth;
FEndPicker.Top := 0;
end;
procedure TCFDateRang.CMMouseEnter(var Msg: TMessage);
begin
inherited;
UpdateDirectUI
end;
procedure TCFDateRang.CMMouseLeave(var Msg: TMessage);
begin
inherited;
UpdateDirectUI;
end;
constructor TCFDateRang.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSplitWidth := 16;
FBeginPicker := TBeginPicker.Create(Self);
FBeginPicker.Parent := Self;
FEndPicker := TEndPicker.Create(Self);
FEndPicker.Parent := Self;
SetFormat('YYYY-MM-DD');
Width := FBeginPicker.Width * 2 + FSplitWidth + GetSystemMetrics(SM_CYBORDER) * 2;
Height := FBeginPicker.Height;
end;
destructor TCFDateRang.Destroy;
begin
FBeginPicker.Free;
FEndPicker.Free;
inherited;
end;
procedure TCFDateRang.DoOnPopupSelectDateTime(const ABeginDT, AEndDT: TDateTime);
begin
BeginUpdate;
try
FBeginPicker.DateTime := ABeginDT;
FEndPicker.DateTime := AEndDT;
finally
EndUpdate;
end;
end;
procedure TCFDateRang.DrawControl(ACanvas: TCanvas);
var
vRect: TRect;
begin
inherited DrawControl(ACanvas);
// 外观,圆角矩形
vRect := Rect(0, 0, Width, Height);
ACanvas.Brush.Style := bsSolid;
if ReadOnly then
ACanvas.Brush.Color := GReadOlnyBackColor;
if BorderVisible then
begin
if FFocus or (cmsMouseIn in MouseState) then
ACanvas.Pen.Color := GBorderHotColor
else
ACanvas.Pen.Color := GBorderColor;
ACanvas.Pen.Width := GBorderWidth;
ACanvas.Pen.Style := psSolid;
end
else
ACanvas.Pen.Style := psClear;
if RoundCorner > 0 then
ACanvas.RoundRect(vRect, GRoundSize, GRoundSize)
else
ACanvas.Rectangle(vRect);
ACanvas.Brush.Color := GLineColor;
if MouseState <> [] then
begin
vRect := Bounds(FBeginPicker.Left + FBeginPicker.Width + GetSystemMetrics(SM_CYBORDER) + 4, (Height div 2) - 1,
2, 2);
ACanvas.FillRect(vRect);
vRect.Offset(4, 0);
ACanvas.FillRect(vRect);
vRect.Offset(4, 0);
ACanvas.FillRect(vRect);
end
else
ACanvas.FillRect(Bounds(FBeginPicker.Left + FBeginPicker.Width + GetSystemMetrics(SM_CYBORDER), Height div 2,
FSplitWidth, 1));
end;
function TCFDateRang.GetBeginDate: TDateTime;
begin
Result := FBeginPicker.DateTime;
end;
function TCFDateRang.GetButtonVisible: Boolean;
begin
Result := FBeginPicker.ButtonVisible;
end;
function TCFDateRang.GetEndDate: TDateTime;
begin
Result := FEndPicker.DateTime;
end;
function TCFDateRang.GetFormat: string;
begin
Result := FBeginPicker.Format;
end;
function TCFDateRang.GetReadOnly: Boolean;
begin
Result := FBeginPicker.ReadOnly;
end;
procedure TCFDateRang.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if (X > FBeginPicker.BoundsRect.Right) and (X < FEndPicker.BoundsRect.Left) then
PopupRangSelect;
end;
procedure TCFDateRang.PopupRangSelect;
var
vPopup: TRangPopup;
begin
vPopup := TRangPopup.Create(Self);
try
vPopup.OnSelectDateTime := DoOnPopupSelectDateTime;
vPopup.Alignment := taCenter;
vPopup.Popup(Self);
finally
vPopup.Free;
end;
end;
procedure TCFDateRang.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
vDC: HDC;
vWidth, vHeight: Integer;
begin
vDC := GetDC(0);
try
Canvas.Handle := vDC;
Canvas.Font := Font;
vWidth := Canvas.TextWidth(FormatDateTime('YYYY-MM-DD', Now)) * 2 + FSplitWidth + GetSystemMetrics(SM_CYBORDER) * 2;
if vWidth < AWidth then
vWidth := AWidth;
vHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth;;
if vHeight < AHeight then
vHeight := AHeight;
Canvas.Handle := 0;
finally
ReleaseDC(0, vDC);
end;
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
CalcPickerPosition;
end;
procedure TCFDateRang.SetButtonVisible(Value: Boolean);
begin
if FBeginPicker.ButtonVisible <> Value then
begin
BeginUpdate;
try
FBeginPicker.ButtonVisible := Value;
FEndPicker.ButtonVisible := Value;
CalcPickerPosition;
finally
EndUpdate;
end;
end;
end;
procedure TCFDateRang.SetFormat(Value: string);
begin
if FBeginPicker.Format <> Value then
begin
FBeginPicker.Format := Value;
FEndPicker.Format := Value;
UpdateDirectUI;
end;
end;
procedure TCFDateRang.SetReadOnly(Value: Boolean);
begin
if FBeginPicker.ReadOnly <> Value then
begin
FBeginPicker.ReadOnly := Value;
FEndPicker.ReadOnly := Value;
end;
end;
procedure TCFDateRang.WMCLBUTTONDOWN(var Message: TMessage);
//var
// vPopup: TCPopup;
begin
// vPopup := TCPopup.Create(Self);
// try
// vPopup.PopupControl := Self;
// //FPopup.OnDrawWindow := DoOnPopupDrawWindow;
// vPopup.SetSize(FBeginPicker.Width, 120);
// vPopup.Popup(Left, Top);
// finally
// vPopup.Free;
// end;
end;
{ TRangPopup }
constructor TRangPopup.Create(AOwner: TComponent);
var
i: Integer;
begin
inherited Create(AOwner);
FSplitSize := 5;
FControlOwner := TDROwnerControl.Create(nil);
FYearComBox := TRangCombobox.Create(Self);
//FYearComBox.Font.Size := 8;
FYearComBox.Style := csDropDownList;
FYearComBox.Left := FSplitSize;
FYearComBox.Top := FSplitSize;
FYearComBox.OnCloseUp := DoOnComboxCloseUp;
FYearComBox.Width := 100;
for i := StartYear to EndYear do
FYearComBox.Items.Add(IntToStr(i));
FYearComBox.ItemIndex := 0;
FYearComBox.Parent := FControlOwner;
FControlOwner.Width := FYearComBox.Width + FSplitSize * 2;
FMonthComBox := TRangCombobox.Create(Self);
//FMonthComBox.Font.Size := 8;
FMonthComBox.Style := csDropDownList;
FMonthComBox.Left := FYearComBox.Left;
FMonthComBox.Top := FYearComBox.Top + FYearComBox.Height + FSplitSize;
FMonthComBox.OnCloseUp := DoOnComboxCloseUp;
FMonthComBox.Width := 100;
FMonthComBox.Items.Add('上半年');
FMonthComBox.Items.Add('下半年');
for i := 1 to 4 do
FMonthComBox.Items.Add(IntToStr(i) + '季度');
for i := 1 to 12 do
FMonthComBox.Items.Add(IntToStr(i) + '月');
FMonthComBox.ItemIndex := 0;
FMonthComBox.Parent := FControlOwner;
FButton := TRangButton.Create(Self);
FButton.ParentFont := False;
FButton.ModalResult := mrOk;
FControlOwner.Height := FYearComBox.Height * 2 + FButton.Height + FSplitSize * 4;
FButton.Left := (FControlOwner.Width - FButton.Width) div 2;
FButton.Top := FMonthComBox.Top + FMonthComBox.Height + FSplitSize;
FButton.OnClick := DoOnButtonClick;
FButton.Parent := FControlOwner;
//
OnPopupClose := DoOnPopupClose;
FControlOwner.Parent := (AOwner as TWinControl);
Self.PopupControl := FControlOwner;
end;
destructor TRangPopup.Destroy;
begin
FYearComBox.Free;
FMonthComBox.Free;
FButton.Free;
FControlOwner.Free;
inherited;
end;
procedure TRangPopup.DoOnButtonClick(Sender: TObject);
begin
ClosePopup(False);
end;
procedure TRangPopup.DoOnComboxCloseUp(const AItemIndex, AItemX,
AItemY: Integer; var ACanCloseUp: Boolean);
begin
UpdatePopup;
end;
procedure TRangPopup.DoOnPopupClose(Sender: TObject);
var
vBegDT, vEndDT: TDateTime;
vYear: Word;
begin
if Assigned(FOnSelectDateTime) then
begin
vYear := FYearComBox.ItemIndex + StartYear;
case FMonthComBox.ItemIndex of
0: // 上半年
begin
vBegDT := StartOfAMonth(vYear, 1);
vEndDT := EndOfAMonth(vYear, 6);
end;
1: // 下半年
begin
vBegDT := StartOfAMonth(vYear, 7);
vEndDT := EndOfAMonth(vYear, 12);
end;
2: // 1季度
begin
vBegDT := StartOfAMonth(vYear, 1);
vEndDT := EndOfAMonth(vYear, 3);
end;
3: // 2季度
begin
vBegDT := StartOfAMonth(vYear, 4);
vEndDT := EndOfAMonth(vYear, 6);
end;
4: // 3季度
begin
vBegDT := StartOfAMonth(vYear, 7);
vEndDT := EndOfAMonth(vYear, 9);
end;
5: // 4季度
begin
vBegDT := StartOfAMonth(vYear, 10);
vEndDT := EndOfAMonth(vYear, 12);
end;
6..17: // 1-12月
begin
vBegDT := StartOfAMonth(vYear, FMonthComBox.ItemIndex + 1);
vEndDT := EndOfAMonth(vYear, FMonthComBox.ItemIndex + 1);
end;
end;
FOnSelectDateTime(vBegDT, vEndDT);
end;
end;
procedure TRangPopup.Popup(const AControl: TControl);
begin
inherited;
end;
{ TDROwnerControl }
procedure TDROwnerControl.DrawControl(ACanvas: TCanvas);
begin
inherited;
ACanvas.Pen.Color := GBorderColor;
ACanvas.Rectangle(ClientRect);
end;
{ TBeginPicker }
procedure TBeginPicker.DrawControl(ACanvas: TCanvas);
begin
inherited DrawControl(ACanvas);
if Self.BorderVisible then
begin
ACanvas.Pen.Color := GBackColor;
ACanvas.MoveTo(Width - 1, BorderWidth + 1);
ACanvas.LineTo(Width - 1, Height - BorderWidth - 1);
ACanvas.MoveTo(Width - GIconWidth, BorderWidth + 1);
ACanvas.LineTo(Width - GIconWidth, Height - BorderWidth - 1);
end;
end;
{ TEndPicker }
procedure TEndPicker.DrawControl(ACanvas: TCanvas);
begin
inherited DrawControl(ACanvas);
if Self.BorderVisible then
begin
ACanvas.Pen.Color := GBackColor;
ACanvas.MoveTo(0, BorderWidth + 1);
ACanvas.LineTo(0, Height - BorderWidth - 1);
ACanvas.MoveTo(Width - GIconWidth, BorderWidth + 1);
ACanvas.LineTo(Width - GIconWidth, Height - BorderWidth - 1);
end;
end;
end.
|
unit uFrLicense;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
uInstallFrame,
uInstallUtils,
uTranslate,
uInstallZip,
uMemory,
uConstants;
type
TFrLicense = class(TInstallFrame)
MemLicense: TMemo;
CbAcceptLicenseAgreement: TCheckBox;
procedure CbAcceptLicenseAgreementClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Init; override;
procedure LoadLanguage; override;
function ValidateFrame : Boolean; override;
end;
implementation
{$R *.dfm}
{ TFrLicense }
procedure TFrLicense.CbAcceptLicenseAgreementClick(Sender: TObject);
begin
FrameChanged;
end;
procedure TFrLicense.Init;
var
MS : TMemoryStream;
LicenceFileName : string;
begin
inherited;
MS := TMemoryStream.Create;
try
LicenceFileName := Format('%s%s.txt', ['License', TTranslatemanager.Instance.Language]);
GetRCDATAResourceStream(SetupDataName, MS);
MemLicense.Text := ReadFileContent(MS, LicenceFileName);
finally
F(MS);
end;
end;
procedure TFrLicense.LoadLanguage;
begin
inherited;
CbAcceptLicenseAgreement.Caption := L('I accept license agreement');
end;
function TFrLicense.ValidateFrame: Boolean;
begin
Result := CbAcceptLicenseAgreement.Checked;
end;
end.
|
unit libvlc;
interface
uses
Windows, Dialogs, Classes, SysUtils, SyncObjs, Registry;
const
LIBVLC_ROOT = 'vizier';
LIBVLC_SNAPSHOTS = 'vizier\snapshots';
const
libvlc_MediaMetaChanged = 0;
libvlc_MediaSubItemAdded = 1;
libvlc_MediaDurationChanged = 2;
libvlc_MediaParsedChanged = 3;
libvlc_MediaFreed = 4;
libvlc_MediaStateChanged = 5;
libvlc_MediaSubItemTreeAdded = 6;
libvlc_MediaPlayerMediaChanged = $100;
libvlc_MediaPlayerNothingSpecial = $101;
libvlc_MediaPlayerOpening = $102;
libvlc_MediaPlayerBuffering = $103;
libvlc_MediaPlayerPlaying = $104;
libvlc_MediaPlayerPaused = $105;
libvlc_MediaPlayerStopped = $106;
libvlc_MediaPlayerForward = $107;
libvlc_MediaPlayerBackward = $108;
libvlc_MediaPlayerEndReached = $109;
libvlc_MediaPlayerEncounteredError = $10A;
libvlc_MediaPlayerTimeChanged = $10B;
libvlc_MediaPlayerPositionChanged = $10C;
libvlc_MediaPlayerSeekableChanged = $10D;
libvlc_MediaPlayerPausableChanged = $10E;
libvlc_MediaPlayerTitleChanged = $10F;
libvlc_MediaPlayerSnapshotTaken = $110;
libvlc_MediaPlayerLengthChanged = $111;
libvlc_MediaPlayerVout = $112;
libvlc_MediaPlayerScrambledChanged = $113;
libvlc_MediaPlayerESAdded = $114; // VLC 3.0.0
libvlc_MediaPlayerESDeleted = $115; // VLC 3.0.0
libvlc_MediaPlayerESSelected = $116; // VLC 3.0.0
libvlc_MediaPlayerCorked = $117;
libvlc_MediaPlayerUncorked = $118;
libvlc_MediaPlayerMuted = $119;
libvlc_MediaPlayerUnmuted = $11A;
libvlc_MediaPlayerAudioVolume = $11B;
libvlc_MediaPlayerAudioDevice = $11C; // VLC 3.0.0
libvlc_MediaPlayerChapterChanged = $11D; // VLC 3.0.0
libvlc_MediaListItemAdded = $200;
libvlc_MediaListWillAddItem = $201;
libvlc_MediaListItemDeleted = $202;
libvlc_MediaListWillDeleteItem = $203;
libvlc_MediaListEndReached = $204;
libvlc_MediaListViewItemAdded = $300;
libvlc_MediaListViewWillAddItem = $301;
libvlc_MediaListViewItemDeleted = $302;
libvlc_MediaListViewWillDeleteItem = $303;
libvlc_MediaListPlayerPlayed = $400;
libvlc_MediaListPlayerNextItemSet = $401;
libvlc_MediaListPlayerStopped = $402;
{$IFDEF USE_VLC_DEPRECATED_API}
libvlc_MediaDiscovererStarted = $500;
libvlc_MediaDiscovererEnded = $501;
{$ENDIF}
libvlc_RendererDiscovererItemAdded = $502;
libvlc_RendererDiscovererItemDeleted = $503;
libvlc_VlmMediaAdded = $600;
libvlc_VlmMediaRemoved = $601;
libvlc_VlmMediaChanged = $602;
libvlc_VlmMediaInstanceStarted = $603;
libvlc_VlmMediaInstanceStopped = $604;
libvlc_VlmMediaInstanceStatusInit = $605;
libvlc_VlmMediaInstanceStatusOpening = $606;
libvlc_VlmMediaInstanceStatusPlaying = $607;
libvlc_VlmMediaInstanceStatusPause = $608;
libvlc_VlmMediaInstanceStatusEnd = $609;
libvlc_VlmMediaInstanceStatusError = $60A;
type
plibvlc_instance_t = type Pointer;
plibvlc_media_player_t = type Pointer;
plibvlc_media_t = type Pointer;
plibvlc_event_manager_t = type Pointer;
plibvlc_event_type_t = type Integer;
type
libvlc_time_t_ptr = ^libvlc_time_t;
libvlc_time_t = Int64;
type
libvlc_state_t = (
libvlc_NothingSpecial, // 0,
libvlc_Opening, // 1,
// Deprecated value. Check the
// libvlc_MediaPlayerBuffering event to know the
// buffering state of a libvlc_media_player
libvlc_Buffering, // 2,
libvlc_Playing, // 3,
libvlc_Paused, // 4,
libvlc_Stopped, // 5,
libvlc_Ended, // 6,
libvlc_Error // 7
);
type
event_media_duration_changed_t = record
new_duration : Int64;
end;
type
media_parsed_changed_t = record
new_status : Integer; // see @ref libvlc_media_parsed_status_t
end;
type
media_state_changed_t = record
new_state : libvlc_state_t; // see @ref libvlc_state_t
end;
type
media_player_buffering_t = record
new_cache : Single; // float
end;
type
media_player_chapter_changed_t = record
new_chapter : Integer;
end;
type
media_player_time_changed_t = record
new_time : libvlc_time_t;
end;
type
media_player_position_changed_t = record
new_position : Single; // float
end;
type
media_player_seekable_changed_t = record
new_seekable : Integer;
end;
type
media_player_pausable_changed_t = record
new_pausable : Integer;
end;
type
media_player_vout_t = record
new_count : Integer;
end;
type
media_player_scrambled_changed_t = record
new_scrambled : Integer;
end;
type
media_player_snapshot_taken_t = record
psz_filename : PAnsiChar;
end;
type
media_player_length_changed_t = record
new_length : libvlc_time_t;
end;
type
media_player_title_changed_t = record
new_title : Integer;
end;
type
vlm_media_event_t = record
psz_media_name : PAnsiChar;
psz_instance_name : PAnsiChar;
end;
// Extra MediaPlayer
type
media_player_media_changed_t = record
new_media : plibvlc_media_t;
end;
type
media_player_audio_volume_t = record
volume : Single;
end;
type
media_player_audio_device_t = record
device : PAnsiChar;
end;
libvlc_event_t_ptr = ^libvlc_event_t;
libvlc_event_t = record
event_type : plibvlc_event_type_t;
p_obj : Pointer; (* Object emitting the event *)
case plibvlc_event_type_t of
// media descriptor
libvlc_MediaDurationChanged : (media_duration_changed : event_media_duration_changed_t);
libvlc_MediaParsedChanged : (media_parsed_changed : media_parsed_changed_t);
libvlc_MediaStateChanged : (media_state_changed : media_state_changed_t);
// media instance
libvlc_MediaPlayerBuffering : (media_player_buffering : media_player_buffering_t);
libvlc_MediaPlayerChapterChanged : (media_player_chapter_changed : media_player_chapter_changed_t);
libvlc_MediaPlayerPositionChanged : (media_player_position_changed : media_player_position_changed_t);
libvlc_MediaPlayerTimeChanged : (media_player_time_changed : media_player_time_changed_t);
libvlc_MediaPlayerTitleChanged : (media_player_title_changed : media_player_title_changed_t);
libvlc_MediaPlayerSeekableChanged : (media_player_seekable_changed : media_player_seekable_changed_t);
libvlc_MediaPlayerPausableChanged : (media_player_pausable_changed : media_player_pausable_changed_t);
libvlc_MediaPlayerScrambledChanged : (media_player_scrambled_changed : media_player_scrambled_changed_t);
libvlc_MediaPlayerVout : (media_player_vout : media_player_vout_t);
// snapshot taken
libvlc_MediaPlayerSnapshotTaken : (media_player_snapshot_taken : media_player_snapshot_taken_t);
// Length changed
libvlc_MediaPlayerLengthChanged : (media_player_length_changed : media_player_length_changed_t);
// VLM media
libvlc_VlmMediaAdded,
libvlc_VlmMediaRemoved,
libvlc_VlmMediaChanged,
libvlc_VlmMediaInstanceStarted,
libvlc_VlmMediaInstanceStopped,
libvlc_VlmMediaInstanceStatusInit,
libvlc_VlmMediaInstanceStatusOpening,
libvlc_VlmMediaInstanceStatusPlaying,
libvlc_VlmMediaInstanceStatusPause,
libvlc_VlmMediaInstanceStatusEnd,
libvlc_VlmMediaInstanceStatusError : (vlm_media_event : vlm_media_event_t);
// Extra MediaPlayer
libvlc_MediaPlayerMediaChanged : (media_player_media_changed : media_player_media_changed_t);
libvlc_MediaPlayerESAdded,
libvlc_MediaPlayerESDeleted,
libvlc_MediaPlayerAudioVolume : (media_player_audio_volume : media_player_audio_volume_t);
libvlc_MediaPlayerAudioDevice : (media_player_audio_device : media_player_audio_device_t);
end;
plibvlc_event_callback_t = procedure(p_event: libvlc_event_t_ptr; p_data: Pointer); cdecl;
procedure init(player: integer; Handle: Cardinal);
procedure play(player: integer; url: string; cacheTime: integer = 5);
function size(player: integer): TPoint;
function getPlayUrl(player: integer): string;
function getPlayCacheTime(player: integer): integer;
function status(player: integer): integer;
procedure snapshot(player: integer; filename: string);
//procedure vlcReplay;
//function vlcSize: TPoint;
//function vlcGetStatus: libvlc_state_t;
type
TLibVlcThread = class(TThread)
protected
procedure execute; override;
end;
type
TVlcPlayer = record
vlcPanelHandle: cardinal;
vlcInstance: plibvlc_instance_t;
vlcMedia: plibvlc_media_t;
vlcMediaPlayer: plibvlc_media_player_t;
//vlcEventManager: plibvlc_event_manager_t;
vlcUrl: string;
vlcStatus: integer;
vlcCacheTime: integer;
vlcWH: TPoint;
prevUrl: string;
prevCache: integer;
replay: boolean;
lastPlayTime: TDateTime;
end;
implementation
var
vlcPlayers: array[1..10] of TVlcPlayer;
var
libVlcThread: TLibVlcThread;
libVlcThreadCS: TCriticalSection;
var
libvlc_media_new_path : function(p_instance: Plibvlc_instance_t; path: PAnsiChar): Plibvlc_media_t; cdecl;
libvlc_media_new_location : function(p_instance: plibvlc_instance_t; psz_mrl: PAnsiChar): Plibvlc_media_t; cdecl;
libvlc_media_add_option : procedure(p_media_player: Plibvlc_media_player_t; psz_options: PAnsiChar; i_flags: integer); cdecl;
libvlc_media_player_new_from_media : function(p_media: Plibvlc_media_t): Plibvlc_media_player_t; cdecl;
libvlc_media_player_set_hwnd : procedure(p_media_player: Plibvlc_media_player_t; drawable: Pointer); cdecl;
libvlc_media_player_play : procedure(p_media_player: Plibvlc_media_player_t); cdecl;
libvlc_media_player_pause : procedure(p_media_player: Plibvlc_media_player_t); cdecl;
libvlc_media_player_stop : procedure(p_media_player: Plibvlc_media_player_t); cdecl;
libvlc_media_player_release : procedure(p_media_player: Plibvlc_media_player_t); cdecl;
libvlc_media_player_is_playing : function(p_media_player: Plibvlc_media_player_t): Integer; cdecl;
libvlc_media_player_get_state : function(p_media_player: Plibvlc_media_player_t): libvlc_state_t; cdecl;
libvlc_media_release : procedure(p_media: Plibvlc_media_t); cdecl;
libvlc_new : function(argc: Integer; argv: PAnsiChar): Plibvlc_instance_t; cdecl;
libvlc_release : procedure(p_instance: Plibvlc_instance_t); cdecl;
libvlc_video_set_mouse_input : procedure(p_media_player: Plibvlc_media_player_t; p_on: LongBool); cdecl;
libvlc_video_set_key_input : procedure(p_media_player: Plibvlc_media_player_t; p_on: LongBool); cdecl;
libvlc_video_get_size : function(p_media_player: Plibvlc_media_player_t; p_num: integer; var p_width, p_height: integer) : Integer; cdecl;
libvlc_video_set_aspect_ratio : procedure(p_media_player: Plibvlc_media_player_t; aspect:PChar); cdecl;
libvlc_media_player_event_manager : function(p_media_player: Plibvlc_media_player_t): plibvlc_event_manager_t; cdecl;
libvlc_event_attach : function(p_event_manager: plibvlc_event_manager_t; i_event_type: plibvlc_event_type_t; f_callback: plibvlc_event_callback_t; user_data: Pointer): integer; cdecl;
libvlc_video_take_snapshot : procedure(p_media_player: Plibvlc_media_player_t; num: byte; psz_filepath: PAnsiChar; i_width, i_height: LongWord); cdecl;
vlcLib: integer;
function LoadVLCLibrary: integer;
var
APath, vlcPath: string;
reg: TRegistry;
begin
vlcPath := '';
reg := TRegistry.Create;
try
reg.RootKey := HKEY_LOCAL_MACHINE;
if (reg.OpenKey('SoftWare\Microsoft\Windows\CurrentVersion\App Paths\vlc.exe', false)) then
begin
vlcPath := reg.ReadString('Path');
end;
finally
reg.Free;
end;
APath := ExtractFileDir(ParamStr(0));
Result := LoadLibrary(PAnsiChar(vlcPath + '\libvlccore.dll'));
Result := LoadLibrary(PAnsiChar(vlcPath + '\libvlc.dll'));
end;
procedure GetAProcAddress(handle: integer; var addr: Pointer; procName: string);
begin
addr := GetProcAddress(handle, PAnsiChar(procName));
end;
procedure LoadVLCFunctions(vlcHandle: integer);
begin
GetAProcAddress(vlcHandle, @libvlc_new, 'libvlc_new');
GetAProcAddress(vlcHandle, @libvlc_media_new_location, 'libvlc_media_new_location');
GetAProcAddress(vlcHandle, @libvlc_media_add_option, 'libvlc_media_add_option');
GetAProcAddress(vlcHandle, @libvlc_media_player_new_from_media, 'libvlc_media_player_new_from_media');
GetAProcAddress(vlcHandle, @libvlc_media_release, 'libvlc_media_release');
GetAProcAddress(vlcHandle, @libvlc_media_player_set_hwnd, 'libvlc_media_player_set_hwnd');
GetAProcAddress(vlcHandle, @libvlc_media_player_play, 'libvlc_media_player_play');
GetAProcAddress(vlcHandle, @libvlc_media_player_pause, 'libvlc_media_player_pause');
GetAProcAddress(vlcHandle, @libvlc_media_player_stop, 'libvlc_media_player_stop');
GetAProcAddress(vlcHandle, @libvlc_media_player_release, 'libvlc_media_player_release');
GetAProcAddress(vlcHandle, @libvlc_release, 'libvlc_release');
GetAProcAddress(vlcHandle, @libvlc_media_player_is_playing, 'libvlc_media_player_is_playing');
GetAProcAddress(vlcHandle, @libvlc_media_player_get_state, 'libvlc_media_player_get_state');
GetAProcAddress(vlcHandle, @libvlc_media_new_path, 'libvlc_media_new_path');
GetAProcAddress(vlcHandle, @libvlc_video_set_mouse_input, 'libvlc_video_set_mouse_input');
GetAProcAddress(vlcHandle, @libvlc_video_set_key_input, 'libvlc_video_set_key_input');
GetAProcAddress(vlcHandle, @libvlc_video_get_size, 'libvlc_video_get_size');
GetAProcAddress(vlcHandle, @libvlc_video_set_aspect_ratio, 'libvlc_video_set_aspect_ratio');
GetAProcAddress(vlcHandle, @libvlc_media_player_event_manager, 'libvlc_media_player_event_manager');
GetAProcAddress(vlcHandle, @libvlc_video_take_snapshot, 'libvlc_video_take_snapshot');
end;
procedure init(player: integer; Handle: Cardinal);
begin
with vlcPlayers[player] do
begin
vlcPanelHandle := Handle;
end;
end;
procedure play(player: integer; url: string; cacheTime: integer = 5);
begin
libVlcThreadCS.Enter;
try
vlcPlayers[player].vlcUrl := url;
vlcPlayers[player].vlcCacheTime := cacheTime;
vlcPlayers[player].replay := true;
vlcPlayers[player].lastPlayTime := now;
finally
libVlcThreadCS.Leave;
end;
end;
function size(player: integer): TPoint;
begin
Result := vlcPlayers[player].vlcWH;
if (Result.X > 10000) then Result.X := 0;
if (Result.Y > 10000) then Result.Y := 0;
end;
function getPlayUrl(player: integer): string;
begin
libVlcThreadCS.Enter;
try
Result := vlcPlayers[player].vlcUrl;
finally
libVlcThreadCS.Leave;
end;
end;
function getPlayCacheTime(player: integer): integer;
begin
libVlcThreadCS.Enter;
try
Result := vlcPlayers[player].vlcCacheTime;
finally
libVlcThreadCS.Leave;
end;
end;
function status(player: integer): integer;
begin
Result := vlcPlayers[player].vlcStatus;
end;
procedure snapshot(player: integer; filename: string);
begin
if not Assigned(vlcPlayers[player].vlcMediaPlayer) then Exit;
if (size(player).X = 0) or (size(player).Y = 0) then exit;
filename := ExtractFileDir(ParamStr(0)) + '\' + LIBVLC_SNAPSHOTS + '\' + filename;
libVlcThreadCS.Enter;
try
libvlc_video_take_snapshot(vlcPlayers[player].vlcMediaPlayer, 0, PAnsiChar(filename), size(player).X, size(player).Y);
finally
libVlcThreadCS.Leave;
end;
end;
procedure vlcStop(player: integer);
begin
if not Assigned(vlcPlayers[player].vlcMediaPlayer) then Exit;
with vlcPlayers[player] do
begin
libvlc_media_player_stop(vlcMediaPlayer);
while (libvlc_media_player_is_playing(vlcMediaPlayer) > 0) do
begin
Sleep(100);
end;
libvlc_media_player_release(vlcMediaPlayer);
vlcMediaPlayer := nil;
//libvlc_release(vlcInstance);
lastPlayTime := now;
end;
end;
procedure vlcPlay(player: integer; url: string; cacheTime: integer = 5);
begin
if (vlcPlayers[player].vlcPanelHandle = 0) then Exit;
vlcStop(player);
with vlcPlayers[player] do
begin
replay := false;
vlcInstance := libvlc_new(0, nil);
vlcMedia := libvlc_media_new_location(vlcInstance, PAnsiChar(url));
vlcMediaPlayer := libvlc_media_player_new_from_media(vlcMedia);
libvlc_media_add_option(vlcMedia, PAnsiChar(':network-caching=' + IntToStr(cacheTime)), 0);
libvlc_media_add_option(vlcMedia, PAnsiChar(':rtsp-tcp'), 0);
libvlc_media_release(vlcMedia);
libvlc_media_player_set_hwnd(vlcMediaPlayer, Pointer(vlcPanelHandle));
libvlc_media_player_play(vlcMediaPlayer);
libvlc_video_set_aspect_ratio(vlcMediaPlayer, '16:9');
libvlc_video_set_mouse_input(vlcMediaPlayer, false);
libvlc_video_set_key_input(vlcMediaPlayer, false);
end;
end;
function vlcSize(player: integer): TPoint;
var
w, h: integer;
begin
Result := Point(0, 0);
if not Assigned(vlcPlayers[player].vlcMediaPlayer) then Exit;
libvlc_video_get_size(vlcPlayers[player].vlcMediaPlayer, 0, w, h);
Result := Point(w, h);
end;
function vlcCheckPlaying(player: integer): boolean;
begin
Result := false;
if not Assigned(vlcPlayers[player].vlcMediaPlayer) then Exit;
Result := libvlc_media_player_is_playing(vlcPlayers[player].vlcMediaPlayer) > 0;
end;
function vlcGetStatus(player: integer): libvlc_state_t;
begin
Result := libvlc_NothingSpecial;
if not Assigned(vlcPlayers[player].vlcMediaPlayer) then Exit;
Result := libvlc_media_player_get_state(vlcPlayers[player].vlcMediaPlayer);
end;
{ TLibVlcThread }
procedure TLibVlcThread.execute;
var
url: string;
cache: integer;
k: integer;
begin
inherited;
while not Terminated do
begin
for k := 1 to Length(vlcPlayers) do
begin
try
if (vlcPlayers[k].vlcPanelHandle > 0) then
begin
if (vlclib = 0) then // Библиотека не загружена - грузим ее
begin
vlclib := LoadVLCLibrary;
if vlclib > 0 then LoadVLCFunctions(vlclib);
end;
if (vlcLib > 0) then // Библиотека загружена
begin
vlcPlayers[k].vlcStatus := integer(vlcGetStatus(k));
libVlcThreadCS.Enter;
try
url := vlcPlayers[k].vlcUrl;
cache := vlcPlayers[k].vlcCacheTime;
finally
libVlcThreadCS.Leave;
end;
if (vlcPlayers[k].prevUrl <> url) or
(vlcPlayers[k].prevCache <> cache) or
(vlcPlayers[k].replay) or
(now - vlcPlayers[k].lastPlayTime > 120 / (24 * 3600)) then vlcPlayers[k].vlcStatus := -1;
case vlcPlayers[k].vlcStatus of
1, 2, 3, 4, 5: // Статусы которые при проигрывании
begin
vlcPlayers[k].vlcWH := vlcSize(k);
end;
else
begin
vlcPlayers[k].vlcWH := Point(0, 0);
vlcStop(k);
if (url <> '') and (cache >= 0) then vlcPlay(k, url, cache);
end;
end;
vlcPlayers[k].prevUrl := url;
vlcPlayers[k].prevCache := cache;
end;
Sleep(10);
end
else
begin
vlcPlayers[k].vlcStatus := -1;
end;
except
Sleep(100);
end;
end;
Sleep(50);
end;
for k := 1 to Length(vlcPlayers) do
begin
try
vlcStop(k);
except
end;
end;
FreeLibrary(vlclib);
end;
initialization
libVlcThreadCS := TCriticalSection.Create;
libVlcThread := TLibVlcThread.Create(true);
libVlcThread.Priority := tpIdle;
libVlcThread.FreeOnTerminate := true;
libVlcThread.Resume;
finalization
libVlcThread.Terminate;
WaitForSingleObject(libVlcThread.Handle, 10000);
libVlcThreadCS.Free;
end.
|
unit LrCollapsable;
interface
uses
SysUtils, Windows, Classes, Controls, Messages, StdCtrls, ExtCtrls, Forms,
Graphics;
type
TLrCollapsable = class(TCustomControl)
private
FBorderColor: TColor;
FClosed: Boolean;
// FClosedGlyph: TBitmap;
// FHot: Boolean;
// FOpenGlyph: TBitmap;
FOpenHeight: Integer;
FHeaderColor: TColor;
FHeaderHeight: Integer;
protected
function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override;
function GetGlyph: TBitmap;
function GetHeaderRect: TRect;
procedure AdjustClientRect(var Rect: TRect); override;
// procedure AlignControls(AControl: TControl; var Rect: TRect); override;
// procedure CMControlChange(
// var Message: TCMControlChange); message CM_CONTROLCHANGE;
// procedure CreateHeader;
// procedure CreateTimer;
procedure DefineProperties(Filer: TFiler); override;
procedure LoadExtraProps(Reader: TReader);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure OpenClose;
procedure Paint; override;
procedure SetBorderColor(const Value: TColor);
procedure SetClosed(const Value: Boolean);
procedure SetHeaderColor(const Value: TColor);
procedure SetHeaderHeight(const Value: Integer);
// procedure SetHot(const Value: Boolean);
procedure StoreExtraProps(Writer: TWriter);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property HeaderRect: TRect read GetHeaderRect;
// property Hot: Boolean read FHot write SetHot;
published
property Align;
property AutoSize;
property BorderColor: TColor read FBorderColor write SetBorderColor
default clWhite;
property Color;
property Caption;
property Closed: Boolean read FClosed write SetClosed default false;
property Enabled;
property Font;
property HeaderColor: TColor read FHeaderColor write SetHeaderColor
default clBtnFace;
property HeaderHeight: Integer read FHeaderHeight write SetHeaderHeight
default 18;
property ParentFont;
property Visible;
end;
implementation
{$R LrBarImages.res}
var
ResClosedGlyph: TBitmap;
ResOpenGlyph: TBitmap;
procedure NeedResGlyphs;
begin
if ResClosedGlyph = nil then
begin
ResClosedGlyph := TBitmap.Create;
ResClosedGlyph.LoadFromResourceName(HInstance, 'LRCLOSED');
ResOpenGlyph := TBitmap.Create;
ResOpenGlyph.LoadFromResourceName(HInstance, 'LROPEN');
end;
end;
{ TLrCollapsable }
constructor TLrCollapsable.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
NeedResGlyphs;
FBorderColor := clWhite;
FHeaderColor := clBtnFace;
FHeaderHeight := 18;
end;
destructor TLrCollapsable.Destroy;
begin
inherited;
end;
procedure TLrCollapsable.LoadExtraProps(Reader: TReader);
begin
FOpenHeight := Reader.ReadInteger;
end;
procedure TLrCollapsable.StoreExtraProps(Writer: TWriter);
begin
Writer.WriteInteger(FOpenHeight);
end;
procedure TLrCollapsable.DefineProperties(Filer: TFiler);
begin
inherited; { allow base classes to define properties }
Filer.DefineProperty('ExtraProps', LoadExtraProps, StoreExtraProps, true);
end;
function TLrCollapsable.GetHeaderRect: TRect;
begin
Result := Rect(0, 0, ClientWidth, HeaderHeight);
end;
function TLrCollapsable.GetGlyph: TBitmap;
begin
if Closed then
Result := ResClosedGlyph
else
Result := ResOpenGlyph;
end;
procedure TLrCollapsable.Paint;
var
r: TRect;
begin
inherited;
r := HeaderRect;
Canvas.Brush.Color := HeaderColor;
Canvas.Pen.Color := BorderColor;
Canvas.Rectangle(r);
InflateRect(r, -4, -2);
Canvas.Draw(r.Left, r.Top + (r.Bottom - r.Top - GetGlyph.Height) div 2,
GetGlyph);
Inc(r.Left, 20);
Canvas.Font := Font;
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
DrawText(Canvas.Handle, PChar(Caption), Length(Caption), r, 0);
SetBkMode(Canvas.Handle, OPAQUE);
end;
procedure TLrCollapsable.OpenClose;
begin
if not Closed then
begin
FOpenHeight := Height;
Height := HeaderHeight;
FClosed := true;
end
else begin
Height := FOpenHeight;
FClosed := false;
end;
AdjustSize;
end;
procedure TLrCollapsable.AdjustClientRect(var Rect: TRect);
begin
inherited;
Inc(Rect.Top, HeaderHeight);
end;
function TLrCollapsable.CanAutoSize(var NewWidth,
NewHeight: Integer): Boolean;
begin
Result := inherited CanAutoSize(NewWidth, NewHeight); // and not Closed;
if Closed then
NewHeight := HeaderHeight;
end;
procedure TLrCollapsable.SetClosed(const Value: Boolean);
begin
if (FClosed <> Value) then
OpenClose;
end;
procedure TLrCollapsable.SetHeaderHeight(const Value: Integer);
begin
FHeaderHeight := Value;
Invalidate;
end;
procedure TLrCollapsable.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if Y < HeaderHeight then
OpenClose;
end;
procedure TLrCollapsable.SetBorderColor(const Value: TColor);
begin
BorderColor := Value;
Invalidate;
end;
procedure TLrCollapsable.SetHeaderColor(const Value: TColor);
begin
FHeaderColor := Value;
Invalidate;
end;
{
procedure TLrCollapsable.SetHot(const Value: Boolean);
begin
FHot := Value;
Invalidate;
end;
}
end.
|
unit fruDBFilter;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, fruFilter, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
dxSkinOffice2013White, cxLabel, Vcl.ExtCtrls, Vcl.Menus, Vcl.StdCtrls,
cxButtons, Vcl.DBCtrls, vwuCommon;
type
TfrDBFilter = class(TfrFilter)
cbFilter: TDBLookupComboBox;
procedure buFilterClearClick(Sender: TObject);
procedure cbFilterClick(Sender: TObject);
private
FDataList: TvwCommon;
protected
function GetKeyValue: Variant; override;
procedure SetKeyValue(const Value: Variant); override;
public
property DataList: TvwCommon read FDataList write FDataList;
{обновление данных с запросом на сервер}
procedure Refresh(); virtual;
end;
implementation
{$R *.dfm}
{ TfrDBFilter }
procedure TfrDBFilter.buFilterClearClick(Sender: TObject);
begin
KeyValue:= Null;
DoChange();
end;
procedure TfrDBFilter.cbFilterClick(Sender: TObject);
begin
DoChange();
end;
function TfrDBFilter.GetKeyValue: Variant;
begin
Result:= cbFilter.KeyValue;
end;
procedure TfrDBFilter.Refresh;
begin
FDataList.RefreshData(FDataList.FID.Value);
end;
procedure TfrDBFilter.SetKeyValue(const Value: Variant);
begin
inherited;
cbFilter.KeyValue:= Value;
end;
end.
|
unit MainF;
interface
uses
Windows,
SysUtils,
ShellAPI,
Registry,
MWpasU,
Messages,
KeyCodeU,
IniFiles,
Forms;
type
TRunEntry = record
Atom : ATOM;
Path : String;
Params : String;
end;
TRunEntries = array of TRunEntry;
TMainForm = class(TForm)
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private-Deklarationen }
FConnectAtom : ATOM;
FDisconnectAtom : ATOM;
FEndAtom : ATOM;
FInstance : String;
FQuitAtom : ATOM;
FReconnectAtom : ATOM;
FRunEntries : TRunEntries;
procedure WMHotKey(var Msg: TWMHotKey); message WM_HOTKEY;
procedure WMQueryEndSession(var Msg: TWMQueryEndSession); message WM_QUERYENDSESSION;
procedure AddToAutostart;
procedure RegisterHotkeys;
procedure RemoveFromAutostart;
procedure UnregisterHotkeys;
public
{ Public-Deklarationen }
end;
var
MainForm : TMainForm;
implementation
{$R *.dfm}
{ TMainForm }
procedure TMainForm.WMHotKey(var Msg : TWMHotKey);
procedure SendString(const AString : String);
var
LAccess : TMWconnAccessMode;
LFile : THandle;
LMapping : PMWconnIO;
begin
if (IsMWconnRunning(FInstance)) then
begin
LAccess := OpenMWconnIO(LFile, LMapping, FInstance);
try
if ((LAccess = mwamAll) or (LAccess = mwamWrite)) then
begin
ZeroMemory(@LMapping^.Command[0], Length(LMapping^.Command));
CopyMemory(@LMapping^.Command[0], @AString[1], Length(AString));
end;
finally
CloseMWconnIO(LFile, LMapping);
end;
end;
end;
var
LIndex : LongInt;
begin
if (Msg.HotKey = FConnectAtom) then
SendString(MWconn_Connect);
if (Msg.HotKey = FDisconnectAtom) then
SendString(MWconn_Disconnect);
if (Msg.HotKey = FEndAtom) then
SendString(MWconn_End);
if (Msg.HotKey = FQuitAtom) then
begin
RemoveFromAutostart;
Close;
end;
if (Msg.HotKey = FReconnectAtom) then
SendString(MWconn_Reconnect);
for LIndex := 0 to Pred(Length(FRunEntries)) do
begin
if (Msg.HotKey = FRunEntries[LIndex].Atom) then
begin
if (Trim(FRunEntries[LIndex].Path) <> '') then
ShellExecute(Handle, 'open', PChar(FRunEntries[LIndex].Path),
PChar(FRunEntries[LIndex].Params),
PChar(ExtractFilePath(FRunEntries[LIndex].Path)), SW_SHOWNORMAL);
Break;
end;
end;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
UnregisterHotkeys;
end;
procedure TMainForm.AddToAutostart;
var
LRegistry : TRegistry;
begin
LRegistry := TRegistry.Create(KEY_ALL_ACCESS);
try
LRegistry.RootKey := HKEY_CURRENT_USER;
if LRegistry.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', false) then
begin
try
LRegistry.WriteString('MWhotkey', Application.ExeName);
finally
LRegistry.CloseKey;
end;
end;
finally
LRegistry.Free;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FConnectAtom := 0;
FDisconnectAtom := 0;
FEndAtom := 0;
FQuitAtom := 0;
FReconnectAtom := 0;
SetLength(FRunEntries, 0);
AddToAutostart;
RegisterHotkeys;
end;
procedure TMainForm.RegisterHotkeys;
function DoRegister(const AString : String) : ATOM;
var
LHotkey : THotkey;
begin
Result := 0;
try
LHotkey := StringToHotkey(AString);
Result := GlobalAddAtom(PChar('MWhotkey: ' + LHotkey.Value));
if (Result > 0) then
RegisterHotKey(Handle, Result, LHotkey.Modifiers, LHotkey.Key);
except
// duplicate key or no key
end;
end;
var
LAtom : ATOM;
LCount : Byte;
LIniFile : TIniFile;
begin
UnregisterHotkeys;
LIniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
try
// MWconn shortcut options
FConnectAtom := DoRegister(LIniFile.ReadString('MWconn', 'Connect', 'CTRL+ALT+C'));
FDisconnectAtom := DoRegister(LIniFile.ReadString('MWconn', 'Disconnect', 'CTRL+ALT+D'));
FEndAtom := DoRegister(LIniFile.ReadString('MWconn', 'End', 'CTRL+ALT+E'));
FReconnectAtom := DoRegister(LIniFile.ReadString('MWconn', 'Reconnect', 'CTRL+ALT+R'));
// MWconn general options
FInstance := LIniFile.ReadString('MWconn', 'Instance', '');
// MWhotkey shortcut options
FQuitAtom := DoRegister(LIniFile.ReadString('MWhotkey', 'Quit', 'CTRL+ALT+END'));
// Run shortcut options
LCount := 1;
while (LIniFile.ValueExists('Run', 'Hotkey' + IntToStr(LCount)) and
LIniFile.ValueExists('Run', 'Path' + IntToStr(LCount))) do
begin
LAtom := DoRegister(LIniFile.ReadString('Run', 'Hotkey' + IntToStr(LCount), ''));
if (LAtom > 0) then
begin
SetLength(FRunEntries, Succ(Length(FRunEntries)));
FRunEntries[High(FRunEntries)].Atom := LAtom;
FRunEntries[High(FRunEntries)].Path := Trim(LIniFile.ReadString('Run', 'Path' + IntToStr(LCount), ''));
FRunEntries[High(FRunEntries)].Params := Trim(LIniFile.ReadString('Run', 'Params' + IntToStr(LCount), ''));
end;
Inc(LCount);
end;
finally
LIniFile.Free;
end;
end;
procedure TMainForm.UnregisterHotkeys;
var
LIndex : LongInt;
begin
if (FConnectAtom > 0) then
begin
UnRegisterHotKey(Handle, FConnectAtom);
GlobalDeleteAtom(FConnectAtom);
FConnectAtom := 0;
end;
if (FDisconnectAtom > 0) then
begin
UnRegisterHotKey(Handle, FDisconnectAtom);
GlobalDeleteAtom(FDisconnectAtom);
FDisconnectAtom := 0;
end;
if (FEndAtom > 0) then
begin
UnRegisterHotKey(Handle, FEndAtom);
GlobalDeleteAtom(FEndAtom);
FEndAtom := 0;
end;
if (FQuitAtom > 0) then
begin
UnRegisterHotKey(Handle, FQuitAtom);
GlobalDeleteAtom(FQuitAtom);
FQuitAtom := 0;
end;
if (FReconnectAtom > 0) then
begin
UnRegisterHotKey(Handle, FReconnectAtom);
GlobalDeleteAtom(FReconnectAtom);
FReconnectAtom := 0;
end;
for LIndex := 0 to Pred(Length(FRunEntries)) do
begin
if (FRunEntries[LIndex].Atom > 0) then
begin
UnRegisterHotKey(Handle, FRunEntries[LIndex].Atom);
GlobalDeleteAtom(FRunEntries[LIndex].Atom);
end;
end;
SetLength(FRunEntries, 0);
end;
procedure TMainForm.RemoveFromAutostart;
var
LRegistry : TRegistry;
begin
LRegistry := TRegistry.Create(KEY_ALL_ACCESS);
try
LRegistry.RootKey := HKEY_CURRENT_USER;
if LRegistry.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', false) then
begin
try
if LRegistry.ValueExists('MWhotkey') then
LRegistry.DeleteValue('MWhotkey');
finally
LRegistry.CloseKey;
end;
end;
finally
LRegistry.Free;
end;
end;
procedure TMainForm.WMQueryEndSession(var Msg : TWMQueryEndSession);
begin
// do not interrupt Windows shutdown
Msg.Result := 1;
Close;
end;
end.
|
unit uWinList;
interface
uses Classes ,windows,SysUtils,DBClient,DB,Dialogs ,ShellAPI,Forms,IMCode,uFolder;
type
TResultDataset = class(TClientDataset)
private
procedure MergeFrom(Src: TClientDataset);
protected
procedure Init ;virtual;
public
constructor Create (O : TComponent);override ;
procedure DoFilter (S : String;Exactly:Boolean = false);virtual;
procedure CancelFilter ;virtual;
procedure DoRun ;virtual ;
end;
type
TIndexThread = class(TThread)
private
Fcds: TClientDataSet;
FRootFolder: String;
procedure Setcds(const Value: TClientDataSet);
procedure SetRootFolder(const Value: String);
procedure DeleteLastChar(var S: string);
procedure FillDir(s: String; var Dataset: TClientDataSet);
function GetLastChar(S: string): String;
function GetLastDir(S: string): String;
{ Private declarations }
protected
procedure Execute; override;
property cds :TClientDataSet read Fcds write Setcds;
property RootFolder :String read FRootFolder write SetRootFolder;
destructor Destroy ;override ;
public
end;
function GetFixDisk:string ;
type
TIndexer =class
class function IndexAll : TResultDataset;
end;
implementation
{ TAllWindows }
procedure TResultDataset.MergeFrom(Src:TClientDataset);
var
i : integer;
Dst:TClientDataset;
begin
Src.First ;
Dst := Self;
while not Src.eof do begin
Dst.Append;
for i :=0 to Dst.Fields.Count -1 do
Dst.Fields[i].Asstring := Src.Fields[i].Asstring ;
Dst.Post ;
Src.Next ;
end;
end;
class function TIndexer.IndexAll : TResultDataset;
var
IndexThread:array of TIndexThread;
sl : TStringList ;
i : Integer ;
begin
sl := TStringList.Create ;
try
TFolder.GetLevel1Sons(sl);
SetLength(IndexThread,sl.Count);
for i := 0 to sl.Count -1 do begin
IndexThread[i] := TIndexThread.Create(true);
IndexThread[i].cds := TResultDataset.create(nil);
IndexThread[i].RootFolder := sl.Strings[i] ;
IndexThread[i].FreeOnTerminate := False;
IndexThread[i].Resume;
end;
for i := 0 to sl.Count -1 do
IndexThread[i].WaitFor ;
Result := TResultDataset.Create (nil);
if sl.count >=1 then begin
for i := 0 to sl.count -1 do begin
Result.MergeFrom(IndexThread[i].cds);
//ShowMessage(IntToStr(IndexThread[i].cds.RecordCount));
end;
end;
Result.First ;
finally
for i := 0 to sl.Count -1 do begin
IndexThread[i].Free;
end;
sl.Free ;
end;
end;
procedure TResultDataset.DoRun;
begin
inherited;
ShellExecute(0,nil,PChar(fieldByName('key').AsString),nil,nil,SW_SHOWNORMAL);
end;
procedure TIndexThread.DeleteLastChar(var S:string);
begin
S := Copy(S,1,Length(S)-1);
end;
function TIndexThread.GetLastChar(S:string):String;
begin
Result := Copy(S,Length(S),1);
end;
function TIndexThread.GetLastDir(S:string):String;
var
i :Integer ;
begin
if GetLastChar(S) ='\' then
DeleteLastChar(S);
i := Length(s);
while i > 0 do
begin
if Copy(S,i,1) ='\' then begin
Result := Copy(S,i+1,Length(s));
Exit;
end;
Dec(i);
end;
Result := s ;
end;
procedure TIndexThread.FillDir(s:String;var Dataset :TClientDataSet);
var
temPath:String;
sr:TSearchRec;
function EnsureSlash(a:string):String;
begin
if a[Length(a)]<>'\' then
result := a+'\';
end;
begin
temPath:=s+'\*.*';
if SysUtils.FindFirst(temPath,faAnyFile,sr)=0 then
repeat
if (sr.Name='.') or (sr.Name='..') then continue
else
//if (sr.Attr and faDirectory)=sr.Attr then
// 上面这个方法是delphi给的例子,但是找不到program files 之类的17属性的目录
// 下面是我试验处理的。
if ((sr.Attr and faDirectory)= faDirectory)
and ((sr.Attr and faHidden)<> faHidden)
then
begin
Dataset.Append;
Dataset.FieldByName('key').asString := s+'\'+sr.name;
//Dataset.FieldByName('value').asString := getPyString(GetLastDir(s+sr.name));
Dataset.FieldByName('value').asString := getPyString(Dataset.FieldByName('key').asString);
Dataset.Post ;
Application.ProcessMessages;
FillDir(s+'\'+sr.Name,Dataset);
//FillDir(EnsureSlash(s)+sr.Name+'\',Dataset);
end;
until SysUtils.FindNext(sr)<>0 ;
SysUtils.FindClose(sr);
Dataset.First;
end;
procedure TResultDataset.CancelFilter;
begin
Self.Filtered := False;
end;
constructor TResultDataset.Create(O: TComponent);
begin
inherited;
Init ;
end;
procedure TResultDataset.DoFilter(S: String;Exactly:Boolean = false);
begin
FilterOptions := [foCaseInsensitive];
if Exactly then
Filter := 'value ='''+S+''''
else
Filter := 'value like ''%'+S+'%''';
Filtered := True ;
end;
procedure TResultDataset.Init;
var
F :TStringField ;
begin
F := TStringField.Create(nil);
F.Size := 255 ;
F.DisplayWidth := 80;
F.FieldName := 'key';
F.DataSet := Self ;
F := TStringField.Create(nil);
F.FieldName := 'value';
F.Size := 255 ;
F.Visible:= False;
F.DataSet := Self ;
CreateDataSet ;
end;
{ TIndexThread }
procedure TIndexThread.Execute;
begin
inherited;
FillDir(FRootFolder,Fcds);
end;
function GetFixDisk:string ;
var
i,len : Integer ;
A : Array [0..255] of char ;
B : String ;
sl :TStringList ;
begin
FillChar(A,255,#0);
len := GetLogicalDriveStrings(255,A);
sl := TStringList.Create ;
try
for I := 0 to len -1 do
if A[I] = #0 then begin
if (b <> '') and (GetDriveType(PChar(b)) = DRIVE_FIXED) then
sl.Add(b);
b := '';
end else
b := b + A[I] ;
Result := sl.CommaText ;
finally
sl.Free ;
end;
end;
procedure TIndexThread.Setcds(const Value: TClientDataSet);
begin
Fcds := Value;
end;
procedure TIndexThread.SetRootFolder(const Value: String);
begin
FRootFolder := Value;
end;
destructor TIndexThread.Destroy;
begin
if Assigned(Fcds)then
Fcds.Free ;
inherited;
end;
end.
|
unit St_sp_Hostel_Add_Many_Room;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, FIBDataSet,
pFIBDataSet, cxCheckBox, Buttons, cxMaskEdit, cxDropDownEdit,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxControls, cxGridCustomView, cxGrid, cxTextEdit, cxLabel,
cxContainer, cxGroupBox, StdCtrls, cxButtons;
type
TBuildsFormAddRoom2 = class(TForm)
OKButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
cxLabel1: TcxLabel;
FromEdit: TcxTextEdit;
cxLabel2: TcxLabel;
ToEdit: TcxTextEdit;
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DBTableView1ID_TYPE_ROOM: TcxGridDBColumn;
cxGrid1DBTableView1NAME_TYPE_ROOM: TcxGridDBColumn;
cxGrid1DBTableView1SHORT_NAME: TcxGridDBColumn;
cxGrid1DBTableView1MAX_PEOPLE_COUNT: TcxGridDBColumn;
cxGrid1DBTableView1SIZE: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
cxGroupBox2: TcxGroupBox;
cxLabel3: TcxLabel;
TypeEdit: TcxPopupEdit;
cxGroupBox3: TcxGroupBox;
AddButton: TSpeedButton;
DeleteButton: TSpeedButton;
DownButton: TSpeedButton;
UpButton: TSpeedButton;
cxGrid2: TcxGrid;
cxGrid2TableView1: TcxGridTableView;
cxGrid2TableView1ID_ROOM_TYPE: TcxGridColumn;
cxGrid2TableView1NAME_ROOM_TYPE: TcxGridColumn;
cxGrid2Level1: TcxGridLevel;
cxCheckBox1: TcxCheckBox;
DataSource1: TDataSource;
pFIBDataSet1: TpFIBDataSet;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyleRepository2: TcxStyleRepository;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure cxCheckBox1Click(Sender: TObject);
procedure cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure AddButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure UpButtonClick(Sender: TObject);
procedure DownButtonClick(Sender: TObject);
procedure cxGrid2TableView1CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure OKButtonClick(Sender: TObject);
procedure FromEditKeyPress(Sender: TObject; var Key: Char);
procedure ToEditKeyPress(Sender: TObject; var Key: Char);
procedure TypeEditKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
id_type_room : integer;
procedure CheckUpDownButtons;
end;
var
BuildsFormAddRoom2: TBuildsFormAddRoom2;
implementation
uses DataModule1_Unit, Unit_of_Utilits;
{$R *.dfm}
procedure TBuildsFormAddRoom2.CheckUpDownButtons;
begin
if cxGrid2TableView1.DataController.RecordCount = 0 then begin
UpButton.Enabled := false;
DownButton.Enabled := false;
exit;
end;
if cxGrid2TableView1.DataController.FocusedRecordIndex > 0 then UpButton.Enabled := true else UpButton.Enabled := false;
if cxGrid2TableView1.DataController.FocusedRecordIndex < cxGrid2TableView1.DataController.RecordCount - 1 then DownButton.Enabled := true else DownButton.Enabled := false;
end;
procedure TBuildsFormAddRoom2.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TBuildsFormAddRoom2.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
pFIBDataSet1.Close;
action:=cafree;
end;
procedure TBuildsFormAddRoom2.FormShow(Sender: TObject);
begin
pFIBDataSet1.Open;
FromEdit.SetFocus;
end;
procedure TBuildsFormAddRoom2.cxCheckBox1Click(Sender: TObject);
begin
cxGroupBox3.Visible := cxCheckBox1.Checked;
if cxGroupBox3.Visible then Height := 290 else Height := 145;
end;
procedure TBuildsFormAddRoom2.cxGrid1DBTableView1CellClick(
Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
TypeEdit.DroppedDown := false;
id_type_room := pFIBDataSet1['ID_TYPE_ROOM'];
TypeEdit.Text := pFIBDataSet1['NAME_TYPE_ROOM'];
end;
procedure TBuildsFormAddRoom2.AddButtonClick(Sender: TObject);
begin
if id_type_room = -1 then begin
ShowMessage('Перед добавлением необходимо указать тип комнаты.');
exit;
end;
cxGrid2TableView1.DataController.RecordCount := cxGrid2TableView1.DataController.RecordCount + 1;
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.RecordCount - 1, 0] := id_type_room;
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.RecordCount - 1, 1] := TypeEdit.Text;
cxGrid2TableView1.DataController.FocusedRecordIndex := cxGrid2TableView1.DataController.RecordCount - 1;
DeleteButton.Enabled := true;
CheckUpDownButtons;
end;
procedure TBuildsFormAddRoom2.FormCreate(Sender: TObject);
begin
id_type_room := -1;
cxGrid2TableView1.Items[0].DataBinding.ValueTypeClass := TcxIntegerValueType;
cxGrid2TableView1.Items[1].DataBinding.ValueTypeClass := TcxStringValueType;
end;
procedure TBuildsFormAddRoom2.DeleteButtonClick(Sender: TObject);
begin
cxGrid2TableView1.DataController.DeleteFocused;
if cxGrid2TableView1.DataController.RecordCount = 0 then DeleteButton.Enabled := false;
CheckUpDownButtons;
end;
procedure TBuildsFormAddRoom2.UpButtonClick(Sender: TObject);
var
tmp_id : integer;
tmp_type : string;
begin
tmp_id := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 0];
tmp_type := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 1];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 0] := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex - 1, 0];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 1] := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex - 1, 1];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex - 1, 0] := tmp_id;
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex - 1, 1] := tmp_type;
cxGrid2TableView1.DataController.FocusedRecordIndex := cxGrid2TableView1.DataController.FocusedRecordIndex - 1;
CheckUpDownButtons;
end;
procedure TBuildsFormAddRoom2.DownButtonClick(Sender: TObject);
var
tmp_id : integer;
tmp_type : string;
begin
tmp_id := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 0];
tmp_type := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 1];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 0] := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex + 1, 0];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex, 1] := cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex + 1, 1];
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex + 1, 0] := tmp_id;
cxGrid2TableView1.DataController.Values[cxGrid2TableView1.DataController.FocusedRecordIndex + 1, 1] := tmp_type;
cxGrid2TableView1.DataController.FocusedRecordIndex := cxGrid2TableView1.DataController.FocusedRecordIndex + 1;
CheckUpDownButtons;
end;
procedure TBuildsFormAddRoom2.cxGrid2TableView1CellClick(
Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
CheckUpDownButtons;
end;
procedure TBuildsFormAddRoom2.OKButtonClick(Sender: TObject);
begin
if not IntegerCheck(FromEdit.Text) then begin
ShowMessage('Начало интервала введено неверно.');
FromEdit.SetFocus;
exit;
end;
if not IntegerCheck(ToEdit.Text) then begin
ShowMessage('Конец интервала введен неверно.');
ToEdit.SetFocus;
exit;
end;
if StrToInt(FromEdit.Text) >= StrToInt(ToEdit.Text) then begin
ShowMessage('Значение начала интервала должно быть меньше значения конца интервала.');
ToEdit.SetFocus;
exit;
end;
if cxCheckBox1.Checked then begin
if cxGrid2TableView1.DataController.RecordCount = 0 then begin
ShowMessage('Необходимо добавит хотя бы один тип комнаты.');
exit;
end;
end else begin
if id_type_room = -1 then begin
ShowMessage('Необходимо указать тип комнаты.');
exit;
end;
end;
ModalResult := mrOk;
end;
procedure TBuildsFormAddRoom2.FromEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then ToEdit.SetFocus;
end;
procedure TBuildsFormAddRoom2.ToEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then TypeEdit.SetFocus;
end;
procedure TBuildsFormAddRoom2.TypeEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then OKButton.SetFocus;
end;
end.
|
unit AsSynAutoCorrectEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, AsSynAutoCorrect, Buttons, Registry;
type
TfrmAutoCorrectEditor = class(TForm)
lblLabel1: TLabel;
lblLabel2: TLabel;
lbxItems: TListBox;
pnlSeparator: TPanel;
btnAdd: TSpeedButton;
btnDelete: TSpeedButton;
btnClear: TSpeedButton;
btnEdit: TSpeedButton;
btnExit: TSpeedButton;
bvlSeparator: TBevel;
procedure FormShow(Sender: TObject);
procedure lbxItemsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure lbxItemsClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
AsSynAutoCorrect: TAsSynAutoCorrect;
end;
var
frmAutoCorrectEditor: TfrmAutoCorrectEditor;
Reg: TRegIniFile;
implementation
{$R *.DFM}
procedure TfrmAutoCorrectEditor.FormShow(Sender: TObject);
var
i: Integer;
begin
Reg := TRegIniFile.Create('');
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('Software\Aerodynamica\Components\AsSynAutoCorrect', True);
i := Reg.ReadInteger('', 'Top', 0);
if i <> 0 then Top := i;
i := Reg.ReadInteger('', 'Left', 0);
if i <> 0 then Left := i;
i := Reg.ReadInteger('', 'Width', 0);
if i <> 0 then Width := i;
i := Reg.ReadInteger('', 'Height', 0);
if i <> 0 then Height := i;
lbxItems.Items.Assign(AsSynAutoCorrect.ReplaceItems);
end;
procedure TfrmAutoCorrectEditor.lbxItemsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
CurrentText: String;
begin
CurrentText := lbxItems.Items[Index];
with lbxItems do
begin
Canvas.FillRect(Rect);
Canvas.TextOut(Rect.Left + 2, Rect.Top, HalfString(CurrentText, True));
Canvas.TextOut(Rect.Left + (lbxItems.ClientWidth div 2) + 2, Rect.Top, HalfString(CurrentText, False));
end;
end;
procedure TfrmAutoCorrectEditor.btnAddClick(Sender: TObject);
var
sReplaceFrom, sReplaceTo: String;
begin
if InputQuery('Add...', 'Replace:', sReplaceFrom) then
InputQuery('Add...', 'With:', sReplaceTo)
else
Exit;
with AsSynAutoCorrect do
begin
if (sReplaceFrom <> '') and (sReplaceTo <> '') then
begin
Add(sReplaceFrom, sReplaceTo);
lbxItems.Items.Assign(AsSynAutoCorrect.ReplaceItems);
end;
end;
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmAutoCorrectEditor.btnDeleteClick(Sender: TObject);
begin
if lbxItems.ItemIndex < 0 then
begin
MessageBox(0, 'Please select an item before executing this command!', 'Error', MB_APPLMODAL or MB_ICONERROR);
Exit;
end;
AsSynAutoCorrect.Delete(lbxItems.ItemIndex);
lbxItems.Items.Assign(AsSynAutoCorrect.ReplaceItems);
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmAutoCorrectEditor.btnEditClick(Sender: TObject);
var
sReplaceFrom, sReplaceTo, CurrentText: String;
begin
if lbxItems.ItemIndex < 0 then
begin
MessageBox(0, 'Please select an item before executing this command!', 'Error', MB_APPLMODAL or MB_ICONERROR);
Exit;
end;
CurrentText := AsSynAutoCorrect.ReplaceItems[lbxItems.ItemIndex];
sReplaceFrom := HalfString(CurrentText, True);
sReplaceTo := HalfString(CurrentText, False);
if InputQuery('Edit...', 'Replace:', sReplaceFrom) then
InputQuery('Edit...', 'With:', sReplaceTo)
else
Exit;
with AsSynAutoCorrect do
begin
Edit(lbxItems.ItemIndex, sReplaceFrom, sReplaceTo);
lbxItems.Items.Assign(AsSynAutoCorrect.ReplaceItems);
end;
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmAutoCorrectEditor.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmAutoCorrectEditor.btnClearClick(Sender: TObject);
begin
if MessageBox(0, 'Are you sure you want to clear the entire list?', 'Confirmation', MB_APPLMODAL or MB_YESNO or MB_ICONQUESTION) <> IDYES then Exit;
AsSynAutoCorrect.ReplaceItems.Clear;
lbxItems.Items.Clear;
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmAutoCorrectEditor.lbxItemsClick(Sender: TObject);
begin
btnDelete.Enabled := not lbxItems.ItemIndex < 0;
btnEdit.Enabled := not lbxItems.ItemIndex < 0;
end;
procedure TfrmAutoCorrectEditor.FormResize(Sender: TObject);
begin
if Height < 215 then Height := 215;
if Width < 272 then Width := 272;
lbxItems.Height := ClientHeight - 66;
lbxItems.Width := ClientWidth - 17;
pnlSeparator.Left := (lbxItems.Width div 2) + lbxItems.Left;
lblLabel2.Left := pnlSeparator.Left;
pnlSeparator.Height := lbxItems.Height;
end;
procedure TfrmAutoCorrectEditor.FormDestroy(Sender: TObject);
begin
Reg.WriteInteger('', 'Left', Left);
Reg.WriteInteger('', 'Top', Top);
Reg.WriteInteger('', 'Width', Width);
Reg.WriteInteger('', 'Height', Height);
Reg.Free;
end;
end.
|
unit uBase85;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
System.SysUtils, System.Classes, System.StrUtils, uBase;
function Encode(data: TBytes; PrefixPostfix: Boolean): String;
procedure EncodeBlock(count: Integer; sb: TStringBuilder;
encodedBlock: array of byte; tuple: UInt32);
function Decode(data: String; PrefixPostfix: Boolean): TBytes;
procedure DecodeBlock(bytes: Integer; decodedBlock: TBytes; tuple: LongWord);
Const
DefaultAlphabet: Array [0 .. 84] of String = ('!', '"', '#', '$', '%', '&',
'''', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u');
DefaultSpecial = Char(0);
Pow85: Array [0 .. 4] of UInt32 = (85 * 85 * 85 * 85, 85 * 85 * 85,
85 * 85, 85, 1);
Prefix = '<~';
Postfix = '~>';
implementation
function Encode(data: TBytes; PrefixPostfix: Boolean): String;
var
encodedBlock: array of byte;
decodedBlockLength, count: Integer;
sb: TStringBuilder;
tuple: UInt32;
b: byte;
begin
SetLength(encodedBlock, 5);
decodedBlockLength := 4;
sb := TStringBuilder.Create;
sb.Clear;
try
if (PrefixPostfix) then
begin
sb.Append(Prefix);
end;
count := 0;
tuple := 0;
for b in data do
begin
if (count >= (decodedBlockLength - 1)) then
begin
tuple := tuple or b;
if (tuple = 0) then
begin
sb.Append('z')
end
else
begin
EncodeBlock(Length(encodedBlock), sb, encodedBlock, tuple);
tuple := 0;
count := 0;
end;
end
else
begin
tuple := tuple or (UInt32(b shl (24 - (count * 8))));
inc(count);
end;
end;
if (count > 0) then
begin
EncodeBlock(count + 1, sb, encodedBlock, tuple);
end;
if (PrefixPostfix) then
begin
sb.Append(Postfix);
end;
result := sb.ToString;
finally
sb.Free;
end;
end;
procedure EncodeBlock(count: Integer; sb: TStringBuilder;
encodedBlock: array of byte; tuple: UInt32);
var
i: Integer;
begin
i := Pred(Length(encodedBlock));
while i >= 0 do
begin
encodedBlock[i] := byte(tuple mod 85);
tuple := tuple div 85;
dec(i);
end;
i := 0;
while i < count do
begin
sb.Append(DefaultAlphabet[encodedBlock[i]]);
inc(i);
end;
end;
function Decode(data: String; PrefixPostfix: Boolean): TBytes;
var
dataWithoutPrefixPostfix: String;
ms: TMemoryStream;
count, encodedBlockLength, i: Integer;
processChar: Boolean;
tuple: LongWord;
decodedBlock: TBytes;
c: Char;
begin
if isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
dataWithoutPrefixPostfix := data;
if (PrefixPostfix) then
begin
if not(StartsWith(dataWithoutPrefixPostfix, Prefix) or
EndsWith(dataWithoutPrefixPostfix, Postfix)) then
begin
raise Exception.Create('ASCII85 encoded data should begin with "' + Prefix
+ '" and end with "' + Postfix + '"');
end;
dataWithoutPrefixPostfix := Copy(dataWithoutPrefixPostfix, 3,
Length(dataWithoutPrefixPostfix) - 4);
end;
ms := TMemoryStream.Create;
try
count := 0;
tuple := UInt32(0);
encodedBlockLength := 5;
SetLength(decodedBlock, 4);
for c in dataWithoutPrefixPostfix do
begin
Case IndexStr(c, ['z']) of
0:
begin
if (count <> 0) then
begin
raise Exception.Create
('The character z is invalid inside an ASCII85 block.');
end;
decodedBlock[0] := 0;
decodedBlock[1] := 0;
decodedBlock[2] := 0;
decodedBlock[3] := 0;
ms.Write(decodedBlock, 0, Length(decodedBlock));
processChar := False;
end
else
begin
processChar := True;
end;
end;
if (processChar) then
begin
Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial);
tuple := tuple + UInt32(InvAlphabet[Ord(c)]) * Pow85[count];
inc(count);
if (count = encodedBlockLength) then
begin
DecodeBlock(Length(decodedBlock), decodedBlock, tuple);
ms.Write(decodedBlock, 0, Length(decodedBlock));
tuple := 0;
count := 0;
end;
end;
end;
if (count <> 0) then
begin
if (count = 1) then
begin
raise Exception.Create
('The last block of ASCII85 data cannot be a single byte.');
end;
dec(count);
tuple := tuple + Pow85[count];
DecodeBlock(count, decodedBlock, tuple);
for i := 0 to Pred(count) do
begin
ms.Write(decodedBlock[i], 1);
end;
end;
ms.Position := 0;
SetLength(result, ms.Size);
ms.Read(result[0], ms.Size);
finally
ms.Free;
end;
end;
procedure DecodeBlock(bytes: Integer; decodedBlock: TBytes; tuple: LongWord);
var
i: Integer;
begin
for i := 0 to Pred(bytes) do
begin
decodedBlock[i] := byte(tuple shr (24 - (i * 8)));
end;
end;
end.
|
unit Jobs;
{
Interface unit for Windows 2000 Job Objects.
james job object definition windows
}
interface
Uses Windows;
const
JOB_OBJECT_ASSIGN_PROCESS = $0001;
{$EXTERNALSYM JOB_OBJECT_ASSIGN_PROCESS}
JOB_OBJECT_SET_ATTRIBUTES = $0002;
{$EXTERNALSYM JOB_OBJECT_SET_ATTRIBUTES}
JOB_OBJECT_QUERY = $0004;
{$EXTERNALSYM JOB_OBJECT_QUERY}
JOB_OBJECT_TERMINATE = $0008;
{$EXTERNALSYM JOB_OBJECT_TERMINATE}
JOB_OBJECT_SET_SECURITY_ATTRIBUTES = $0010;
{$EXTERNALSYM JOB_OBJECT_SET_SECURITY_ATTRIBUTES}
JOB_OBJECT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $1F ;
{$EXTERNALSYM JOB_OBJECT_ALL_ACCESS}
//
// Extended Limits
//
JOB_OBJECT_LIMIT_PROCESS_MEMORY = $00000100;
{$EXTERNALSYM JOB_OBJECT_LIMIT_PROCESS_MEMORY}
JOB_OBJECT_LIMIT_JOB_MEMORY = $00000200;
{$EXTERNALSYM JOB_OBJECT_LIMIT_JOB_MEMORY}
JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = $00000400;
{$EXTERNALSYM JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION}
JOB_OBJECT_LIMIT_BREAKAWAY_OK = $00000800;
{$EXTERNALSYM JOB_OBJECT_LIMIT_BREAKAWAY_OK}
JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK = $00001000;
{$EXTERNALSYM JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK}
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = $00002000;
{$EXTERNALSYM JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE}
Type
TJobObjectInfoClass = Cardinal;
PJobObjectAssociateCompletionPort = ^ TJobObjectAssociateCompletionPort;
TJobObjectAssociateCompletionPort = Record
CompletionKey: Pointer;
CompletionPort: THandle;
End;
PJobObjectBasicLimitInformation = ^ TJobObjectBasicLimitInformation;
TJobObjectBasicLimitInformation = Record
PerProcessUserTimeLimit: TLargeInteger;
PerJobUserTimeLimit: TLargeInteger;
LimitFlags: DWORD;
MinimumWorkingSetSize: DWORD;
MaximumWorkingSetSize: DWORD;
ActiveProcessLimit: DWORD;
Affinity: DWORD;
PriorityClass: DWORD;
SchedulingClass: DWORD;
End;
PJobObjectBasicUIRestrictions = ^ TJobObjectBasicUIRestrictions;
TJobObjectBasicUIRestrictions = Record
UIRestrictionsClass: DWORD;
End;
PJobObjectEndOfJobTimeInformation = ^ TJobObjectEndOfJobTimeInformation;
TJobObjectEndOfJobTimeInformation = Record
EndOfJobTimeAction: DWORD;
End;
TIOCounters = Record {all fields should be actually unsigned int64's}
ReadOperationCount: Int64;
WriteOperationCount: Int64;
OtherOperationCount: Int64;
ReadTransferCount: Int64;
WriteTransferCount: Int64;
OtherTransferCount: Int64;
End;
PJobObjectExtendedLimitInformation = ^ TJobObjectExtendedLimitInformation;
TJobObjectExtendedLimitInformation = Record
BasicLimitInformation: TJobObjectBasicLimitInformation;
IoInfo: TIOCounters;
ProcessMemoryLimit: DWORD;
JobMemoryLimit: DWORD;
PeakProcessMemoryUsed: DWORD;
PeakJobMemoryUsed: DWORD;
End;
PJobObjectSecurityLimitInformation = ^ TJobObjectSecurityLimitInformation;
TJobObjectSecurityLimitInformation = Record
SecurityLimitFlags: DWORD;
JobToken: THandle;
SidsToDisable: PTokenGroups;
PrivilegesToDelete: PTokenPrivileges;
RestrictedSids: PTokenGroups;
End;
PJobObjectBasicAccountingInformation = ^ TJobObjectBasicAccountingInformation;
TJobObjectBasicAccountingInformation = Record
TotalUserTime: TLargeInteger;
TotalKernelTime: TLargeInteger;
ThisPeriodTotalUserTime: TLargeInteger;
ThisPeriodTotalKernelTime: TLargeInteger;
TotalPageFaultCount: DWORD;
TotalProcesses: DWORD;
ActiveProcesses: DWORD;
TotalTerminatedProcesses: DWORD;
End;
PJobObjectBasicAndIOAccountingInformation = ^ TJobObjectBasicAndIOAccountingInformation;
TJobObjectBasicAndIOAccountingInformation = Record
BasicInfo: TJobObjectBasicAccountingInformation;
IoInfo: TIOCounters;
End;
PJobObjectBasicProcessIDList = ^ TJobObjectBasicProcessIDList;
TJobObjectBasicProcessIDList = Record
NumberOfAssignedProcesses: DWORD;
NumberOfProcessIdsInList: DWORD;
ProcessIdList: Array [0 .. 0] of ULONG;
End;
Const
{For TJobObjectInfoClass}
JobObjectBasicAccountingInformation = 1;
JobObjectBasicLimitInformation = 2;
JobObjectBasicProcessIdList = 3;
JobObjectBasicUIRestrictions = 4;
JobObjectSecurityLimitInformation = 5;
JobObjectEndOfJobTimeInformation = 6;
JobObjectAssociateCompletionPortInformation = 7;
JobObjectBasicAndIoAccountingInformation = 8;
JobObjectExtendedLimitInformation = 9;
MaxJobObjectInfoClass = 10;
{Miscellaneous constants}
JOB_OBJECT_TERMINATE_AT_END_OF_JOB = 0;
JOB_OBJECT_POST_AT_END_OF_JOB = 1;
JOB_OBJECT_MSG_END_OF_JOB_TIME = 1;
JOB_OBJECT_MSG_END_OF_PROCESS_TIME = 2;
JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT = 3;
JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = 4;
JOB_OBJECT_MSG_NEW_PROCESS = 6;
JOB_OBJECT_MSG_EXIT_PROCESS = 7;
JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS = 8;
JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT = 9;
JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = 10;
JOB_OBJECT_LIMIT_WORKINGSET = $00000001;
JOB_OBJECT_LIMIT_PROCESS_TIME = $00000002;
JOB_OBJECT_LIMIT_JOB_TIME = $00000004;
JOB_OBJECT_LIMIT_ACTIVE_PROCESS = $00000008;
JOB_OBJECT_LIMIT_AFFINITY = $00000010;
JOB_OBJECT_LIMIT_PRIORITY_CLASS = $00000020;
JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME = $00000040;
JOB_OBJECT_LIMIT_SCHEDULING_CLASS = $00000080;
JOB_OBJECT_LIMIT_RESERVED1 = $00002000;
JOB_OBJECT_LIMIT_RESERVED2 = $00004000;
JOB_OBJECT_LIMIT_RESERVED3 = $00008000;
JOB_OBJECT_LIMIT_RESERVED4 = $00010000;
JOB_OBJECT_LIMIT_RESERVED5 = $00020000;
JOB_OBJECT_LIMIT_RESERVED6 = $00040000;
JOB_OBJECT_LIMIT_VALID_FLAGS = $0007FFFF;
JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS = $000000FF;
JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS = $00001FFF;
JOB_OBJECT_RESERVED_LIMIT_VALID_FLAGS = $0007FFFF;
JOB_OBJECT_UILIMIT_NONE = $00000000;
JOB_OBJECT_UILIMIT_HANDLES = $00000001;
JOB_OBJECT_UILIMIT_READCLIPBOARD = $00000002;
JOB_OBJECT_UILIMIT_WRITECLIPBOARD = $00000004;
JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS = $00000008;
JOB_OBJECT_UILIMIT_DISPLAYSETTINGS = $00000010;
JOB_OBJECT_UILIMIT_GLOBALATOMS = $00000020;
JOB_OBJECT_UILIMIT_DESKTOP = $00000040;
JOB_OBJECT_UILIMIT_EXITWINDOWS = $00000080;
JOB_OBJECT_UILIMIT_ALL = $000000FF;
JOB_OBJECT_UI_VALID_FLAGS = $000000FF;
JOB_OBJECT_SECURITY_NO_ADMIN = $00000001;
JOB_OBJECT_SECURITY_RESTRICTED_TOKEN = $00000002;
JOB_OBJECT_SECURITY_ONLY_TOKEN = $00000004;
JOB_OBJECT_SECURITY_FILTER_TOKENS = $00000008;
JOB_OBJECT_SECURITY_VALID_FLAGS = $0000000F;
CREATE_BREAKAWAY_FROM_JOB = $01000000;
Function AssignProcessToJobObject (hJob, hProcess: THandle): Bool; StdCall;
External Kernel32 Name 'AssignProcessToJobObject';
Function CreateJobObject (lpJobAttributes: PSecurityAttributes;
lpName: PAnsiChar): THandle; StdCall;
External Kernel32 Name 'CreateJobObjectA';
Function OpenJobObject (dwDesiredAccess: DWORD; bInheritHandle: Bool;
lpName: PAnsiChar): THandle; StdCall;
External Kernel32 Name 'OpenJobObjectA';
Function QueryInformationJobObject (hJob: THandle;
JobObjectInformationClass: TJobObjectInfoClass;
lpJobObjectInformation: Pointer;
cbJobObjectInformationLength: DWORD;
lpReturnLength: PDWORD): Bool; StdCall;
External Kernel32 Name 'QueryInformationJobObject';
Function SetInformationJobObject (hJob: THandle;
JobObjectInformationClass: TJobObjectInfoClass;
lpJobObjectInformation: Pointer;
cbJobObjectInformationLength: DWORD): Bool; StdCall;
External Kernel32 Name 'SetInformationJobObject';
Function TerminateJobObject (hJob: THandle; uExitCode: UINT): Bool; StdCall;
External Kernel32 Name 'TerminateJobObject';
implementation
end.
|
namespace GlHelper;
interface
type
ShapeVec = public record
vec : TVector3;
normal : TVector3;
texture : TVector2;
class method I (v1,v2,v3,n1,n2,n3 : Single) : ShapeVec;
end;
ShapeVecArray = public array of ShapeVec;
IntArray = public array of UInt16;
Shape = public class
private
faces : array of ShapeVecArray;
faceindexes : array of IntArray;
fmin, fmax : TVector3;
method fixcenter;
method checkMaxsize(Values : array of TVector3);
public
constructor (facecount : Integer);
constructor (const Box: Boolean);
method addFaceVecs(const &index : Integer; const Values : array of TVector3);
method addNormales(const &index : Integer; const Values : array of TVector3);
method addTexture(const &index : Integer; const Values : array of TVector2);
method addIndexes(const &index : Integer; const Values : array of Integer);
method getVecArray(const Layout : VertexLayout) : array of VertexArray;
end;
implementation
constructor Shape(facecount: Integer);
begin
inherited ();
faces := new ShapeVecArray[facecount];
faceindexes := new IntArray[facecount];
end;
method Shape.addFaceVecs(const &index: Integer; const Values: array of TVector3);
require
(&index >= 0) and (&index < length(faces));
begin
var i : Integer;
faces[&index] := new ShapeVec[Values.length];
for i := 0 to Values.length - 1 do
faces[&index][i].vec := Values[i];
if &index = 0 then
begin
fmin := Values[0];
fmax := fmin;
end;
checkMaxsize(Values);
end;
method Shape.addNormales(const &index: Integer; const Values: array of TVector3);
require
Values.length = faces[&index].length;
begin
var i : Integer;
for i := 0 to Values.length - 1 do
faces[&index][i].normal := Values[i];
end;
method Shape.addTexture(const &index: Integer; const Values: array of TVector2);
require
length(Values) = length(faces[&index]);
begin
var i : Integer;
for i := 0 to length(Values) - 1 do
faces[&index][i].texture := Values[i];
end;
method Shape.addIndexes(const &index: Integer; const Values: array of Integer);
require
(&index >= 0) and (&index < length(faceindexes));
begin
var i : Integer;
faceindexes[&index] := new UInt16[length(Values)];
for i := 0 to Values.length - 1 do
faceindexes[&index][i] := Values[i];
end;
method Shape.getVecArray(const Layout: VertexLayout): array of VertexArray;
begin
// fixcenter;
var i : Integer;
result := new VertexArray[faces.length];
for i := 0 to faces.length-1 do
begin
result[i] := new VertexArray(
Layout,faces[i].length * sizeOf(ShapeVec), faceindexes[i].length,
@faces[i][0].vec.X, @faceindexes[i][0]);
end;
end;
method Shape.checkMaxsize(Values: array of TVector3);
begin
for t in Values do
begin
fmin.X := Math.Min(fmin.X, t.X);
fmin.Y := Math.Min(fmin.Y, t.Y);
fmin.Z := Math.Min(fmin.Z, t.Z);
fmax.X := Math.Max(fmax.X, t.X);
fmax.Y := Math.Max(fmax.Y, t.Y);
fmax.Z := Math.Max(fmax.Z, t.Z);
end;
end;
method Shape.fixcenter;
begin
var i, j : Integer;
var Midpoint : TVector3 := ((fmax - fmin) / 2) + fmin;
for i := 0 to faces.length-1 do
for j := 0 to faces[i].length-1 do
begin
var s : ShapeVec := faces[i,j];
s.vec := s.vec-Midpoint;
faces[i,j] := s; //faces[i,j].v-Midpoint;
end;
end;
constructor Shape(const Box: Boolean);
const V: array of array of Single = [
// Positions // Normals
[
-0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, 0.5, -0.5, 0.0, 0.0, -1.0
],[
-0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 0.0, 1.0],[
-0.5, 0.5, 0.5, -1.0, 0.0, 0.0,
-0.5, 0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, 0.5, -1.0, 0.0, 0.0],[
0.5, 0.5, 0.5, 1.0, 0.0, 0.0,
0.5, 0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0],[
-0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, -1.0, 0.0],[
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 1.0, 0.0]];
INDICES: array of array of UInt16 = [
[0, 1, 2, 2, 3, 0],[
4, 5, 6, 6, 7, 4],[
8, 9, 10, 10, 11, 8],[
12, 13, 14, 14, 15, 12],[
16, 17, 18, 18, 19, 16],[
20, 21, 22, 22, 23, 20]];
begin
constructor (6);
var j : Integer ;
for j := 0 to 5 do
begin
faces[j]:= [
ShapeVec.I(V[j][0],V[j][1],V[j][2],V[j][3],V[j][4], V[j][5]),
ShapeVec.I(V[j][6],V[j][7],V[j][8],V[j][9],V[j][10], V[j][11]),
ShapeVec.I(V[j][12],V[0][13],V[j][14],V[j][15],V[j][16], V[j][17]),
ShapeVec.I(V[j][18],V[j][19],V[j][20],V[j][21],V[j][22], V[j][23])
];
faceindexes[j] := INDICES[j];
end;
fmin.Init(-0.5);
fmax.Init(0.5);
end;
class method ShapeVec.I(v1: Single; v2: Single; v3: Single; n1: Single; n2: Single; n3: Single) : ShapeVec;
begin
result.vec.X := v1;
result.vec.Y := v2;
result.vec.Z := v3;
result.normal.X := n1;
result.normal.Y := n2;
result.normal.Z := n3;
result.texture.S := 0;
result.texture.T := 0;
end;
end. |
unit SDUi18n_mo;
// .mo file format described at:
// http://www.gnu.org/software/hello/manual/gettext/MO-Files.html
interface
uses
Windows, Classes,
SDUClasses;
type
TMOHeader = record
Magic: DWORD;
FileFormatRevision: DWORD;
NumberOfStrings: DWORD;
OffsetOriginal: DWORD;
OffsetTranslated: DWORD;
HashTableSize: DWORD;
HashTableOffset: DWORD;
end;
TTransObj = class
protected
FHeader: TMOHeader;
FFile: TSDUFileStream;
FOriginal: TStringList;
FTranslated: TStringList;
public
constructor Create();
destructor Destroy();
function Load(filename: WideString): boolean;
procedure Unload();
function GetString_Original(idx: DWORD): WideString;
function GetString_Translated(idx: DWORD): WideString;
function GetText(original: WideString): WideString; overload;
function GetText(original: WideString; plural: integer): WideString; overload;
end;
implementation
uses
SysUtils,
SDUGeneral;
const
MO_MAGIC_1 = $950412de;
MO_MAGIC_2 = $de120495;
constructor TTransObj.Create();
begin
inherited;
FFile := nil;
FOriginal:= nil;
FTranslated:= nil;
end;
destructor TTransObj.Destroy();
begin
Unload();
inherited;
end;
function TTransObj.Load(filename: WideString): boolean;
var
retval: boolean;
theText: WideString;
lenStr: DWORD;
i: DWORD;
offset: ULONGLONG;
begin
retval := FALSE;
Unload();
FFile := TSDUFileStream.Create(filename, (fmOpenRead or fmShareDenyNone));
if (FFile <> nil) then
begin
FHeader.Magic := FFile.ReadDWORD_LE();
if (
(FHeader.Magic = MO_MAGIC_1) or
(FHeader.Magic = MO_MAGIC_2)
) then
begin
FHeader.FileFormatRevision := FFile.ReadDWORD_LE();
FHeader.NumberOfStrings := FFile.ReadDWORD_LE();
FHeader.OffsetOriginal := FFile.ReadDWORD_LE();
FHeader.OffsetTranslated := FFile.ReadDWORD_LE();
FHeader.HashTableSize := FFile.ReadDWORD_LE();
FHeader.HashTableOffset := FFile.ReadDWORD_LE();
FOriginal:= TStringList.Create();
for i:=1 to FHeader.NumberOfStrings do
begin
FFile.Position := FHeader.OffsetOriginal + ((i-1)*8);
lenStr := FFile.ReadDWORD_LE();
offset := FFile.ReadDWORD_LE();
FFile.Position := offset;
theText := FFile.ReadString(lenStr);
FOriginal.Add(theText);
end;
FTranslated:= TStringList.Create();
for i:=1 to FHeader.NumberOfStrings do
begin
FFile.Position := FHeader.OffsetTranslated + ((i-1)*8);
lenStr := FFile.ReadDWORD_LE();
offset := FFile.ReadDWORD_LE();
FFile.Position := offset;
theText := FFile.ReadString(lenStr);
FTranslated.Add(theText);
end;
retval := TRUE;
end;
end;
if not(retval) then
begin
Unload();
end;
Result := retval;
end;
procedure TTransObj.Unload();
begin
if (FFile <> nil) then
begin
FFile.Free();
end;
if (FOriginal <> nil) then
begin
FOriginal.Free();
end;
if (FTranslated <> nil) then
begin
FTranslated.Free();
end;
end;
function TTransObj.GetString_Original(idx: DWORD): WideString;
begin
Result := FOriginal[idx];
end;
function TTransObj.GetString_Translated(idx: DWORD): WideString;
begin
Result := FTranslated[idx];
end;
function TTransObj.GetText(original: WideString): WideString;
var
i: DWORD;
retval: WideString;
begin
retval := '';
for i:=0 to (FHeader.NumberOfStrings-1) do
begin
if (GetString_Original(i) = original) then
begin
retval := GetString_Translated(i);
break
end;
end;
if (retval = '') then
begin
retval := original;
end;
Result := retval;
end;
function TTransObj.GetText(original: WideString; plural: integer): WideString; overload;
begin
lplp
end;
END.
|
unit OptimizeImageUnit;
interface
uses
Windows,
Graphics,
GBlur2,
Dmitry.Graphics.Types,
uMemory;
type
TConvolutionMatrix = record
Matrix: array [0 .. 24] of Integer;
Devider: Integer;
end;
type
TRGBArray = array [0 .. 32677] of Windows.TRGBTriple; // bitmap element (API windows)
pRGBArray = ^TRGBArray; // type pointer to 3 bytes array
TArPRGBArray = array of PRGBArray;
procedure OptimizeImage(S,D : TBitmap; CallBack : TProgressCallBackProc = nil);
procedure MatrixEffectsW(Fa, Fb: Integer; Tscan3, Tscan2: TArPRGBArray; W1, H1: Integer; M: TConvolutionMatrix;
CallBack: TProgressCallBackProc = nil);
function Filterchoice(Numero: Integer): TConvolutionMatrix;
implementation
procedure MatrixEffectsW(Fa, Fb: Integer; Tscan3, Tscan2: TArPRGBArray; W1, H1: Integer; M: TConvolutionMatrix;
CallBack: TProgressCallBackProc = nil);
const
M3 : array[0..24] of integer = (1,1,1,1,1, // to detect if matrix is 3x3
1,0,0,0,1, // or 5x5
1,0,0,0,1,
1,0,0,0,1,
1,1,1,1,1);
var
X, Y: Integer;
R, G, B: Integer;
RR, GG, BB: Integer;
I: Integer; // index of matrix coefficients
Ix, Iy, Dx, Dy, D: Integer; // positions of sliding matrix
Terminating: Boolean;
begin
Terminating:=false;
if M.Devider = 0 then M.Devider := 1;
dx := 0;
For i := 0 to 24 do if (M.Matrix[i] AND M3[i]) <> 0 then inc(dx);
if dx = 0 then d := 1 else d := 2 ; // offset from center
For y := 0 to h1 do
begin
for x := 0 to w1 do
begin
RR := 0; GG := 0; BB := 0;
for dy := -d to d do
for dx := -d to d do
begin
// current pixel location
iy := y+dy;
ix := x+dx;
if (iy >= 1) and (iy <= h1) and // check limits
(ix >= 1) and (ix <= w1) then
begin
R := Tscan3[iy, ix].RgbtRed;
G := Tscan3[iy, ix].Rgbtgreen;
B := Tscan3[iy, ix].Rgbtblue;
end else
begin
R := Tscan3[y, x].RgbtRed; // outside : original pixel
G := Tscan3[y, x].Rgbtgreen;
B := Tscan3[y, x].Rgbtblue;
end;
i := 12 + dy * 5 + dx; // matrix factor position
RR := RR + R * M.Matrix[i]; // multiply color values bu matrix factor
GG := GG + G * M.Matrix[i];
BB := BB + B * M.Matrix[i];
end;
RR := RR div M.Devider; // divide results to preserve luminance
GG := GG div M.Devider;
BB := BB div M.Devider;
if RR > 255 then RR := 255 else if RR < 0 then RR := 0; // check color bounds
if GG > 255 then GG := 255 else if GG < 0 then GG := 0;
if BB > 255 then BB := 255 else if BB < 0 then BB := 0;
Tscan2[y,x].rgbtred := RR; // resulting pixel
Tscan2[y,x].rgbtgreen := GG;
Tscan2[y,x].rgbtblue := BB;
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(fa+Round(fb*y/(h1+1)),Terminating);
if Terminating then Break;
end;
end;
Function Filterchoice(Numero : integer): TConvolutionMatrix;
const
// Constants for convolution (filter) matrix 3x3 ou 5x5
// used to apply some effect on a picture. The current pixel (matrix center)
// is modified by the next pixels. The color values of each pixel are
// multiplied by the corresponding matrix value and added to a counter.
// This sum is then divided by the divisor to give the new "center" pixel
// color value. This allows integer computing.
// Last parameter is the divisor to obtain : Sum of elements / divisor = 1
// to preserve the pixel luminance.
// ** marked fonctions are used in this program, others are samples
F0 : array[0..9] of integer = ( 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); // neutral
F1 : array[0..9] of integer = ( 0, 0, 0, 0, 1, 1, 0, 1, 1, 4); // anti Alias
F2 : array[0..9] of integer = ( 1, 2, 1, 2,20, 2, 1, 2, 1, 32); // ** blur
F3 : array[0..25] of integer =
(1,2,4,2,1, 2,4,6,4,2, 4,6,8,6,4, 2,4,6,4,2, 1,2,4,2,1, 84); // blur more
F4 : array[0..9] of integer = (-1,-2,-1, -2,28,-2, -1,-2,-1, 16); // ** sharpen
F5 : array[0..9] of integer = ( 0,-1, 0, -1, 6,-1, 0,-1, 0, 2); // sharpen more
F6 : array[0..9] of integer = (-5,-5,-5, -5,42,-5, -5,-5,-5, 2); // Lithography
F7 : array[0..9] of integer = (-1,-1,-1, -1, 9,-1, -1,-1,-1, 1); // Hi pass
F8 : array[0..9] of integer = ( 0,-1, 0, -1, 1, 1, 0, 1, 0, 1); // emboss
F9 : array[0..9] of integer = ( 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); // engrave
FA : array[0..9] of integer = ( 1, 1, 1, 1,-8, 1, 1, 1, 1, 1); // lines
FB : array[0..9] of integer = ( 4, 4, 4, 4,-33,4, 4, 4, 4, 1); // ** edges
FC : array[0..9] of integer = ( 0,-1,-1, 0, 2, 0, 0, 0, 0, 1); // sculpture
// load 3x3 matrix
Procedure F9Load(af : array of integer);
var
i, j : integer;
begin
for j := 0 to 24 do Result.Matrix[j] := 0;
i := 0;
for j := 6 to 8 do begin Result.Matrix[j] := af[i]; inc(i); end;
for j := 11 to 13 do begin Result.Matrix[j] := af[i]; inc(i); end;
for j := 16 to 18 do begin Result.Matrix[j] := af[i]; inc(i); end;
Result.Devider := af[9];
end;
// load 5x5 matrix
Procedure F25load(af : array of integer);
var
i : integer;
begin
for i := 0 to 24 do Result.Matrix[i] := af[i];
Result.Devider := af[25];
end;
begin
case numero of
0 : F9Load(F0); // Neutral
1 : F9Load(F1); // anti allias
2 : F9Load(F2); // blur
3 : F25load(F3); // blur more
4 : F9Load(F4); // sharpen
5 : F9Load(F5); // sharpen more
6 : F9Load(F6); // Lithography
7 : F9Load(F7); // Hi pass
8 : F9Load(F8); // emboss
9 : F9Load(F9); // engrave
10: F9Load(FA); // lines
11: F9Load(FB); // edges
12: F9Load(FC); // sculpture
end;
end;
procedure OptimizeImage(S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
var
X, Y: Integer;
R3, G3, B3, R2, G2, B2, R4: Integer;
Tscan2, Tscan3, Tscan4: TArPRGBArray;
Terminating: Boolean;
Temp1: TBitmap;
begin
Terminating := False;
Temp1 := TBitmap.Create;
try
Temp1.PixelFormat := pf24bit;
S.PixelFormat := pf24bit;
D.Assign(S);
if Assigned(CallBack) then
CallBack(5, Terminating);
D.PixelFormat := pf24bit;
SetLength(Tscan2, S.Height);
SetLength(Tscan3, S.Height);
SetLength(Tscan4, S.Height);
Temp1.SetSize(S.Width, S.Height);
for Y := 0 to S.Height - 1 do
begin
Tscan2[Y] := D.ScanLine[Y];
Tscan3[Y] := S.ScanLine[Y];
Tscan4[Y] := Temp1.ScanLine[Y];
end;
MatrixEffectsW(5, 20, Tscan3, Tscan4, S.Width - 1, S.Height - 1, Filterchoice(11));
GBlurWX(25, 20, Temp1, GBlur2.TArPRGBArray(Tscan4), 2, CallBack);
GBlurWX(45, 20, D, GBlur2.TArPRGBArray(Tscan2), 3, CallBack);
for y := 0 to S.height-1 do
begin
for x := 0 to S.width-1 do
begin
R3 := Tscan3[y,x].Rgbtred; // current image
G3 := Tscan3[y,x].Rgbtgreen;
B3 := Tscan3[y,x].Rgbtblue;
R2 := Tscan2[y,x].Rgbtred; // blurred image
G2 := Tscan2[y,x].Rgbtgreen;
B2 := Tscan2[y,x].Rgbtblue;
R4 := Tscan4[y,x].Rgbtred; // mask
if R4 > 0 then
begin
Tscan2[y,x].Rgbtred := (R2+R3*3) div 4; // edges
Tscan2[y,x].Rgbtgreen := (G2+G3*3) div 4;
Tscan2[y,x].Rgbtblue := (B2+B3*3) div 4;
end else
begin
Tscan2[y,x].Rgbtred := (R2*7+R3) div 8; // blur areas
Tscan2[y,x].Rgbtgreen := (G2*7+G3) div 8;
Tscan2[y,x].Rgbtblue := (B2*7+B3) div 8;
end;
end;
if y mod 50=0 then
If Assigned(CallBack) then CallBack(65+Round(35*y/S.Height),Terminating);
if Terminating then Break;
end;
finally
F(Temp1);
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ExtDlgs, Menus, ComCtrls;
type
// thread de traitement de l'image
TTraitement=class(tthread)
private
ThFinal:tbitmap; // bitmap temporaire avec le résultat
ThOriginal:tbitmap; // bitmap temporaire avec la source
progression:integer; // progression du traitement (en %)
TabConLum:array[0..255] of byte;// table précalculée du contraste/luminosité
procedure AfficheResultat; // synchronize le résultat local avec le bitmap de Form1
procedure AfficheProgression; // synchronize la progression local avec le TProgressBar de Form1
protected
procedure Execute; override; // boucle principale de traitement
public
Angle:integer; // paramètres de traitements
variation:integer;
taille:integer;
Contraste:integer;
Luminosite:integer;
longueur:integer;
quantite:integer;
Restart:boolean; // = true pour forcé le redémarrage du traitement au début
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
end;
TForm1 = class(TForm)
Panel1: TPanel;
MainMenu1: TMainMenu;
Fichier1: TMenuItem;
Ouvrir1: TMenuItem;
Quitter1: TMenuItem;
N1: TMenuItem;
ScrollBox1: TScrollBox;
PaintBox1: TPaintBox;
Label1: TLabel;
ScrollBar1: TScrollBar;
ScrollBar2: TScrollBar;
Label2: TLabel;
ScrollBar3: TScrollBar;
Label3: TLabel;
ScrollBar4: TScrollBar;
Label4: TLabel;
ScrollBar5: TScrollBar;
Label5: TLabel;
OpenPictureDialog1: TOpenPictureDialog;
SavePictureDialog1: TSavePictureDialog;
Enregistrer1: TMenuItem;
Label6: TLabel;
ScrollBar6: TScrollBar;
ScrollBar7: TScrollBar;
Label7: TLabel;
ProgressBar1: TProgressBar;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure PaintBox1Paint(Sender: TObject);
procedure Ouvrir1Click(Sender: TObject);
procedure ScrollBar1Change(Sender: TObject);
procedure Enregistrer1Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
Final:tbitmap;
Original:tbitmap;
end;
var
Form1: TForm1;
Traitement:TTraitement;
implementation
{$R *.dfm}
constructor TTraitement.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
// on crée le bitmap local
thOriginal := TBitmap.Create;
form1.Original.Canvas.Lock; // <<---- Ok
// on y transfert l'image chargé dans Form1
thOriginal.Assign(form1.Original);
form1.Original.Canvas.UnLock; // <<---- Ok
thOriginal.PixelFormat:=pf24bit;
// on crée un deuxième bitmap pour le résultat
thFinal := TBitmap.Create;
thFinal.width:=thOriginal.Width;
thFinal.Height:=thOriginal.Height;
Restart:=true;
end;
destructor TTraitement.Destroy;
begin
// destruction des bitmaps
thFinal.Free;
thOriginal.Free;
inherited Destroy;
end;
// on met juste à jour la position de la progressbar
procedure TTraitement.AfficheProgression;
begin
form1.ProgressBar1.Position:=progression;
end;
// on met à jour le bitmap FINAL et le paintbox de Form1
procedure TTraitement.AfficheResultat;
begin
form1.Final.canvas.Draw(0,0,thfinal);
form1.PaintBox1.Canvas.Draw(0,0,thfinal);
end;
//traitement principal
procedure TTraitement.Execute;
var
i,j,l,tl,x,y,ii,jj,maxIt,progress:integer;
a:single;
r,v,b:integer;
lum,cont,tai,ang,varia,lon,quant:integer;
im1:pbytearray;
begin
while not terminated do
begin
progression:=0;
synchronize(AfficheProgression);
// on attend un changement dans les paramètres
while not restart and not terminated do ;
restart:=false;
// on "fige" les paramètres
lum:=luminosite;
cont:=contraste;
tai:=taille;
ang:=angle;
varia:=variation;
lon:=longueur;
quant:=quantite;
//précalcul du contraste luminosité
for i:=0 to 255 do
begin
// luminosité
l:=i+((255-i)*Lum) Div 255;
// contraste
tl :=(Abs(127-l)*Cont) Div 255;
If (l > 127) Then l:=l+tl Else l:=l-tl;
if l<0 then l:=0 else if l>255 then l:=255;
TabConLum[i]:=l
end;
thfinal.Canvas.Lock; // <<---- Pourquoi ???
thoriginal.Canvas.Lock; // <<---- Pourquoi ???
// on efface le résultat
thfinal.Canvas.FillRect(thfinal.canvas.ClipRect);
// on calcul le nombre d'itération
maxIt:=thoriginal.Height*thoriginal.width*quant div 100;
for j:=1 to MaxIt do
begin
// si on demande d'arrêter, ben... heu... on arrête...
if restart or terminated then break;
// on choisi un pixel quelconque dans l'original
x:=random(thoriginal.Width-7);
y:=random(thoriginal.Height-7);
r:=0;
v:=0;
b:=0;
// on fait la moyenne des 49 pixels autours
for jj:=y to y+6 do
begin
im1:=thoriginal.ScanLine[jj];
for ii:=x to x+6 do
begin
// on applique en même temps le contraste/luminosité
r:=r+TabConLum[im1[ii*3+2]];
v:=v+TabConLum[im1[ii*3+1]];
b:=b+TabConLum[im1[ii*3+0]];
end;
end;
// on choisi un angle pour le trait de crayon
a:=(angle+random(varia*2)-varia)*pi/180;
// on trace le trait avec la couleur moyenne dans le résultat
thfinal.Canvas.Pen.Width:=tai;
thfinal.Canvas.Pen.Color:=rgb(r div 49,v div 49,b div 49);
thfinal.canvas.MoveTo(x,y);
thfinal.canvas.LineTo(round(x+lon*cos(a)),round(y+lon*sin(a)));
// on met éventuellement à jour la progressbar de form1
progress:=j*100 div MaxIt;
if progression<>progress then
begin
progression:=progress;
synchronize(AfficheProgression);
end;
end;
thoriginal.Canvas.UnLock; // <<---- Pourquoi ???
thfinal.Canvas.unLock; // <<---- Pourquoi ???
// si aucune relance n'est demandée, on affiche le résultat dans le PaintBox
if not restart and not terminated then synchronize(AfficheResultat);
end;
end;
// TFORM1 ---- TFORM1 ---- TFORM1 ---- TFORM1 ---- TFORM1 ---- TFORM1 ----
procedure TForm1.FormCreate(Sender: TObject);
begin
original:=tbitmap.Create;
final:=tbitmap.Create;
Traitement:=TTraitement.Create(false);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
traitement.Terminate;
traitement.WaitFor;
original.Free;
final.Free;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
begin
paintbox1.Canvas.Draw(0,0,final);
end;
procedure TForm1.Ouvrir1Click(Sender: TObject);
begin
if not openpicturedialog1.Execute then exit;
traitement.Terminate;
traitement.WaitFor;
original.LoadFromFile(openpicturedialog1.FileName);
original.PixelFormat:=pf24bit;
paintbox1.Width:=original.Width;
paintbox1.Height:=original.Height;
final.Assign(original);
Traitement:=TTraitement.Create(false);
ScrollBar1Change(nil);
end;
procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
Traitement.Contraste:=scrollbar1.Position;
Traitement.Luminosite:=scrollbar2.Position;
Traitement.taille:=scrollbar3.Position;
Traitement.Angle:=scrollbar4.Position;
Traitement.Variation:=scrollbar5.Position;
Traitement.Longueur:=scrollbar6.Position;
Traitement.quantite:=scrollbar7.Position;
label1.caption:=format('Contrast: %d%%',[scrollbar1.Position*100 div 255]);
label2.caption:=format('Luminosité: %d%%',[scrollbar2.Position*100 div 255]);
label3.caption:=format('Taille du crayon: %d',[scrollbar3.Position]);
label4.caption:=format('Angle Principal: %d°',[scrollbar4.Position]);
label5.caption:=format('Variation: ±%d°',[scrollbar5.Position]);
label6.caption:=format('Longueur du trait: %d',[scrollbar6.Position]);
label7.caption:=format('Quantité de Trait: %d%%',[scrollbar7.Position]);
Traitement.Restart:=true;
end;
procedure TForm1.Enregistrer1Click(Sender: TObject);
begin
if not savepicturedialog1.Execute then exit;
final.SaveToFile(savepicturedialog1.FileName);
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniGUIBaseClasses, uniPanel,
cfs.GCharts.uniGUI, Data.DB, Datasnap.DBClient, uniBasicGrid, uniDBGrid,
uniMemo, uniDBNavigator, uniToolBar, uniButton;
type
TMainForm = class(TUniForm)
UniPanel1: TUniPanel;
UniPanel2: TUniPanel;
uniGChartsFrame1: TuniGChartsFrame;
DataSource1: TDataSource;
UniDBGrid1: TUniDBGrid;
UniButton1: TUniButton;
procedure UniFormCreate(Sender: TObject);
procedure UniButton1Click(Sender: TObject);
procedure uniGChartsFrame1Select(Sender: TuniGChartsFrame;
const ChartId, Row, Column, Value, Category: string);
private
FClientDataSet: TClientDataSet;
procedure CreateClientDataSet;
procedure GenerateChart;
public
end;
function MainForm: TMainForm;
implementation
{$R *.dfm}
uses
uniGUIVars, MainModule, cfs.GCharts;
function MainForm: TMainForm;
begin
Result := TMainForm(UniMainModule.GetFormInstance(TMainForm));
end;
procedure TMainForm.UniFormCreate(Sender: TObject);
begin
CreateClientDataSet;
GenerateChart;
end;
procedure TMainForm.CreateClientDataSet;
begin
FClientDataSet := TClientDataSet.Create(Self);
FClientDataSet.FieldDefs.Add('Year', ftString, 4, False);
FClientDataSet.FieldDefs.Add('Sales', ftCurrency, 0, False);
FClientDataSet.FieldDefs.Add('Expenses', ftCurrency, 0, False);
FClientDataSet.CreateDataSet;
FClientDataSet.Open;
FClientDataSet.AppendRecord(['2016', 1000, 400]);
FClientDataSet.AppendRecord(['2017', 1170, 460]);
FClientDataSet.AppendRecord(['2018', 660, 1120]);
FClientDataSet.AppendRecord(['2019', 1030, 540]);
FClientDataSet.AppendRecord(['2020', 880, 600]);
FClientDataSet.AppendRecord(['2021', null, null]);
DataSource1.DataSet := FClientDataSet;
end;
procedure TMainForm.GenerateChart;
var
//Defined as TInterfacedObject. No need try..finally
AreaChart: IcfsGChartProducer;
ColumnChart: IcfsGChartProducer;
Profit: Currency;
begin
AreaChart := TcfsGChartProducer.Create;
AreaChart.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART;
AreaChart.Data.AssignFromDataSet(FClientDataSet);
AreaChart.Options.Title('Company Performance');
AreaChart.Options.Legend('position', 'bottom');
AreaChart.LibraryLanguage := UniSession.Language;
ColumnChart := TcfsGChartProducer.Create;
ColumnChart.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
ColumnChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Profit'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE)
]);
FClientDataSet.First;
while not FClientDataSet.eof do
begin
Profit := FClientDataSet.FieldByName('Sales').AsCurrency - FClientDataSet.FieldByName('Expenses').AsCurrency;
ColumnChart.Data.AddRow;
ColumnChart.Data.SetValue(0, FClientDataSet.FieldByName('Year').Value);
ColumnChart.Data.SetValue(1, Profit);
if Profit < 0 then
ColumnChart.Data.SetValue(2, 'red');
FClientDataSet.Next;
end;
ColumnChart.Options.Title('Company Profit');
ColumnChart.Options.Legend('position', 'none');
ColumnChart.LibraryLanguage := UniSession.Language;
// Generate
uniGChartsFrame1.DocumentInit;
uniGChartsFrame1.DocumentSetBody(
'<div style="display: flex; width: 100%; height: 100%;">'
+ '<div id="AreaChart" style="width: 50%"></div>'
+ '<div id="ColumnChart" style="width: 50%"></div>'
+ '</div>'
+ '</div>'
);
uniGChartsFrame1.DocumentGenerate('AreaChart', AreaChart);
uniGChartsFrame1.DocumentGenerate('ColumnChart', ColumnChart);
uniGChartsFrame1.DocumentPost;
end;
procedure TMainForm.UniButton1Click(Sender: TObject);
begin
GenerateChart;
end;
procedure TMainForm.uniGChartsFrame1Select(Sender: TuniGChartsFrame; const ChartId, Row, Column, Value, Category: string);
begin
ShowMessageN(Format('ChartId=%s, Row=%s, Column=%s, Value=%s, Category=%s', [ChartId, Row, Column, Value, Category]));
end;
initialization
RegisterAppFormClass(TMainForm);
end.
|
unit Suprema;
{
Written by: Alejandro Granera V.
agranera@biotracksoftware.com
www.biotracksoftware.com
}
interface
uses Windows, ActiveX, Classes, Graphics, StdVCL, Variants, ComCtrls, SysUtils;
type
UFS_STATUS = Integer;
HUFScanner = Pointer;
UFM_STATUS = TOleEnum;
HUFMatcher = Pointer;
const
MAX_TEMPLATESIZE=384;
MAX_NUMTEMPLATES=4000; // 2000 EMPLEADOS, 2 huellas para cada uno
MIN_QUALITY=50;
type
TTemplete2Array = array of array of byte;
PTemplete2Array = ^TTemplete2Array;
var
UFS_result : UFS_Status;
UFM_result : UFM_Status;
pnScannerNumber:Pointer;
szErrorString:WideString;
Scanner : HUFScanner;
serialstr : PWideChar;
INIT_OK :Boolean;
Template1 : String; // Template1 represents the fingerprint stored in
// the database (as a string or memo field) and Template2 is the
// fingerprint captured to be compared with Template1
Template1Byte,Template2Byte : Array [0..MAX_TEMPLATESIZE-1] of Byte; // represent the fingerprints as an Array of Bytes
sizeTemplate1 : word;
sizeTemplate2:Integer;
// hMatcher : HUFMATCHER;
const
{Constants for UFS_Status}
UFS_OK = 0;
UFS_ERROR = -1;
UFS_ERR_NO_LICENSE = -101;
UFS_ERR_LICENSE_NOT_MATCH = -102;
UFS_ERR_LICENSE_EXPIRED = -103;
UFS_ERR_NOT_SUPPORTED = -111;
UFS_ERR_INVALID_PARAMETERS = -112;
UFS_ERR_ALREADY_INITIALIZED = -201;
UFS_ERR_NOT_INITIALIZED = -202;
UFS_ERR_DEVICE_NUMBER_EXCEED = -203;
UFS_ERR_LOAD_SCANNER_LIBRARY = -204;
UFS_ERR_CAPTURE_RUNNING = -211;
UFS_ERR_CAPTURE_FAILED = -212;
UFS_ERR_NOT_GOOD_IMAGE = -301;
UFS_ERR_EXTRACTION_FAILED = -302;
UFS_ERR_CORE_NOT_DETECTED = -351;
UFS_ERR_CORE_TO_LEFT = -352;
UFS_ERR_CORE_TO_LEFT_TOP = -353;
UFS_ERR_CORE_TO_TOP = -354;
UFS_ERR_CORE_TO_RIGHT_TOP = -355;
UFS_ERR_CORE_TO_RIGHT = -356;
UFS_ERR_CORE_TO_RIGHT_BOTTOM = -357;
UFS_ERR_CORE_TO_BOTTOM = -358;
UFS_ERR_CORE_TO_LEFT_BOTTOM = -359;
{Constants for UFS_Param}
UFS_PARAM_TIMEOUT = 201;
UFS_PARAM_BRIGHTNESS = 202;
UFS_PARAM_SENSITIVITY = 203;
UFS_PARAM_SERIAL = 204;
UFS_PARAM_DETECT_CORE = 301;
UFS_PARAM_TEMPLATE_SIZE = 302;
UFS_PARAM_USE_SIF = 311;
{Constants for UFS_Scanner_Type}
UFS_SCANNER_TYPE_SFR200 = 1001;
UFS_SCANNER_TYPE_SFR300 = 1002;
UFS_SCANNER_TYPE_SFR300v2 = 1003;
{Constants for UFM_Status}
UFM_OK = 0;
UFM_ERROR = -1;
UFM_ERR_NO_LICENSE = -101;
UFM_ERR_LICENSE_NOT_MATCH = -102;
UFM_ERR_LICENSE_EXPIRED = -103;
UFM_ERR_NOT_SUPPORTED = -111;
UFM_ERR_INVALID_PARAMETERS = -112;
UFM_ERR_MATCH_TIMEOUT = -401;
UFM_ERR_MATCH_ABORTED = -402;
UFM_ERR_TEMPLATE_TYPE = -411;
{Constants for UFM_Param}
UFM_PARAM_FAST_MODE = 301;
UFM_PARAM_SECURITY_LEVEL = 302;
UFM_PARAM_USE_SIF = 311;
MAX_TEMPLATE_SIZE = 384;
function UFS_Init: UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_Update: UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_Uninit: UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_GetScannerHandle(nScannerIndex: Integer;var phScanner: HUFSCANNER): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_GetParameter_B(hScanner: HUFSCANNER;nParam: Integer;var pValue: PWideChar): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_SetParameter(hScanner: HUFSCANNER;nParam: Integer; pValue: PInteger): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_CaptureSingleImage(hScanner: HUFSCANNER): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_Extract(hScanner: HUFSCANNER;var pTemplate: Byte;var pnTemplateSize: Integer;var pnEnrollQuality: Integer): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_DrawCaptureImageBuffer(hScanner: HUFSCANNER;hDC: HDC;nLeft: Integer;nTop: Integer;nRight: Integer;nBottom: Integer;bCore: Integer): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_ClearCaptureImageBuffer(hScanner: HUFSCANNER): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_GetErrorString(res : UFS_Status; szErrorString:WideString): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFS_GetScannerNumber(var pnScannerNumber:Pointer): UFS_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFM_Create(var phMatcher: HUFMATCHER): UFM_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFM_Delete(hMatcher: HUFMATCHER): UFM_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function UFM_Verify(hMatcher: HUFMATCHER;var pTemplate1: Byte;nTemplate1Size: Integer;var pTemplate2: Byte;nTemplate2Size: Integer;var bVerifySucceed: Integer): UFM_STATUS cdecl {$IFDEF WIN32} stdcall {$ENDIF};
function InitDevice(StatusBar:TstatusBar): UFS_Status;
function CaptureFingerprint1 (Statusbar:TStatusBar) : String;
procedure CaptureFingerprint2;
procedure ConvertStringIntoByteArray(pString : String;var TemplateByte:Array of Byte; var sizeTemplate:word);
implementation
function UFS_Init; external 'UFSCANNER.DLL';
function UFS_Update; external 'UFSCANNER.DLL';
function UFS_Uninit; external 'UFSCANNER.DLL';
function UFS_GetScannerHandle; external 'UFSCANNER.DLL';
function UFS_GetParameter_B; external 'UFSCANNER.DLL';
function UFS_SetParameter; external 'UFSCANNER.DLL';
function UFS_CaptureSingleImage; external 'UFSCANNER.DLL';
function UFS_Extract; external 'UFSCANNER.DLL';
function UFS_DrawCaptureImageBuffer; external 'UFSCANNER.DLL';
function UFS_ClearCaptureImageBuffer; external 'UFSCANNER.DLL';
function UFS_GetErrorString; external 'UFSCANNER.DLL';
function UFS_GetScannerNumber; external 'UFSCANNER.DLL';
function UFM_Create; external 'UFMATCHER.DLL';
function UFM_Delete; external 'UFMATCHER.DLL';
function UFM_Verify; external 'UFMATCHER.DLL';
function InitDevice(StatusBar:TstatusBar): UFS_Status;
VAR
TimeOut, value:Integer;
bvalue :Boolean;
begin
//init device
ufs_result:=UFS_init;
result := UFS_result;
if ufs_result=ufs_ok then begin
UFS_GetScannerHandle(0,Scanner);
// Set timeout for capturing images to 5 seconds
TimeOut := 5000;
UFS_SetParameter(Scanner,UFS_PARAM_TIMEOUT,@TimeOut);
// Set template size to 384 bytes
value := MAX_TEMPLATE_SIZE;
UFS_SetParameter(Scanner, UFS_PARAM_TEMPLATE_SIZE, @value);
value := 4;
UFS_SetParameter(Scanner,UFS_PARAM_SENSITIVITY, @value);
// Set not to detect core when extracting template
bvalue := False;
UFS_SetParameter(Scanner, UFS_PARAM_DETECT_CORE, @bvalue);
UFS_GetParameter_B(Scanner,UFS_PARAM_SERIAL,serialstr);
if StatusBar <> nil then begin
StatusBar.Panels[0].Text := 'Init OK';
StatusBar.Panels[1].Text := ('Serial number: '+ serialstr);
end;
end else begin
ufs_result := UFS_GetErrorString(ufs_result,szErrorString);
if StatusBar <> nil then begin
StatusBar.Panels[1].Text := '';
StatusBar.Panels[1].Text := 'Init Error: ' + szErrorString;
end;
end;
end;
function CaptureFingerprint1 (Statusbar:TStatusBar) : String;
{Captures a fingerprint from the buffer and puts it in the string variable Template1}
var
Buffer : Array [0..MAX_TEMPLATESIZE-1] of Byte;
i, TSize, Quality : Integer;
tempFingerprint : String;
begin
//fingerprint is a Hexadecimal String, you can store it in the database in a string or memo field.
tempfingerprint:='';
ufs_result:=UFS_Extract(Scanner,Buffer[0],TSize,Quality);
if ((ufs_result=ufs_ok) and (Quality>=MIN_QUALITY)) then begin
for i := 0 to TSize - 1 do tempfingerprint:=tempfingerprint+inttohex(Buffer[i],2);
StatusBar.Panels[0].Text := ('Enroll OK, quality: '+inttostr(quality)+' %');
end else
StatusBar.Panels[0].Text := ('Enroll Error');
result:=tempfingerprint;
end;
procedure CaptureFingerprint2;
{Captures a fingerprint from the Buffer and puts it in Template2Byte}
var
Quality : Integer;
begin
ufs_result:=UFS_Extract(Scanner,Template2Byte[0],sizeTemplate2,Quality);
// you can handle the Quality result
end;
procedure ConvertStringIntoByteArray(pString : String; var TemplateByte:Array of Byte; var sizeTemplate:Word);
//put the pString parameter into TemplateByte1 Array, for example to get a string fingerprint
//stored in a database as string field and put it into the Array
var
i : integer;
temp : String;
begin
for i:=0 to Length(TemplateByte)-1 do begin
TemplateByte[i]:=255;
end;
i:=1;
while i<= (length(pString)/2) do begin
temp:='$'+pString[2*(i-1)+1]+pString[2*i];
TemplateByte[i-1]:=strtoint(temp);
i:=i+1;
end;
sizeTemplate:=i-1;
end;
//****************************************************************************************************
end.
|
unit IdSASL_NTLM;
interface
{$i IdCompilerDefines.inc}
uses
IdSASL,
IdSASLUserPass;
const
DEF_LMCompatibility = 0;
type
TIdSASLNTLM = class(TIdSASLUserPass)
protected
FDomain : String;
FLMCompatibility : LongWord;
procedure InitComponent; override;
public
class function ServiceName: TIdSASLServiceName; override;
function TryStartAuthenticate(const AHost, AProtocolName: string; var VInitialResponse: string): Boolean; override;
function StartAuthenticate(const AChallenge, AHost, AProtocolName:string) : String; override;
function ContinueAuthenticate(const ALastResponse, AHost, AProtocolName: String): string; override;
function IsReadyToStart: Boolean; override;
property Domain : String read FDomain write FDomain;
{
The LMCompatibility property is designed to work directly with the "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LMCompatibilityLevel"
and will act as this key is documented. This effects how NTLM authentication
is done on the server. We do not pull the value from the registry because other systems
don't have a registry and you may want to set this to a value that's different from
your registry.
http://davenport.sourceforge.net/ntlm.html describes these like this:
=======================================================================
Level | Sent by Client | Accepted by Server
=======================================================================
0 | LM NTLM | LM NTLM /LMv2 NTLMv2
1 | LM NTLM | LM NTLM /LMv2 NTLMv2
2 | NTLM (is sent in both feilds) | LM NTLM /LMv2 NTLMv2
3 | LMv2 NTLMv2 | LM NTLM /LMv2 NTLMv2
4 | LMv2 NTLMv2 | NTLM /LMv2 NTLMv2
5 | LMv2 NTLMv2 | LMv2 NTLMv2
}
property LMCompatibility : LongWord read FLMCompatibility write FLMCompatibility default DEF_LMCompatibility;
end;
implementation
uses
IdFIPS, IdNTLMv2, IdGlobal;
//uses IdNTLM;
{ TIdSASLNTLM }
function TIdSASLNTLM.ContinueAuthenticate(const ALastResponse, AHost,
AProtocolName: String): string;
var
LMsg : TIdBytes;
LNonce : TIdBytes; //this is also called the challange
LTargetName, LTargetInfo : TIdBytes;
LFlags : LongWord;
LDomain, LUserName : String;
LEncoding: IIdTextEncoding;
begin
LEncoding := IndyTextEncoding_8Bit;
LMsg := ToBytes(ALastResponse, LEncoding{$IFDEF STRING_IS_ANSI}, LEncoding{$ENDIF});
IdNTLMv2.ReadType2Msg(LMsg, LFlags, LTargetName, LTargetInfo, LNonce);
IdGlobal.DebugOutput('Type 2 Flags = '+ DumpFlags(LFlags));
GetDomain(GetUsername, LUsername, LDomain);
Result := BytesToStringRaw( BuildType3Msg(LDomain, LDomain, GetUsername, GetPassword,
LFlags, LNonce, LTargetName, LTargetInfo, FLMCompatibility) );
end;
procedure TIdSASLNTLM.InitComponent;
begin
inherited InitComponent;
Self.FLMCompatibility := DEF_LMCompatibility;
end;
function TIdSASLNTLM.IsReadyToStart: Boolean;
begin
Result := (not GetFIPSMode) and (inherited IsReadyToStart) and
NTLMFunctionsLoaded;
end;
class function TIdSASLNTLM.ServiceName: TIdSASLServiceName;
begin
Result := 'NTLM'; {Do not localize}
end;
function TIdSASLNTLM.TryStartAuthenticate(const AHost, AProtocolName: string;
var VInitialResponse: string): Boolean;
var
LDomain, LUsername : String;
begin
GetDomain(GetUsername, LUsername, LDomain);
if LDomain = '' then begin
LDomain := FDomain;
end;
VInitialResponse := BytesToStringRaw(IdNTLMv2.BuildType1Msg(LDomain, LDomain, FLMCompatibility));
Result := True;
end;
function TIdSASLNTLM.StartAuthenticate(const AChallenge, AHost, AProtocolName: string): String;
begin
TryStartAuthenticate(AHost, AProtocolName, Result);
end;
end.
|
unit uFrmEmailBuilder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls,
Email, Buttons, DB, DBClient, Contnrs;
type
TFrmEmailBuilder = class(TFrmParent)
Label1: TLabel;
edtSubject: TEdit;
mmReceivers: TMemo;
Label2: TLabel;
btnSend: TButton;
Label3: TLabel;
memBody: TMemo;
Emails: TEmail;
Label5: TLabel;
edtAttached: TEdit;
btnOpenFile: TSpeedButton;
rbEmailTo: TRadioGroup;
OP: TOpenDialog;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSendClick(Sender: TObject);
procedure rbEmailToClick(Sender: TObject);
procedure btnOpenFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
sAll : String;
FEmailList,
FCustomerEmail : String;
FIDCustomer : Integer;
FCustomerList : TClientDataSet;
FProductsList : TClientDataSet;
Customers: TObjectList;
Products: TObjectList;
procedure BuildEmailList; overload;
procedure BuildEmailList(argCustomers: TObjectList); overload;
procedure BuildBody; overload;
procedure BuildBody(argProducts: TObjectList); overload;
procedure RefreshSendList;
public
procedure Start(IDCustomer : Integer; Customer, Products : TClientDataSet); overload;
procedure Start(argIdCustomer: Integer; argCustomerList, argProductList: TObjectList); overload;
end;
implementation
uses uDM, uDMGlobal, ufrmStoreAccount;
{$R *.dfm}
procedure TFrmEmailBuilder.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmEmailBuilder.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmEmailBuilder.btnSendClick(Sender: TObject);
begin
inherited;
with Emails do
begin
BlindCopyTo.Text := mmReceivers.Text;
FromName := DM.fUser.UserName;
Subject := edtSubject.Text;
Body := memBody.Text;
AttachedFiles.Text := edtAttached.Text;
//Mostra o Email
ShowDialog := True;
SendMail;
end;
end;
procedure TFrmEmailBuilder.Start(IDCustomer : Integer; Customer, Products : TClientDataSet);
begin
FCustomerList := Customer;
FProductsList := Products;
FIDCustomer := IDCustomer;
if FCustomerList <> nil then
begin
BuildEmailList;
if FIDCustomer = 0 then
rbEmailTo.ItemIndex := 1;
end;
if FProductsList <> nil then
BuildBody;
ShowModal;
end;
procedure TFrmEmailBuilder.BuildEmailList;
begin
with FCustomerList do
begin
First;
FEmailList := '';
rbEmailTo.Items.Strings[0] := 'No Customer';
rbEmailTo.Items.Strings[1] := sAll;
while not EOF do
begin
if FieldByName('email').AsString <> '' then
FEmailList := FEmailList + FieldByName('email').AsString + '; ';
if FIDCustomer = FieldByName('IDPessoa').AsInteger then
begin
FCustomerEmail := FieldByName('email').AsString;
rbEmailTo.Items.Strings[0] := FieldByName('FullName').AsString;
end;
Next;
end;
end;
end;
procedure TFrmEmailBuilder.RefreshSendList;
begin
case rbEmailTo.ItemIndex of
0 : begin
mmReceivers.Text := FCustomerEmail;
end;
1 : begin
mmReceivers.Text := FEmailList;
end;
end;
end;
procedure TFrmEmailBuilder.rbEmailToClick(Sender: TObject);
begin
inherited;
RefreshSendList;
end;
procedure TFrmEmailBuilder.btnOpenFileClick(Sender: TObject);
begin
inherited;
if OP.Execute then
edtAttached.Text := OP.FileName;
end;
procedure TFrmEmailBuilder.BuildBody;
begin
with FProductsList do
begin
First;
while not EOF do
begin
memBody.Lines.Add(FieldByName('Model').AsString + ' - ' + FieldByName('Description').AsString);
memBody.Lines.Add(' ' + FormatFloat('#,##0.00', FieldByName('SalePrice').AsCurrency));
memBody.Lines.Add('');
Next;
end;
end;
end;
procedure TFrmEmailBuilder.FormCreate(Sender: TObject);
begin
inherited;
case DMGlobal.IDLanguage of
LANG_ENGLISH:
begin
sAll := 'All';
end;
LANG_PORTUGUESE:
begin
sAll := 'Todos';
end;
LANG_SPANISH :
begin
sAll := 'Todos';
end;
end;
end;
procedure TFrmEmailBuilder.Start(argIdCustomer: Integer; argCustomerList,
argProductList: TObjectList);
begin
self.Customers := argCustomerList;
self.Products := argProductList;
FIDCustomer := argIdCustomer;
if ( self.Customers.Count > 0 ) then begin
BuildEmailList(argCustomerList);
if ( FIDCustomer = 0 ) then begin
rbEmailTo.ItemIndex := 1;
end;
end;
if ( self.Products.Count > 0 ) then begin
BuildBody(self.Products);
end;
ShowModal;
end;
procedure TFrmEmailBuilder.BuildBody(argProducts: TObjectList);
var
i: Integer;
holdDate,
holdDueDate,
holdStore,
holdNumber,
holdInvoiceNumber,
holdTotal: String;
begin
for i := 0 to argProducts.Count - 1 do begin
holdDate := THold(argProducts[i]).HoldDate;
holdDueDate := THold(argProducts[i]).HoldDueDate;
holdStore := THold(argProducts[i]).HoldStore;
holdNumber := THold(argProducts[i]).HoldNumber;
holdInvoiceNumber := THold(argProducts[i]).HoldInvoiceNumber;
holdTotal := THold(argProducts[i]).HoldTotal;
memBody.lines.add('Transaction Date: ' + holdDate);
memBody.lines.Add('Due Date: ' + holdDueDate);
memBody.lines.Add('Store: ' + holdStore);
memBody.Lines.Add('Hold: ' + holdNumber);
memBody.lines.Add('Invoice ' + holdInvoiceNumber);
memBody.lines.add('Total Invoice: ' + holdTotal);
memBody.lines.add(' ');
memBody.lines.add(' ');
end;
end;
procedure TFrmEmailBuilder.BuildEmailList(argCustomers: TObjectList);
var
i: Integer;
begin
fEmailList := '';
rbEmailTo.items.Strings[0] := 'No Customer';
rbEmailTo.Items.Strings[1] := sAll;
for i := 0 to argCustomers.Count - 1 do begin
FEmailList := FEmailList + TCustomerStoreAccount(argCustomers[i]).CustomerEmail;
if ( IntToStr(FIDCustomer) = TCustomerStoreAccount(argCustomers[i]).CustomerId ) then begin
rbEmailTo.Items.Strings[0] := TCustomerStoreAccount(argCustomers[i]).CustomerName;
FCustomerEmail := TCustomerStoreAccount(argCustomers[i]).CustomerEmail;
end;
end;
memBody.Lines.Add('Total ( All Holds ): ' + TCustomerStoreAccount(argCustomers[0]).CustomerTotalAmount);
end;
end.
|
unit Win32.MFError;
// Checked and Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
(* ++
Microsoft Windows Media Foundation
Copyright (C) Microsoft Corporation. All rights reserved.
Module Name:
mferror.mc
Abstract:
Definitions for MediaFoundation events.
Author:
Revision History:
Notes:
This file is used by the MC tool to generate the mferror.h file
**************************** READ ME ******************************************
Here are the commented error ranges for the Windows Media Technologies Group
RANGES
14000 - 14999 = General Media Foundation errors
15000 - 15999 = ASF parsing errors
16000 - 16999 = Media Source errors
17000 - 17999 = MEDIAFOUNDATION Network Error Events
18000 - 18999 = MEDIAFOUNDATION WMContainer Error Events
19000 - 19999 = MEDIAFOUNDATION Media Sink Error Events
20000 - 20999 = Renderer errors
21000 - 21999 = Topology Errors
25000 - 25999 = Timeline Errors
26000 - 26999 = Unused
28000 - 28999 = Transform errors
29000 - 29999 = Content Protection errors
40000 - 40999 = Clock errors
41000 - 41999 = MF Quality Management Errors
42000 - 42999 = MF Transcode API Errors
43000 - 43999 = MF HW Device Proxy errors
44000 - 44999 = MF Capture Engine errors
45000 - 45999 = MF Media Timeline Controller errors
46000 - 46999 = MediaExtensions via AppService errors
**************************** READ ME ******************************************
-- *)
interface
uses
Windows, Classes;
const
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Success Events
/// //////////////////////////////////////////////////////////////////////
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Warning Events
/// //////////////////////////////////////////////////////////////////////
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Error Events
/// //////////////////////////////////////////////////////////////////////
// Values are 32 bit values laid out as follows:
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-+-----------------------+-------------------------------+
// |Sev|C|R| Facility | Code |
// +---+-+-+-----------------------+-------------------------------+
// where
// Sev - is the severity code
// 00 - Success
// 01 - Informational
// 10 - Warning
// 11 - Error
// C - is the Customer code flag
// R - is a reserved bit
// Facility - is the facility code
// Code - is the facility's status code
// Define the facility codes
FACILITY_MF_WIN32 = $7;
FACILITY_MF = $D;
// Define the severity codes
STATUS_SEVERITY_SUCCESS = $0;
STATUS_SEVERITY_INFORMATIONAL = $1;
STATUS_SEVERITY_WARNING = $2;
STATUS_SEVERITY_ERROR = $3;
// MessageId: MF_E_PLATFORM_NOT_INITIALIZED
// MessageText:
// Platform not initialized. Please call MFStartup().%0
MF_E_PLATFORM_NOT_INITIALIZED = HRESULT($C00D36B0);
// MessageId: MF_E_BUFFERTOOSMALL
// MessageText:
// The buffer was too small to carry out the requested action.%0
MF_E_BUFFERTOOSMALL = HRESULT($C00D36B1);
// MessageId: MF_E_INVALIDREQUEST
// MessageText:
// The request is invalid in the current state.%0
MF_E_INVALIDREQUEST = HRESULT($C00D36B2);
// MessageId: MF_E_INVALIDSTREAMNUMBER
// MessageText:
// The stream number provided was invalid.%0
MF_E_INVALIDSTREAMNUMBER = HRESULT($C00D36B3);
// MessageId: MF_E_INVALIDMEDIATYPE
// MessageText:
// The data specified for the media type is invalid, inconsistent, or not supported by this object.%0
MF_E_INVALIDMEDIATYPE = HRESULT($C00D36B4);
// MessageId: MF_E_NOTACCEPTING
// MessageText:
// The callee is currently not accepting further input.%0
MF_E_NOTACCEPTING = HRESULT($C00D36B5);
// MessageId: MF_E_NOT_INITIALIZED
// MessageText:
// This object needs to be initialized before the requested operation can be carried out.%0
MF_E_NOT_INITIALIZED = HRESULT($C00D36B6);
// MessageId: MF_E_UNSUPPORTED_REPRESENTATION
// MessageText:
// The requested representation is not supported by this object.%0
MF_E_UNSUPPORTED_REPRESENTATION = HRESULT($C00D36B7);
// MessageId: MF_E_NO_MORE_TYPES
// MessageText:
// An object ran out of media types to suggest therefore the requested chain of streaming objects cannot be completed.%0
MF_E_NO_MORE_TYPES = HRESULT($C00D36B9);
// MessageId: MF_E_UNSUPPORTED_SERVICE
// MessageText:
// The object does not support the specified service.%0
MF_E_UNSUPPORTED_SERVICE = HRESULT($C00D36BA);
// MessageId: MF_E_UNEXPECTED
// MessageText:
// An unexpected error has occurred in the operation requested.%0
MF_E_UNEXPECTED = HRESULT($C00D36BB);
// MessageId: MF_E_INVALIDNAME
// MessageText:
// Invalid name.%0
MF_E_INVALIDNAME = HRESULT($C00D36BC);
// MessageId: MF_E_INVALIDTYPE
// MessageText:
// Invalid type.%0
MF_E_INVALIDTYPE = HRESULT($C00D36BD);
// MessageId: MF_E_INVALID_FILE_FORMAT
// MessageText:
// The file does not conform to the relevant file format specification.%0
MF_E_INVALID_FILE_FORMAT = HRESULT($C00D36BE);
// MessageId: MF_E_INVALIDINDEX
// MessageText:
// Invalid index.%0
MF_E_INVALIDINDEX = HRESULT($C00D36BF);
// MessageId: MF_E_INVALID_TIMESTAMP
// MessageText:
// An invalid timestamp was given.%0
MF_E_INVALID_TIMESTAMP = HRESULT($C00D36C0);
// MessageId: MF_E_UNSUPPORTED_SCHEME
// MessageText:
// The scheme of the given URL is unsupported.%0
MF_E_UNSUPPORTED_SCHEME = HRESULT($C00D36C3);
// MessageId: MF_E_UNSUPPORTED_BYTESTREAM_TYPE
// MessageText:
// The byte stream type of the given URL is unsupported.%0
MF_E_UNSUPPORTED_BYTESTREAM_TYPE = HRESULT($C00D36C4);
// MessageId: MF_E_UNSUPPORTED_TIME_FORMAT
// MessageText:
// The given time format is unsupported.%0
MF_E_UNSUPPORTED_TIME_FORMAT = HRESULT($C00D36C5);
// MessageId: MF_E_NO_SAMPLE_TIMESTAMP
// MessageText:
// The Media Sample does not have a timestamp.%0
MF_E_NO_SAMPLE_TIMESTAMP = HRESULT($C00D36C8);
// MessageId: MF_E_NO_SAMPLE_DURATION
// MessageText:
// The Media Sample does not have a duration.%0
MF_E_NO_SAMPLE_DURATION = HRESULT($C00D36C9);
// MessageId: MF_E_INVALID_STREAM_DATA
// MessageText:
// The request failed because the data in the stream is corrupt.%0
MF_E_INVALID_STREAM_DATA = HRESULT($C00D36CB);
// MessageId: MF_E_RT_UNAVAILABLE
// MessageText:
// Real time services are not available.%0
MF_E_RT_UNAVAILABLE = HRESULT($C00D36CF);
// MessageId: MF_E_UNSUPPORTED_RATE
// MessageText:
// The specified rate is not supported.%0
MF_E_UNSUPPORTED_RATE = HRESULT($C00D36D0);
// MessageId: MF_E_THINNING_UNSUPPORTED
// MessageText:
// This component does not support stream-thinning.%0
MF_E_THINNING_UNSUPPORTED = HRESULT($C00D36D1);
// MessageId: MF_E_REVERSE_UNSUPPORTED
// MessageText:
// The call failed because no reverse playback rates are available.%0
MF_E_REVERSE_UNSUPPORTED = HRESULT($C00D36D2);
// MessageId: MF_E_UNSUPPORTED_RATE_TRANSITION
// MessageText:
// The requested rate transition cannot occur in the current state.%0
MF_E_UNSUPPORTED_RATE_TRANSITION = HRESULT($C00D36D3);
// MessageId: MF_E_RATE_CHANGE_PREEMPTED
// MessageText:
// The requested rate change has been pre-empted and will not occur.%0
MF_E_RATE_CHANGE_PREEMPTED = HRESULT($C00D36D4);
// MessageId: MF_E_NOT_FOUND
// MessageText:
// The specified object or value does not exist.%0
MF_E_NOT_FOUND = HRESULT($C00D36D5);
// MessageId: MF_E_NOT_AVAILABLE
// MessageText:
// The requested value is not available.%0
MF_E_NOT_AVAILABLE = HRESULT($C00D36D6);
// MessageId: MF_E_NO_CLOCK
// MessageText:
// The specified operation requires a clock and no clock is available.%0
MF_E_NO_CLOCK = HRESULT($C00D36D7);
// MessageId: MF_S_MULTIPLE_BEGIN
// MessageText:
// This callback and state had already been passed in to this event generator earlier.%0
MF_S_MULTIPLE_BEGIN = HRESULT($000D36D8);
// MessageId: MF_E_MULTIPLE_BEGIN
// MessageText:
// This callback has already been passed in to this event generator.%0
MF_E_MULTIPLE_BEGIN = HRESULT($C00D36D9);
// MessageId: MF_E_MULTIPLE_SUBSCRIBERS
// MessageText:
// Some component is already listening to events on this event generator.%0
MF_E_MULTIPLE_SUBSCRIBERS = HRESULT($C00D36DA);
// MessageId: MF_E_TIMER_ORPHANED
// MessageText:
// This timer was orphaned before its callback time arrived.%0
MF_E_TIMER_ORPHANED = HRESULT($C00D36DB);
// MessageId: MF_E_STATE_TRANSITION_PENDING
// MessageText:
// A state transition is already pending.%0
MF_E_STATE_TRANSITION_PENDING = HRESULT($C00D36DC);
// MessageId: MF_E_UNSUPPORTED_STATE_TRANSITION
// MessageText:
// The requested state transition is unsupported.%0
MF_E_UNSUPPORTED_STATE_TRANSITION = HRESULT($C00D36DD);
// MessageId: MF_E_UNRECOVERABLE_ERROR_OCCURRED
// MessageText:
// An unrecoverable error has occurred.%0
MF_E_UNRECOVERABLE_ERROR_OCCURRED = HRESULT($C00D36DE);
// MessageId: MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS
// MessageText:
// The provided sample has too many buffers.%0
MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS = HRESULT($C00D36DF);
// MessageId: MF_E_SAMPLE_NOT_WRITABLE
// MessageText:
// The provided sample is not writable.%0
MF_E_SAMPLE_NOT_WRITABLE = HRESULT($C00D36E0);
// MessageId: MF_E_INVALID_KEY
// MessageText:
// The specified key is not valid.%0
MF_E_INVALID_KEY = HRESULT($C00D36E2);
// MessageId: MF_E_BAD_STARTUP_VERSION
// MessageText:
// You are calling MFStartup with the wrong MF_VERSION. Mismatched bits?%0
MF_E_BAD_STARTUP_VERSION = HRESULT($C00D36E3);
// MessageId: MF_E_UNSUPPORTED_CAPTION
// MessageText:
// The caption of the given URL is unsupported.%0
MF_E_UNSUPPORTED_CAPTION = HRESULT($C00D36E4);
// MessageId: MF_E_INVALID_POSITION
// MessageText:
// The operation on the current offset is not permitted.%0
MF_E_INVALID_POSITION = HRESULT($C00D36E5);
// MessageId: MF_E_ATTRIBUTENOTFOUND
// MessageText:
// The requested attribute was not found.%0
MF_E_ATTRIBUTENOTFOUND = HRESULT($C00D36E6);
// MessageId: MF_E_PROPERTY_TYPE_NOT_ALLOWED
// MessageText:
// The specified property type is not allowed in this context.%0
MF_E_PROPERTY_TYPE_NOT_ALLOWED = HRESULT($C00D36E7);
// MessageId: MF_E_PROPERTY_TYPE_NOT_SUPPORTED
// MessageText:
// The specified property type is not supported.%0
MF_E_PROPERTY_TYPE_NOT_SUPPORTED = HRESULT($C00D36E8);
// MessageId: MF_E_PROPERTY_EMPTY
// MessageText:
// The specified property is empty.%0
MF_E_PROPERTY_EMPTY = HRESULT($C00D36E9);
// MessageId: MF_E_PROPERTY_NOT_EMPTY
// MessageText:
// The specified property is not empty.%0
MF_E_PROPERTY_NOT_EMPTY = HRESULT($C00D36EA);
// MessageId: MF_E_PROPERTY_VECTOR_NOT_ALLOWED
// MessageText:
// The vector property specified is not allowed in this context.%0
MF_E_PROPERTY_VECTOR_NOT_ALLOWED = HRESULT($C00D36EB);
// MessageId: MF_E_PROPERTY_VECTOR_REQUIRED
// MessageText:
// A vector property is required in this context.%0
MF_E_PROPERTY_VECTOR_REQUIRED = HRESULT($C00D36EC);
// MessageId: MF_E_OPERATION_CANCELLED
// MessageText:
// The operation is cancelled.%0
MF_E_OPERATION_CANCELLED = HRESULT($C00D36ED);
// MessageId: MF_E_BYTESTREAM_NOT_SEEKABLE
// MessageText:
// The provided bytestream was expected to be seekable and it is not.%0
MF_E_BYTESTREAM_NOT_SEEKABLE = HRESULT($C00D36EE);
// MessageId: MF_E_DISABLED_IN_SAFEMODE
// MessageText:
// The Media Foundation platform is disabled when the system is running in Safe Mode.%0
MF_E_DISABLED_IN_SAFEMODE = HRESULT($C00D36EF);
// MessageId: MF_E_CANNOT_PARSE_BYTESTREAM
// MessageText:
// The Media Source could not parse the byte stream.%0
MF_E_CANNOT_PARSE_BYTESTREAM = HRESULT($C00D36F0);
// MessageId: MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS
// MessageText:
// Mutually exclusive flags have been specified to source resolver. This flag combination is invalid.%0
MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS = HRESULT($C00D36F1);
// MessageId: MF_E_MEDIAPROC_WRONGSTATE
// MessageText:
// MediaProc is in the wrong state.%0
MF_E_MEDIAPROC_WRONGSTATE = HRESULT($C00D36F2);
// MessageId: MF_E_RT_THROUGHPUT_NOT_AVAILABLE
// MessageText:
// Real time I/O service can not provide requested throughput.%0
MF_E_RT_THROUGHPUT_NOT_AVAILABLE = HRESULT($C00D36F3);
// MessageId: MF_E_RT_TOO_MANY_CLASSES
// MessageText:
// The workqueue cannot be registered with more classes.%0
MF_E_RT_TOO_MANY_CLASSES = HRESULT($C00D36F4);
// MessageId: MF_E_RT_WOULDBLOCK
// MessageText:
// This operation cannot succeed because another thread owns this object.%0
MF_E_RT_WOULDBLOCK = HRESULT($C00D36F5);
// MessageId: MF_E_NO_BITPUMP
// MessageText:
// Internal. Bitpump not found.%0
MF_E_NO_BITPUMP = HRESULT($C00D36F6);
// MessageId: MF_E_RT_OUTOFMEMORY
// MessageText:
// No more RT memory available.%0
MF_E_RT_OUTOFMEMORY = HRESULT($C00D36F7);
// MessageId: MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED
// MessageText:
// An MMCSS class has not been set for this work queue.%0
MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED = HRESULT($C00D36F8);
// MessageId: MF_E_INSUFFICIENT_BUFFER
// MessageText:
// Insufficient memory for response.%0
MF_E_INSUFFICIENT_BUFFER = HRESULT($C00D7170);
// MessageId: MF_E_CANNOT_CREATE_SINK
// MessageText:
// Activate failed to create mediasink. Call OutputNode::GetUINT32(MF_TOPONODE_MAJORTYPE) for more information.%0
MF_E_CANNOT_CREATE_SINK = HRESULT($C00D36FA);
// MessageId: MF_E_BYTESTREAM_UNKNOWN_LENGTH
// MessageText:
// The length of the provided bytestream is unknown.%0
MF_E_BYTESTREAM_UNKNOWN_LENGTH = HRESULT($C00D36FB);
// MessageId: MF_E_SESSION_PAUSEWHILESTOPPED
// MessageText:
// The media session cannot pause from a stopped state.%0
MF_E_SESSION_PAUSEWHILESTOPPED = HRESULT($C00D36FC);
// MessageId: MF_S_ACTIVATE_REPLACED
// MessageText:
// The activate could not be created in the remote process for some reason it was replaced with empty one.%0
MF_S_ACTIVATE_REPLACED = HRESULT($000D36FD);
// MessageId: MF_E_FORMAT_CHANGE_NOT_SUPPORTED
// MessageText:
// The data specified for the media type is supported, but would require a format change, which is not supported by this object.%0
MF_E_FORMAT_CHANGE_NOT_SUPPORTED = HRESULT($C00D36FE);
// MessageId: MF_E_INVALID_WORKQUEUE
// MessageText:
// The operation failed because an invalid combination of workqueue ID and flags was specified.%0
MF_E_INVALID_WORKQUEUE = HRESULT($C00D36FF);
// MessageId: MF_E_DRM_UNSUPPORTED
// MessageText:
// No DRM support is available.%0
MF_E_DRM_UNSUPPORTED = HRESULT($C00D3700);
// MessageId: MF_E_UNAUTHORIZED
// MessageText:
// This operation is not authorized.%0
MF_E_UNAUTHORIZED = HRESULT($C00D3701);
// MessageId: MF_E_OUT_OF_RANGE
// MessageText:
// The value is not in the specified or valid range.%0
MF_E_OUT_OF_RANGE = HRESULT($C00D3702);
// MessageId: MF_E_INVALID_CODEC_MERIT
// MessageText:
// The registered codec merit is not valid.%0
MF_E_INVALID_CODEC_MERIT = HRESULT($C00D3703);
// MessageId: MF_E_HW_MFT_FAILED_START_STREAMING
// MessageText:
// Hardware MFT failed to start streaming due to lack of hardware resources.%0
MF_E_HW_MFT_FAILED_START_STREAMING = HRESULT($C00D3704);
// MessageId: MF_E_OPERATION_IN_PROGRESS
// MessageText:
// The operation is already in progress.%0
MF_E_OPERATION_IN_PROGRESS = HRESULT($C00D3705);
// MessageId: MF_E_HARDWARE_DRM_UNSUPPORTED
// MessageText:
// No Hardware DRM support is available.%0
MF_E_HARDWARE_DRM_UNSUPPORTED = HRESULT($C00D3706);
// MessageId: MF_E_DURATION_TOO_LONG
// MessageText:
// The specified duration is too long.%0
MF_E_DURATION_TOO_LONG = HRESULT($C00D3707);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION ASF Parsing Informational Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_S_ASF_PARSEINPROGRESS
// MessageText:
// Parsing is still in progress and is not yet complete.%0
MF_S_ASF_PARSEINPROGRESS = HRESULT($400D3A98);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION ASF Parsing Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_ASF_PARSINGINCOMPLETE
// MessageText:
// Not enough data have been parsed to carry out the requested action.%0
MF_E_ASF_PARSINGINCOMPLETE = HRESULT($C00D3A98);
// MessageId: MF_E_ASF_MISSINGDATA
// MessageText:
// There is a gap in the ASF data provided.%0
MF_E_ASF_MISSINGDATA = HRESULT($C00D3A99);
// MessageId: MF_E_ASF_INVALIDDATA
// MessageText:
// The data provided are not valid ASF.%0
MF_E_ASF_INVALIDDATA = HRESULT($C00D3A9A);
// MessageId: MF_E_ASF_OPAQUEPACKET
// MessageText:
// The packet is opaque, so the requested information cannot be returned.%0
MF_E_ASF_OPAQUEPACKET = HRESULT($C00D3A9B);
// MessageId: MF_E_ASF_NOINDEX
// MessageText:
// The requested operation failed since there is no appropriate ASF index.%0
MF_E_ASF_NOINDEX = HRESULT($C00D3A9C);
// MessageId: MF_E_ASF_OUTOFRANGE
// MessageText:
// The value supplied is out of range for this operation.%0
MF_E_ASF_OUTOFRANGE = HRESULT($C00D3A9D);
// MessageId: MF_E_ASF_INDEXNOTLOADED
// MessageText:
// The index entry requested needs to be loaded before it can be available.%0
MF_E_ASF_INDEXNOTLOADED = HRESULT($C00D3A9E);
// MessageId: MF_E_ASF_TOO_MANY_PAYLOADS
// MessageText:
// The packet has reached the maximum number of payloads.%0
MF_E_ASF_TOO_MANY_PAYLOADS = HRESULT($C00D3A9F);
// MessageId: MF_E_ASF_UNSUPPORTED_STREAM_TYPE
// MessageText:
// Stream type is not supported.%0
MF_E_ASF_UNSUPPORTED_STREAM_TYPE = HRESULT($C00D3AA0);
// MessageId: MF_E_ASF_DROPPED_PACKET
// MessageText:
// One or more ASF packets were dropped.%0
MF_E_ASF_DROPPED_PACKET = HRESULT($C00D3AA1);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Media Source Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_NO_EVENTS_AVAILABLE
// MessageText:
// There are no events available in the queue.%0
MF_E_NO_EVENTS_AVAILABLE = HRESULT($C00D3E80);
// MessageId: MF_E_INVALID_STATE_TRANSITION
// MessageText:
// A media source cannot go from the stopped state to the paused state.%0
MF_E_INVALID_STATE_TRANSITION = HRESULT($C00D3E82);
// MessageId: MF_E_END_OF_STREAM
// MessageText:
// The media stream cannot process any more samples because there are no more samples in the stream.%0
MF_E_END_OF_STREAM = HRESULT($C00D3E84);
// MessageId: MF_E_SHUTDOWN
// MessageText:
// The request is invalid because Shutdown() has been called.%0
MF_E_SHUTDOWN = HRESULT($C00D3E85);
// MessageId: MF_E_MP3_NOTFOUND
// MessageText:
// The MP3 object was not found.%0
MF_E_MP3_NOTFOUND = HRESULT($C00D3E86);
// MessageId: MF_E_MP3_OUTOFDATA
// MessageText:
// The MP3 parser ran out of data before finding the MP3 object.%0
MF_E_MP3_OUTOFDATA = HRESULT($C00D3E87);
// MessageId: MF_E_MP3_NOTMP3
// MessageText:
// The file is not really a MP3 file.%0
MF_E_MP3_NOTMP3 = HRESULT($C00D3E88);
// MessageId: MF_E_MP3_NOTSUPPORTED
// MessageText:
// The MP3 file is not supported.%0
MF_E_MP3_NOTSUPPORTED = HRESULT($C00D3E89);
// MessageId: MF_E_NO_DURATION
// MessageText:
// The Media stream has no duration.%0
MF_E_NO_DURATION = HRESULT($C00D3E8A);
// MessageId: MF_E_INVALID_FORMAT
// MessageText:
// The Media format is recognized but is invalid.%0
MF_E_INVALID_FORMAT = HRESULT($C00D3E8C);
// MessageId: MF_E_PROPERTY_NOT_FOUND
// MessageText:
// The property requested was not found.%0
MF_E_PROPERTY_NOT_FOUND = HRESULT($C00D3E8D);
// MessageId: MF_E_PROPERTY_READ_ONLY
// MessageText:
// The property is read only.%0
MF_E_PROPERTY_READ_ONLY = HRESULT($C00D3E8E);
// MessageId: MF_E_PROPERTY_NOT_ALLOWED
// MessageText:
// The specified property is not allowed in this context.%0
MF_E_PROPERTY_NOT_ALLOWED = HRESULT($C00D3E8F);
// MessageId: MF_E_MEDIA_SOURCE_NOT_STARTED
// MessageText:
// The media source is not started.%0
MF_E_MEDIA_SOURCE_NOT_STARTED = HRESULT($C00D3E91);
// MessageId: MF_E_UNSUPPORTED_FORMAT
// MessageText:
// The Media format is recognized but not supported.%0
MF_E_UNSUPPORTED_FORMAT = HRESULT($C00D3E98);
// MessageId: MF_E_MP3_BAD_CRC
// MessageText:
// The MPEG frame has bad CRC.%0
MF_E_MP3_BAD_CRC = HRESULT($C00D3E99);
// MessageId: MF_E_NOT_PROTECTED
// MessageText:
// The file is not protected.%0
MF_E_NOT_PROTECTED = HRESULT($C00D3E9A);
// MessageId: MF_E_MEDIA_SOURCE_WRONGSTATE
// MessageText:
// The media source is in the wrong state.%0
MF_E_MEDIA_SOURCE_WRONGSTATE = HRESULT($C00D3E9B);
// MessageId: MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED
// MessageText:
// No streams are selected in source presentation descriptor.%0
MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED = HRESULT($C00D3E9C);
// MessageId: MF_E_CANNOT_FIND_KEYFRAME_SAMPLE
// MessageText:
// No key frame sample was found.%0
MF_E_CANNOT_FIND_KEYFRAME_SAMPLE = HRESULT($C00D3E9D);
// MessageId: MF_E_UNSUPPORTED_CHARACTERISTICS
// MessageText:
// The characteristics of the media source are not supported.%0
MF_E_UNSUPPORTED_CHARACTERISTICS = HRESULT($C00D3E9E);
// MessageId: MF_E_NO_AUDIO_RECORDING_DEVICE
// MessageText:
// No audio recording device was found.%0
MF_E_NO_AUDIO_RECORDING_DEVICE = HRESULT($C00D3E9F);
// MessageId: MF_E_AUDIO_RECORDING_DEVICE_IN_USE
// MessageText:
// The requested audio recording device is currently in use.%0
MF_E_AUDIO_RECORDING_DEVICE_IN_USE = HRESULT($C00D3EA0);
// MessageId: MF_E_AUDIO_RECORDING_DEVICE_INVALIDATED
// MessageText:
// The audio recording device is no longer present.%0
MF_E_AUDIO_RECORDING_DEVICE_INVALIDATED = HRESULT($C00D3EA1);
// MessageId: MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED
// MessageText:
// The video recording device is no longer present.%0
MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED = HRESULT($C00D3EA2);
// MessageId: MF_E_VIDEO_RECORDING_DEVICE_PREEMPTED
// MessageText:
// The video recording device is preempted by another immersive application.%0
MF_E_VIDEO_RECORDING_DEVICE_PREEMPTED = HRESULT($C00D3EA3);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Network Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_NETWORK_RESOURCE_FAILURE
// MessageText:
// An attempt to acquire a network resource failed.%0
MF_E_NETWORK_RESOURCE_FAILURE = HRESULT($C00D4268);
// MessageId: MF_E_NET_WRITE
// MessageText:
// Error writing to the network.%0
MF_E_NET_WRITE = HRESULT($C00D4269);
// MessageId: MF_E_NET_READ
// MessageText:
// Error reading from the network.%0
MF_E_NET_READ = HRESULT($C00D426A);
// MessageId: MF_E_NET_REQUIRE_NETWORK
// MessageText:
// Internal. Entry cannot complete operation without network.%0
MF_E_NET_REQUIRE_NETWORK = HRESULT($C00D426B);
// MessageId: MF_E_NET_REQUIRE_ASYNC
// MessageText:
// Internal. Async op is required.%0
MF_E_NET_REQUIRE_ASYNC = HRESULT($C00D426C);
// MessageId: MF_E_NET_BWLEVEL_NOT_SUPPORTED
// MessageText:
// Internal. Bandwidth levels are not supported.%0
MF_E_NET_BWLEVEL_NOT_SUPPORTED = HRESULT($C00D426D);
// MessageId: MF_E_NET_STREAMGROUPS_NOT_SUPPORTED
// MessageText:
// Internal. Stream groups are not supported.%0
MF_E_NET_STREAMGROUPS_NOT_SUPPORTED = HRESULT($C00D426E);
// MessageId: MF_E_NET_MANUALSS_NOT_SUPPORTED
// MessageText:
// Manual stream selection is not supported.%0
MF_E_NET_MANUALSS_NOT_SUPPORTED = HRESULT($C00D426F);
// MessageId: MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR
// MessageText:
// Invalid presentation descriptor.%0
MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR = HRESULT($C00D4270);
// MessageId: MF_E_NET_CACHESTREAM_NOT_FOUND
// MessageText:
// Cannot find cache stream.%0
MF_E_NET_CACHESTREAM_NOT_FOUND = HRESULT($C00D4271);
// MessageId: MF_I_MANUAL_PROXY
// MessageText:
// The proxy setting is manual.%0
MF_I_MANUAL_PROXY = HRESULT($400D4272);
// duplicate removed
// MessageId=17011 Severity=Informational Facility=MEDIAFOUNDATION SymbolicName=MF_E_INVALID_REQUEST
// Language=English
// The request is invalid in the current state.%0
// .
// MessageId: MF_E_NET_REQUIRE_INPUT
// MessageText:
// Internal. Entry cannot complete operation without input.%0
MF_E_NET_REQUIRE_INPUT = HRESULT($C00D4274);
// MessageId: MF_E_NET_REDIRECT
// MessageText:
// The client redirected to another server.%0
MF_E_NET_REDIRECT = HRESULT($C00D4275);
// MessageId: MF_E_NET_REDIRECT_TO_PROXY
// MessageText:
// The client is redirected to a proxy server.%0
MF_E_NET_REDIRECT_TO_PROXY = HRESULT($C00D4276);
// MessageId: MF_E_NET_TOO_MANY_REDIRECTS
// MessageText:
// The client reached maximum redirection limit.%0
MF_E_NET_TOO_MANY_REDIRECTS = HRESULT($C00D4277);
// MessageId: MF_E_NET_TIMEOUT
// MessageText:
// The server, a computer set up to offer multimedia content to other computers, could not handle your request for multimedia content in a timely manner. Please try again later.%0
MF_E_NET_TIMEOUT = HRESULT($C00D4278);
// MessageId: MF_E_NET_CLIENT_CLOSE
// MessageText:
// The control socket is closed by the client.%0
MF_E_NET_CLIENT_CLOSE = HRESULT($C00D4279);
// MessageId: MF_E_NET_BAD_CONTROL_DATA
// MessageText:
// The server received invalid data from the client on the control connection.%0
MF_E_NET_BAD_CONTROL_DATA = HRESULT($C00D427A);
// MessageId: MF_E_NET_INCOMPATIBLE_SERVER
// MessageText:
// The server is not a compatible streaming media server.%0
MF_E_NET_INCOMPATIBLE_SERVER = HRESULT($C00D427B);
// MessageId: MF_E_NET_UNSAFE_URL
// MessageText:
// Url.%0
MF_E_NET_UNSAFE_URL = HRESULT($C00D427C);
// MessageId: MF_E_NET_CACHE_NO_DATA
// MessageText:
// Data is not available.%0
MF_E_NET_CACHE_NO_DATA = HRESULT($C00D427D);
// MessageId: MF_E_NET_EOL
// MessageText:
// End of line.%0
MF_E_NET_EOL = HRESULT($C00D427E);
// MessageId: MF_E_NET_BAD_REQUEST
// MessageText:
// The request could not be understood by the server.%0
MF_E_NET_BAD_REQUEST = HRESULT($C00D427F);
// MessageId: MF_E_NET_INTERNAL_SERVER_ERROR
// MessageText:
// The server encountered an unexpected condition which prevented it from fulfilling the request.%0
MF_E_NET_INTERNAL_SERVER_ERROR = HRESULT($C00D4280);
// MessageId: MF_E_NET_SESSION_NOT_FOUND
// MessageText:
// Session not found.%0
MF_E_NET_SESSION_NOT_FOUND = HRESULT($C00D4281);
// MessageId: MF_E_NET_NOCONNECTION
// MessageText:
// There is no connection established with the Windows Media server. The operation failed.%0
MF_E_NET_NOCONNECTION = HRESULT($C00D4282);
// MessageId: MF_E_NET_CONNECTION_FAILURE
// MessageText:
// The network connection has failed.%0
MF_E_NET_CONNECTION_FAILURE = HRESULT($C00D4283);
// MessageId: MF_E_NET_INCOMPATIBLE_PUSHSERVER
// MessageText:
// The Server service that received the HTTP push request is not a compatible version of Windows Media Services (WMS). This error may indicate the push request was received by IIS instead of WMS. Ensure WMS is started and has the HTTP Server control protocol properly enabled and try again.%0
MF_E_NET_INCOMPATIBLE_PUSHSERVER = HRESULT($C00D4284);
// MessageId: MF_E_NET_SERVER_ACCESSDENIED
// MessageText:
// The Windows Media server is denying access. The username and/or password might be incorrect.%0
MF_E_NET_SERVER_ACCESSDENIED = HRESULT($C00D4285);
// MessageId: MF_E_NET_PROXY_ACCESSDENIED
// MessageText:
// The proxy server is denying access. The username and/or password might be incorrect.%0
MF_E_NET_PROXY_ACCESSDENIED = HRESULT($C00D4286);
// MessageId: MF_E_NET_CANNOTCONNECT
// MessageText:
// Unable to establish a connection to the server.%0
MF_E_NET_CANNOTCONNECT = HRESULT($C00D4287);
// MessageId: MF_E_NET_INVALID_PUSH_TEMPLATE
// MessageText:
// The specified push template is invalid.%0
MF_E_NET_INVALID_PUSH_TEMPLATE = HRESULT($C00D4288);
// MessageId: MF_E_NET_INVALID_PUSH_PUBLISHING_POINT
// MessageText:
// The specified push publishing point is invalid.%0
MF_E_NET_INVALID_PUSH_PUBLISHING_POINT = HRESULT($C00D4289);
// MessageId: MF_E_NET_BUSY
// MessageText:
// The requested resource is in use.%0
MF_E_NET_BUSY = HRESULT($C00D428A);
// MessageId: MF_E_NET_RESOURCE_GONE
// MessageText:
// The Publishing Point or file on the Windows Media Server is no longer available.%0
MF_E_NET_RESOURCE_GONE = HRESULT($C00D428B);
// MessageId: MF_E_NET_ERROR_FROM_PROXY
// MessageText:
// The proxy experienced an error while attempting to contact the media server.%0
MF_E_NET_ERROR_FROM_PROXY = HRESULT($C00D428C);
// MessageId: MF_E_NET_PROXY_TIMEOUT
// MessageText:
// The proxy did not receive a timely response while attempting to contact the media server.%0
MF_E_NET_PROXY_TIMEOUT = HRESULT($C00D428D);
// MessageId: MF_E_NET_SERVER_UNAVAILABLE
// MessageText:
// The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.%0
MF_E_NET_SERVER_UNAVAILABLE = HRESULT($C00D428E);
// MessageId: MF_E_NET_TOO_MUCH_DATA
// MessageText:
// The encoding process was unable to keep up with the amount of supplied data.%0
MF_E_NET_TOO_MUCH_DATA = HRESULT($C00D428F);
// MessageId: MF_E_NET_SESSION_INVALID
// MessageText:
// Session not found.%0
MF_E_NET_SESSION_INVALID = HRESULT($C00D4290);
// MessageId: MF_E_OFFLINE_MODE
// MessageText:
// The requested URL is not available in offline mode.%0
MF_E_OFFLINE_MODE = HRESULT($C00D4291);
// MessageId: MF_E_NET_UDP_BLOCKED
// MessageText:
// A device in the network is blocking UDP traffic.%0
MF_E_NET_UDP_BLOCKED = HRESULT($C00D4292);
// MessageId: MF_E_NET_UNSUPPORTED_CONFIGURATION
// MessageText:
// The specified configuration value is not supported.%0
MF_E_NET_UNSUPPORTED_CONFIGURATION = HRESULT($C00D4293);
// MessageId: MF_E_NET_PROTOCOL_DISABLED
// MessageText:
// The networking protocol is disabled.%0
MF_E_NET_PROTOCOL_DISABLED = HRESULT($C00D4294);
// MessageId: MF_E_NET_COMPANION_DRIVER_DISCONNECT
// MessageText:
// The companion driver asked the OS to disconnect from the receiver.%0
MF_E_NET_COMPANION_DRIVER_DISCONNECT = HRESULT($C00D4295);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION WMContainer Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_ALREADY_INITIALIZED
// MessageText:
// This object has already been initialized and cannot be re-initialized at this time.%0
MF_E_ALREADY_INITIALIZED = HRESULT($C00D4650);
// MessageId: MF_E_BANDWIDTH_OVERRUN
// MessageText:
// The amount of data passed in exceeds the given bitrate and buffer window.%0
MF_E_BANDWIDTH_OVERRUN = HRESULT($C00D4651);
// MessageId: MF_E_LATE_SAMPLE
// MessageText:
// The sample was passed in too late to be correctly processed.%0
MF_E_LATE_SAMPLE = HRESULT($C00D4652);
// MessageId: MF_E_FLUSH_NEEDED
// MessageText:
// The requested action cannot be carried out until the object is flushed and the queue is emptied.%0
MF_E_FLUSH_NEEDED = HRESULT($C00D4653);
// MessageId: MF_E_INVALID_PROFILE
// MessageText:
// The profile is invalid.%0
MF_E_INVALID_PROFILE = HRESULT($C00D4654);
// MessageId: MF_E_INDEX_NOT_COMMITTED
// MessageText:
// The index that is being generated needs to be committed before the requested action can be carried out.%0
MF_E_INDEX_NOT_COMMITTED = HRESULT($C00D4655);
// MessageId: MF_E_NO_INDEX
// MessageText:
// The index that is necessary for the requested action is not found.%0
MF_E_NO_INDEX = HRESULT($C00D4656);
// MessageId: MF_E_CANNOT_INDEX_IN_PLACE
// MessageText:
// The requested index cannot be added in-place to the specified ASF content.%0
MF_E_CANNOT_INDEX_IN_PLACE = HRESULT($C00D4657);
// MessageId: MF_E_MISSING_ASF_LEAKYBUCKET
// MessageText:
// The ASF leaky bucket parameters must be specified in order to carry out this request.%0
MF_E_MISSING_ASF_LEAKYBUCKET = HRESULT($C00D4658);
// MessageId: MF_E_INVALID_ASF_STREAMID
// MessageText:
// The stream id is invalid. The valid range for ASF stream id is from 1 to 127.%0
MF_E_INVALID_ASF_STREAMID = HRESULT($C00D4659);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Media Sink Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_STREAMSINK_REMOVED
// MessageText:
// The requested Stream Sink has been removed and cannot be used.%0
MF_E_STREAMSINK_REMOVED = HRESULT($C00D4A38);
// MessageId: MF_E_STREAMSINKS_OUT_OF_SYNC
// MessageText:
// The various Stream Sinks in this Media Sink are too far out of sync for the requested action to take place.%0
MF_E_STREAMSINKS_OUT_OF_SYNC = HRESULT($C00D4A3A);
// MessageId: MF_E_STREAMSINKS_FIXED
// MessageText:
// Stream Sinks cannot be added to or removed from this Media Sink because its set of streams is fixed.%0
MF_E_STREAMSINKS_FIXED = HRESULT($C00D4A3B);
// MessageId: MF_E_STREAMSINK_EXISTS
// MessageText:
// The given Stream Sink already exists.%0
MF_E_STREAMSINK_EXISTS = HRESULT($C00D4A3C);
// MessageId: MF_E_SAMPLEALLOCATOR_CANCELED
// MessageText:
// Sample allocations have been canceled.%0
MF_E_SAMPLEALLOCATOR_CANCELED = HRESULT($C00D4A3D);
// MessageId: MF_E_SAMPLEALLOCATOR_EMPTY
// MessageText:
// The sample allocator is currently empty, due to outstanding requests.%0
MF_E_SAMPLEALLOCATOR_EMPTY = HRESULT($C00D4A3E);
// MessageId: MF_E_SINK_ALREADYSTOPPED
// MessageText:
// When we try to stop a stream sink, it is already stopped.%0
MF_E_SINK_ALREADYSTOPPED = HRESULT($C00D4A3F);
// MessageId: MF_E_ASF_FILESINK_BITRATE_UNKNOWN
// MessageText:
// The ASF file sink could not reserve AVIO because the bitrate is unknown.%0
MF_E_ASF_FILESINK_BITRATE_UNKNOWN = HRESULT($C00D4A40);
// MessageId: MF_E_SINK_NO_STREAMS
// MessageText:
// No streams are selected in sink presentation descriptor.%0
MF_E_SINK_NO_STREAMS = HRESULT($C00D4A41);
// MessageId: MF_S_SINK_NOT_FINALIZED
// MessageText:
// The sink has not been finalized before shut down. This may cause sink to generate corrupted content.%0
MF_S_SINK_NOT_FINALIZED = HRESULT($000D4A42);
// MessageId: MF_E_METADATA_TOO_LONG
// MessageText:
// A metadata item was too long to write to the output container.%0
MF_E_METADATA_TOO_LONG = HRESULT($C00D4A43);
// MessageId: MF_E_SINK_NO_SAMPLES_PROCESSED
// MessageText:
// The operation failed because no samples were processed by the sink.%0
MF_E_SINK_NO_SAMPLES_PROCESSED = HRESULT($C00D4A44);
// MessageId: MF_E_SINK_HEADERS_NOT_FOUND
// MessageText:
// Sink could not create valid output file because required headers were not provided to the sink.%0
MF_E_SINK_HEADERS_NOT_FOUND = HRESULT($C00D4A45);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Renderer Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_VIDEO_REN_NO_PROCAMP_HW
// MessageText:
// There is no available procamp hardware with which to perform color correction.%0
MF_E_VIDEO_REN_NO_PROCAMP_HW = HRESULT($C00D4E20);
// MessageId: MF_E_VIDEO_REN_NO_DEINTERLACE_HW
// MessageText:
// There is no available deinterlacing hardware with which to deinterlace the video stream.%0
MF_E_VIDEO_REN_NO_DEINTERLACE_HW = HRESULT($C00D4E21);
// MessageId: MF_E_VIDEO_REN_COPYPROT_FAILED
// MessageText:
// A video stream requires copy protection to be enabled, but there was a failure in attempting to enable copy protection.%0
MF_E_VIDEO_REN_COPYPROT_FAILED = HRESULT($C00D4E22);
// MessageId: MF_E_VIDEO_REN_SURFACE_NOT_SHARED
// MessageText:
// A component is attempting to access a surface for sharing that is not shared.%0
MF_E_VIDEO_REN_SURFACE_NOT_SHARED = HRESULT($C00D4E23);
// MessageId: MF_E_VIDEO_DEVICE_LOCKED
// MessageText:
// A component is attempting to access a shared device that is already locked by another component.%0
MF_E_VIDEO_DEVICE_LOCKED = HRESULT($C00D4E24);
// MessageId: MF_E_NEW_VIDEO_DEVICE
// MessageText:
// The device is no longer available. The handle should be closed and a new one opened.%0
MF_E_NEW_VIDEO_DEVICE = HRESULT($C00D4E25);
// MessageId: MF_E_NO_VIDEO_SAMPLE_AVAILABLE
// MessageText:
// A video sample is not currently queued on a stream that is required for mixing.%0
MF_E_NO_VIDEO_SAMPLE_AVAILABLE = HRESULT($C00D4E26);
// MessageId: MF_E_NO_AUDIO_PLAYBACK_DEVICE
// MessageText:
// No audio playback device was found.%0
MF_E_NO_AUDIO_PLAYBACK_DEVICE = HRESULT($C00D4E84);
// MessageId: MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE
// MessageText:
// The requested audio playback device is currently in use.%0
MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE = HRESULT($C00D4E85);
// MessageId: MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED
// MessageText:
// The audio playback device is no longer present.%0
MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED = HRESULT($C00D4E86);
// MessageId: MF_E_AUDIO_SERVICE_NOT_RUNNING
// MessageText:
// The audio service is not running.%0
MF_E_AUDIO_SERVICE_NOT_RUNNING = HRESULT($C00D4E87);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Topology Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_TOPO_INVALID_OPTIONAL_NODE
// MessageText:
// The topology contains an invalid optional node. Possible reasons are incorrect number of outputs and inputs or optional node is at the beginning or end of a segment.%0
MF_E_TOPO_INVALID_OPTIONAL_NODE = HRESULT($C00D520E);
// MessageId: MF_E_TOPO_CANNOT_FIND_DECRYPTOR
// MessageText:
// No suitable transform was found to decrypt the content.%0
MF_E_TOPO_CANNOT_FIND_DECRYPTOR = HRESULT($C00D5211);
// MessageId: MF_E_TOPO_CODEC_NOT_FOUND
// MessageText:
// No suitable transform was found to encode or decode the content.%0
MF_E_TOPO_CODEC_NOT_FOUND = HRESULT($C00D5212);
// MessageId: MF_E_TOPO_CANNOT_CONNECT
// MessageText:
// Unable to find a way to connect nodes.%0
MF_E_TOPO_CANNOT_CONNECT = HRESULT($C00D5213);
// MessageId: MF_E_TOPO_UNSUPPORTED
// MessageText:
// Unsupported operations in topoloader.%0
MF_E_TOPO_UNSUPPORTED = HRESULT($C00D5214);
// MessageId: MF_E_TOPO_INVALID_TIME_ATTRIBUTES
// MessageText:
// The topology or its nodes contain incorrectly set time attributes.%0
MF_E_TOPO_INVALID_TIME_ATTRIBUTES = HRESULT($C00D5215);
// MessageId: MF_E_TOPO_LOOPS_IN_TOPOLOGY
// MessageText:
// The topology contains loops, which are unsupported in media foundation topologies.%0
MF_E_TOPO_LOOPS_IN_TOPOLOGY = HRESULT($C00D5216);
// MessageId: MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR
// MessageText:
// A source stream node in the topology does not have a presentation descriptor.%0
MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR = HRESULT($C00D5217);
// MessageId: MF_E_TOPO_MISSING_STREAM_DESCRIPTOR
// MessageText:
// A source stream node in the topology does not have a stream descriptor.%0
MF_E_TOPO_MISSING_STREAM_DESCRIPTOR = HRESULT($C00D5218);
// MessageId: MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED
// MessageText:
// A stream descriptor was set on a source stream node but it was not selected on the presentation descriptor.%0
MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED = HRESULT($C00D5219);
// MessageId: MF_E_TOPO_MISSING_SOURCE
// MessageText:
// A source stream node in the topology does not have a source.%0
MF_E_TOPO_MISSING_SOURCE = HRESULT($C00D521A);
// MessageId: MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED
// MessageText:
// The topology loader does not support sink activates on output nodes.%0
MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED = HRESULT($C00D521B);
/// //////////////////////////////////////////////////////////////////////
// MEDIAFOUNDATION Timeline Error Events
/// //////////////////////////////////////////////////////////////////////
// MessageId: MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID
// MessageText:
// The sequencer cannot find a segment with the given ID.%0
MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID = HRESULT($C00D61AC);
// MessageId: MF_S_SEQUENCER_CONTEXT_CANCELED
// MessageText:
// The context was canceled.%0
MF_S_SEQUENCER_CONTEXT_CANCELED = HRESULT($000D61AD);
// MessageId: MF_E_NO_SOURCE_IN_CACHE
// MessageText:
// Cannot find source in source cache.%0
MF_E_NO_SOURCE_IN_CACHE = HRESULT($C00D61AE);
// MessageId: MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM
// MessageText:
// Cannot update topology flags.%0
MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM = HRESULT($000D61AF);
/// ///////////////////////////////////////////////////////////////////////////
// Transform errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_TRANSFORM_TYPE_NOT_SET
// MessageText:
// A valid type has not been set for this stream or a stream that it depends on.%0
MF_E_TRANSFORM_TYPE_NOT_SET = HRESULT($C00D6D60);
// MessageId: MF_E_TRANSFORM_STREAM_CHANGE
// MessageText:
// A stream change has occurred. Output cannot be produced until the streams have been renegotiated.%0
MF_E_TRANSFORM_STREAM_CHANGE = HRESULT($C00D6D61);
// MessageId: MF_E_TRANSFORM_INPUT_REMAINING
// MessageText:
// The transform cannot take the requested action until all of the input data it currently holds is processed or flushed.%0
MF_E_TRANSFORM_INPUT_REMAINING = HRESULT($C00D6D62);
// MessageId: MF_E_TRANSFORM_PROFILE_MISSING
// MessageText:
// The transform requires a profile but no profile was supplied or found.%0
MF_E_TRANSFORM_PROFILE_MISSING = HRESULT($C00D6D63);
// MessageId: MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT
// MessageText:
// The transform requires a profile but the supplied profile was invalid or corrupt.%0
MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT = HRESULT($C00D6D64);
// MessageId: MF_E_TRANSFORM_PROFILE_TRUNCATED
// MessageText:
// The transform requires a profile but the supplied profile ended unexpectedly while parsing.%0
MF_E_TRANSFORM_PROFILE_TRUNCATED = HRESULT($C00D6D65);
// MessageId: MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED
// MessageText:
// The property ID does not match any property supported by the transform.%0
MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED = HRESULT($C00D6D66);
// MessageId: MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG
// MessageText:
// The variant does not have the type expected for this property ID.%0
MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG = HRESULT($C00D6D67);
// MessageId: MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE
// MessageText:
// An attempt was made to set the value on a read-only property.%0
MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE = HRESULT($C00D6D68);
// MessageId: MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM
// MessageText:
// The array property value has an unexpected number of dimensions.%0
MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM = HRESULT($C00D6D69);
// MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG
// MessageText:
// The array or blob property value has an unexpected size.%0
MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG = HRESULT($C00D6D6A);
// MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE
// MessageText:
// The property value is out of range for this transform.%0
MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE = HRESULT($C00D6D6B);
// MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE
// MessageText:
// The property value is incompatible with some other property or mediatype set on the transform.%0
MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE = HRESULT($C00D6D6C);
// MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE
// MessageText:
// The requested operation is not supported for the currently set output mediatype.%0
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE = HRESULT($C00D6D6D);
// MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE
// MessageText:
// The requested operation is not supported for the currently set input mediatype.%0
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE = HRESULT($C00D6D6E);
// MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION
// MessageText:
// The requested operation is not supported for the currently set combination of mediatypes.%0
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION = HRESULT($C00D6D6F);
// MessageId: MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES
// MessageText:
// The requested feature is not supported in combination with some other currently enabled feature.%0
MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES = HRESULT($C00D6D70);
// MessageId: MF_E_TRANSFORM_NEED_MORE_INPUT
// MessageText:
// The transform cannot produce output until it gets more input samples.%0
MF_E_TRANSFORM_NEED_MORE_INPUT = HRESULT($C00D6D72);
// MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG
// MessageText:
// The requested operation is not supported for the current speaker configuration.%0
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG = HRESULT($C00D6D73);
// MessageId: MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING
// MessageText:
// The transform cannot accept mediatype changes in the middle of processing.%0
MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING = HRESULT($C00D6D74);
// MessageId: MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT
// MessageText:
// The caller should not propagate this event to downstream components.%0
MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT = HRESULT($000D6D75);
// MessageId: MF_E_UNSUPPORTED_D3D_TYPE
// MessageText:
// The input type is not supported for D3D device.%0
MF_E_UNSUPPORTED_D3D_TYPE = HRESULT($C00D6D76);
// MessageId: MF_E_TRANSFORM_ASYNC_LOCKED
// MessageText:
// The caller does not appear to support this transform's asynchronous capabilities.%0
MF_E_TRANSFORM_ASYNC_LOCKED = HRESULT($C00D6D77);
// MessageId: MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER
// MessageText:
// An audio compression manager driver could not be initialized by the transform.%0
MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER = HRESULT($C00D6D78);
// MessageId: MF_E_TRANSFORM_STREAM_INVALID_RESOLUTION
// MessageText:
// The input stream has invalid and illegal resolution. Output should stop on next ProcessOutput call after the invalid and illegal resolution is detected.%0
MF_E_TRANSFORM_STREAM_INVALID_RESOLUTION = HRESULT($C00D6D79);
// MessageId: MF_E_TRANSFORM_ASYNC_MFT_NOT_SUPPORTED
// MessageText:
// The transform cannot be asynchronous in current context.%0
MF_E_TRANSFORM_ASYNC_MFT_NOT_SUPPORTED = HRESULT($C00D6D7A);
// MessageId: MF_E_TRANSFORM_EXATTRIBUTE_NOT_SUPPORTED
// MessageText:
// It is not supported in the current context to have the transform copy attributes from an input sample to an output sample.%0
MF_E_TRANSFORM_EXATTRIBUTE_NOT_SUPPORTED = HRESULT($C00D6D7C);
/// ///////////////////////////////////////////////////////////////////////////
// Content Protection errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_LICENSE_INCORRECT_RIGHTS
// MessageText:
// You are not allowed to open this file. Contact the content provider for further assistance.%0
MF_E_LICENSE_INCORRECT_RIGHTS = HRESULT($C00D7148);
// MessageId: MF_E_LICENSE_OUTOFDATE
// MessageText:
// The license for this media file has expired. Get a new license or contact the content provider for further assistance.%0
MF_E_LICENSE_OUTOFDATE = HRESULT($C00D7149);
// MessageId: MF_E_LICENSE_REQUIRED
// MessageText:
// You need a license to perform the requested operation on this media file.%0
MF_E_LICENSE_REQUIRED = HRESULT($C00D714A);
// MessageId: MF_E_DRM_HARDWARE_INCONSISTENT
// MessageText:
// The licenses for your media files are corrupted. Contact Microsoft product support.%0
MF_E_DRM_HARDWARE_INCONSISTENT = HRESULT($C00D714B);
// MessageId: MF_E_NO_CONTENT_PROTECTION_MANAGER
// MessageText:
// The APP needs to provide IMFContentProtectionManager callback to access the protected media file.%0
MF_E_NO_CONTENT_PROTECTION_MANAGER = HRESULT($C00D714C);
// MessageId: MF_E_LICENSE_RESTORE_NO_RIGHTS
// MessageText:
// Client does not have rights to restore licenses.%0
MF_E_LICENSE_RESTORE_NO_RIGHTS = HRESULT($C00D714D);
// MessageId: MF_E_BACKUP_RESTRICTED_LICENSE
// MessageText:
// Licenses are restricted and hence can not be backed up.%0
MF_E_BACKUP_RESTRICTED_LICENSE = HRESULT($C00D714E);
// MessageId: MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION
// MessageText:
// License restore requires machine to be individualized.%0
MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION = HRESULT($C00D714F);
// MessageId: MF_S_PROTECTION_NOT_REQUIRED
// MessageText:
// Protection for stream is not required.%0
MF_S_PROTECTION_NOT_REQUIRED = HRESULT($000D7150);
// MessageId: MF_E_COMPONENT_REVOKED
// MessageText:
// Component is revoked.%0
MF_E_COMPONENT_REVOKED = HRESULT($C00D7151);
// MessageId: MF_E_TRUST_DISABLED
// MessageText:
// Trusted functionality is currently disabled on this component.%0
MF_E_TRUST_DISABLED = HRESULT($C00D7152);
// MessageId: MF_E_WMDRMOTA_NO_ACTION
// MessageText:
// No Action is set on WMDRM Output Trust Authority.%0
MF_E_WMDRMOTA_NO_ACTION = HRESULT($C00D7153);
// MessageId: MF_E_WMDRMOTA_ACTION_ALREADY_SET
// MessageText:
// Action is already set on WMDRM Output Trust Authority.%0
MF_E_WMDRMOTA_ACTION_ALREADY_SET = HRESULT($C00D7154);
// MessageId: MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE
// MessageText:
// DRM Heaader is not available.%0
MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE = HRESULT($C00D7155);
// MessageId: MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED
// MessageText:
// Current encryption scheme is not supported.%0
MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED = HRESULT($C00D7156);
// MessageId: MF_E_WMDRMOTA_ACTION_MISMATCH
// MessageText:
// Action does not match with current configuration.%0
MF_E_WMDRMOTA_ACTION_MISMATCH = HRESULT($C00D7157);
// MessageId: MF_E_WMDRMOTA_INVALID_POLICY
// MessageText:
// Invalid policy for WMDRM Output Trust Authority.%0
MF_E_WMDRMOTA_INVALID_POLICY = HRESULT($C00D7158);
// MessageId: MF_E_POLICY_UNSUPPORTED
// MessageText:
// The policies that the Input Trust Authority requires to be enforced are unsupported by the outputs.%0
MF_E_POLICY_UNSUPPORTED = HRESULT($C00D7159);
// MessageId: MF_E_OPL_NOT_SUPPORTED
// MessageText:
// The OPL that the license requires to be enforced are not supported by the Input Trust Authority.%0
MF_E_OPL_NOT_SUPPORTED = HRESULT($C00D715A);
// MessageId: MF_E_TOPOLOGY_VERIFICATION_FAILED
// MessageText:
// The topology could not be successfully verified.%0
MF_E_TOPOLOGY_VERIFICATION_FAILED = HRESULT($C00D715B);
// MessageId: MF_E_SIGNATURE_VERIFICATION_FAILED
// MessageText:
// Signature verification could not be completed successfully for this component.%0
MF_E_SIGNATURE_VERIFICATION_FAILED = HRESULT($C00D715C);
// MessageId: MF_E_DEBUGGING_NOT_ALLOWED
// MessageText:
// Running this process under a debugger while using protected content is not allowed.%0
MF_E_DEBUGGING_NOT_ALLOWED = HRESULT($C00D715D);
// MessageId: MF_E_CODE_EXPIRED
// MessageText:
// MF component has expired.%0
MF_E_CODE_EXPIRED = HRESULT($C00D715E);
// MessageId: MF_E_GRL_VERSION_TOO_LOW
// MessageText:
// The current GRL on the machine does not meet the minimum version requirements.%0
MF_E_GRL_VERSION_TOO_LOW = HRESULT($C00D715F);
// MessageId: MF_E_GRL_RENEWAL_NOT_FOUND
// MessageText:
// The current GRL on the machine does not contain any renewal entries for the specified revocation.%0
MF_E_GRL_RENEWAL_NOT_FOUND = HRESULT($C00D7160);
// MessageId: MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND
// MessageText:
// The current GRL on the machine does not contain any extensible entries for the specified extension GUID.%0
MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND = HRESULT($C00D7161);
// MessageId: MF_E_KERNEL_UNTRUSTED
// MessageText:
// The kernel isn't secure for high security level content.%0
MF_E_KERNEL_UNTRUSTED = HRESULT($C00D7162);
// MessageId: MF_E_PEAUTH_UNTRUSTED
// MessageText:
// The response from protected environment driver isn't valid.%0
MF_E_PEAUTH_UNTRUSTED = HRESULT($C00D7163);
// MessageId: MF_E_NON_PE_PROCESS
// MessageText:
// A non-PE process tried to talk to PEAuth.%0
MF_E_NON_PE_PROCESS = HRESULT($C00D7165);
// MessageId: MF_E_REBOOT_REQUIRED
// MessageText:
// We need to reboot the machine.%0
MF_E_REBOOT_REQUIRED = HRESULT($C00D7167);
// MessageId: MF_S_WAIT_FOR_POLICY_SET
// MessageText:
// Protection for this stream is not guaranteed to be enforced until the MEPolicySet event is fired.%0
MF_S_WAIT_FOR_POLICY_SET = HRESULT($000D7168);
// MessageId: MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT
// MessageText:
// This video stream is disabled because it is being sent to an unknown software output.%0
MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT = HRESULT($000D7169);
// MessageId: MF_E_GRL_INVALID_FORMAT
// MessageText:
// The GRL file is not correctly formed, it may have been corrupted or overwritten.%0
MF_E_GRL_INVALID_FORMAT = HRESULT($C00D716A);
// MessageId: MF_E_GRL_UNRECOGNIZED_FORMAT
// MessageText:
// The GRL file is in a format newer than those recognized by this GRL Reader.%0
MF_E_GRL_UNRECOGNIZED_FORMAT = HRESULT($C00D716B);
// MessageId: MF_E_ALL_PROCESS_RESTART_REQUIRED
// MessageText:
// The GRL was reloaded and required all processes that can run protected media to restart.%0
MF_E_ALL_PROCESS_RESTART_REQUIRED = HRESULT($C00D716C);
// MessageId: MF_E_PROCESS_RESTART_REQUIRED
// MessageText:
// The GRL was reloaded and the current process needs to restart.%0
MF_E_PROCESS_RESTART_REQUIRED = HRESULT($C00D716D);
// MessageId: MF_E_USERMODE_UNTRUSTED
// MessageText:
// The user space is untrusted for protected content play.%0
MF_E_USERMODE_UNTRUSTED = HRESULT($C00D716E);
// MessageId: MF_E_PEAUTH_SESSION_NOT_STARTED
// MessageText:
// PEAuth communication session hasn't been started.%0
MF_E_PEAUTH_SESSION_NOT_STARTED = HRESULT($C00D716F);
// MessageId: MF_E_PEAUTH_PUBLICKEY_REVOKED
// MessageText:
// PEAuth's public key is revoked.%0
MF_E_PEAUTH_PUBLICKEY_REVOKED = HRESULT($C00D7171);
// MessageId: MF_E_GRL_ABSENT
// MessageText:
// The GRL is absent.%0
MF_E_GRL_ABSENT = HRESULT($C00D7172);
// MessageId: MF_S_PE_TRUSTED
// MessageText:
// The Protected Environment is trusted.%0
MF_S_PE_TRUSTED = HRESULT($000D7173);
// MessageId: MF_E_PE_UNTRUSTED
// MessageText:
// The Protected Environment is untrusted.%0
MF_E_PE_UNTRUSTED = HRESULT($C00D7174);
// MessageId: MF_E_PEAUTH_NOT_STARTED
// MessageText:
// The Protected Environment Authorization service (PEAUTH) has not been started.%0
MF_E_PEAUTH_NOT_STARTED = HRESULT($C00D7175);
// MessageId: MF_E_INCOMPATIBLE_SAMPLE_PROTECTION
// MessageText:
// The sample protection algorithms supported by components are not compatible.%0
MF_E_INCOMPATIBLE_SAMPLE_PROTECTION = HRESULT($C00D7176);
// MessageId: MF_E_PE_SESSIONS_MAXED
// MessageText:
// No more protected environment sessions can be supported.%0
MF_E_PE_SESSIONS_MAXED = HRESULT($C00D7177);
// MessageId: MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED
// MessageText:
// WMDRM ITA does not allow protected content with high security level for this release.%0
MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED = HRESULT($C00D7178);
// MessageId: MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED
// MessageText:
// WMDRM ITA cannot allow the requested action for the content as one or more components is not properly signed.%0
MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED = HRESULT($C00D7179);
// MessageId: MF_E_ITA_UNSUPPORTED_ACTION
// MessageText:
// WMDRM ITA does not support the requested action.%0
MF_E_ITA_UNSUPPORTED_ACTION = HRESULT($C00D717A);
// MessageId: MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS
// MessageText:
// WMDRM ITA encountered an error in parsing the Secure Audio Path parameters.%0
MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS = HRESULT($C00D717B);
// MessageId: MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS
// MessageText:
// The Policy Manager action passed in is invalid.%0
MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS = HRESULT($C00D717C);
// MessageId: MF_E_BAD_OPL_STRUCTURE_FORMAT
// MessageText:
// The structure specifying Output Protection Level is not the correct format.%0
MF_E_BAD_OPL_STRUCTURE_FORMAT = HRESULT($C00D717D);
// MessageId: MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID
// MessageText:
// WMDRM ITA does not recognize the Explicite Analog Video Output Protection guid specified in the license.%0
MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID = HRESULT($C00D717E);
// MessageId: MF_E_NO_PMP_HOST
// MessageText:
// IMFPMPHost object not available.%0
MF_E_NO_PMP_HOST = HRESULT($C00D717F);
// MessageId: MF_E_ITA_OPL_DATA_NOT_INITIALIZED
// MessageText:
// WMDRM ITA could not initialize the Output Protection Level data.%0
MF_E_ITA_OPL_DATA_NOT_INITIALIZED = HRESULT($C00D7180);
// MessageId: MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT
// MessageText:
// WMDRM ITA does not recognize the Analog Video Output specified by the OTA.%0
MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT = HRESULT($C00D7181);
// MessageId: MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT
// MessageText:
// WMDRM ITA does not recognize the Digital Video Output specified by the OTA.%0
MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT = HRESULT($C00D7182);
// MessageId: MF_E_RESOLUTION_REQUIRES_PMP_CREATION_CALLBACK
// MessageText:
// The protected stream cannot be resolved without the callback PKEY_PMP_Creation_Callback in the configuration property store.%0
MF_E_RESOLUTION_REQUIRES_PMP_CREATION_CALLBACK = HRESULT($C00D7183);
// MessageId: MF_E_INVALID_AKE_CHANNEL_PARAMETERS
// MessageText:
// A valid hostname and port number could not be found in the DTCP parameters.%0
MF_E_INVALID_AKE_CHANNEL_PARAMETERS = HRESULT($C00D7184);
// MessageId: MF_E_CONTENT_PROTECTION_SYSTEM_NOT_ENABLED
// MessageText:
// The content protection system was not enabled by the application.%0
MF_E_CONTENT_PROTECTION_SYSTEM_NOT_ENABLED = HRESULT($C00D7185);
// MessageId: MF_E_UNSUPPORTED_CONTENT_PROTECTION_SYSTEM
// MessageText:
// The content protection system is not supported.%0
MF_E_UNSUPPORTED_CONTENT_PROTECTION_SYSTEM = HRESULT($C00D7186);
// MessageId: MF_E_DRM_MIGRATION_NOT_SUPPORTED
// MessageText:
// DRM migration is not supported for the content.%0
MF_E_DRM_MIGRATION_NOT_SUPPORTED = HRESULT($C00D7187);
// MessageId: MF_E_HDCP_AUTHENTICATION_FAILURE
// MessageText:
// Authentication of the HDCP link failed.%0
MF_E_HDCP_AUTHENTICATION_FAILURE = HRESULT($C00D7188);
// MessageId: MF_E_HDCP_LINK_FAILURE
// MessageText:
// The HDCP link failed after being established.%0
MF_E_HDCP_LINK_FAILURE = HRESULT($C00D7189);
/// ///////////////////////////////////////////////////////////////////////////
// Clock errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_CLOCK_INVALID_CONTINUITY_KEY
// MessageText:
// The continuity key supplied is not currently valid.%0
MF_E_CLOCK_INVALID_CONTINUITY_KEY = HRESULT($C00D9C40);
// MessageId: MF_E_CLOCK_NO_TIME_SOURCE
// MessageText:
// No Presentation Time Source has been specified.%0
MF_E_CLOCK_NO_TIME_SOURCE = HRESULT($C00D9C41);
// MessageId: MF_E_CLOCK_STATE_ALREADY_SET
// MessageText:
// The clock is already in the requested state.%0
MF_E_CLOCK_STATE_ALREADY_SET = HRESULT($C00D9C42);
// MessageId: MF_E_CLOCK_NOT_SIMPLE
// MessageText:
// The clock has too many advanced features to carry out the request.%0
MF_E_CLOCK_NOT_SIMPLE = HRESULT($C00D9C43);
// MessageId: MF_S_CLOCK_STOPPED
// MessageText:
// Timer::SetTimer returns this success code if called happened while timer is stopped. Timer is not going to be dispatched until clock is running.%0
MF_S_CLOCK_STOPPED = HRESULT($000D9C44);
/// ///////////////////////////////////////////////////////////////////////////
// MF Quality Management errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_NO_MORE_DROP_MODES
// MessageText:
// The component does not support any more drop modes.%0
MF_E_NO_MORE_DROP_MODES = HRESULT($C00DA028);
// MessageId: MF_E_NO_MORE_QUALITY_LEVELS
// MessageText:
// The component does not support any more quality levels.%0
MF_E_NO_MORE_QUALITY_LEVELS = HRESULT($C00DA029);
// MessageId: MF_E_DROPTIME_NOT_SUPPORTED
// MessageText:
// The component does not support drop time functionality.%0
MF_E_DROPTIME_NOT_SUPPORTED = HRESULT($C00DA02A);
// MessageId: MF_E_QUALITYKNOB_WAIT_LONGER
// MessageText:
// Quality Manager needs to wait longer before bumping the Quality Level up.%0
MF_E_QUALITYKNOB_WAIT_LONGER = HRESULT($C00DA02B);
// MessageId: MF_E_QM_INVALIDSTATE
// MessageText:
// Quality Manager is in an invalid state. Quality Management is off at this moment.%0
MF_E_QM_INVALIDSTATE = HRESULT($C00DA02C);
/// ///////////////////////////////////////////////////////////////////////////
// MF Transcode errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_TRANSCODE_NO_CONTAINERTYPE
// MessageText:
// No transcode output container type is specified.%0
MF_E_TRANSCODE_NO_CONTAINERTYPE = HRESULT($C00DA410);
// MessageId: MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS
// MessageText:
// The profile does not have a media type configuration for any selected source streams.%0
MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS = HRESULT($C00DA411);
// MessageId: MF_E_TRANSCODE_NO_MATCHING_ENCODER
// MessageText:
// Cannot find an encoder MFT that accepts the user preferred output type.%0
MF_E_TRANSCODE_NO_MATCHING_ENCODER = HRESULT($C00DA412);
// MessageId: MF_E_TRANSCODE_INVALID_PROFILE
// MessageText:
// The profile is invalid.%0
MF_E_TRANSCODE_INVALID_PROFILE = HRESULT($C00DA413);
/// ///////////////////////////////////////////////////////////////////////////
// MF HW Device Proxy errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_ALLOCATOR_NOT_INITIALIZED
// MessageText:
// Memory allocator is not initialized.%0
MF_E_ALLOCATOR_NOT_INITIALIZED = HRESULT($C00DA7F8);
// MessageId: MF_E_ALLOCATOR_NOT_COMMITED
// MessageText:
// Memory allocator is not committed yet.%0
MF_E_ALLOCATOR_NOT_COMMITED = HRESULT($C00DA7F9);
// MessageId: MF_E_ALLOCATOR_ALREADY_COMMITED
// MessageText:
// Memory allocator has already been committed.%0
MF_E_ALLOCATOR_ALREADY_COMMITED = HRESULT($C00DA7FA);
// MessageId: MF_E_STREAM_ERROR
// MessageText:
// An error occurred in media stream.%0
MF_E_STREAM_ERROR = HRESULT($C00DA7FB);
// MessageId: MF_E_INVALID_STREAM_STATE
// MessageText:
// Stream is not in a state to handle the request.%0
MF_E_INVALID_STREAM_STATE = HRESULT($C00DA7FC);
// MessageId: MF_E_HW_STREAM_NOT_CONNECTED
// MessageText:
// Hardware stream is not connected yet.%0
MF_E_HW_STREAM_NOT_CONNECTED = HRESULT($C00DA7FD);
/// ///////////////////////////////////////////////////////////////////////////
// MF Capture Engine and MediaCapture errors
/// ///////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_NO_CAPTURE_DEVICES_AVAILABLE
// MessageText:
// No capture devices are available.%0
MF_E_NO_CAPTURE_DEVICES_AVAILABLE = HRESULT($C00DABE0);
// MessageId: MF_E_CAPTURE_SINK_OUTPUT_NOT_SET
// MessageText:
// No output was set for recording.%0
MF_E_CAPTURE_SINK_OUTPUT_NOT_SET = HRESULT($C00DABE1);
// MessageId: MF_E_CAPTURE_SINK_MIRROR_ERROR
// MessageText:
// The current capture sink configuration does not support mirroring.%0
MF_E_CAPTURE_SINK_MIRROR_ERROR = HRESULT($C00DABE2);
// MessageId: MF_E_CAPTURE_SINK_ROTATE_ERROR
// MessageText:
// The current capture sink configuration does not support rotation.%0
MF_E_CAPTURE_SINK_ROTATE_ERROR = HRESULT($C00DABE3);
// MessageId: MF_E_CAPTURE_ENGINE_INVALID_OP
// MessageText:
// The op is invalid.%0
MF_E_CAPTURE_ENGINE_INVALID_OP = HRESULT($C00DABE4);
// MessageId: MF_E_CAPTURE_ENGINE_ALL_EFFECTS_REMOVED
// MessageText:
// The effects previously added were incompatible with the new topology which caused all effects to be removed.%0
MF_E_CAPTURE_ENGINE_ALL_EFFECTS_REMOVED = HRESULT($C00DABE5);
// MessageId: MF_E_CAPTURE_SOURCE_NO_INDEPENDENT_PHOTO_STREAM_PRESENT
// MessageText:
// The current capture source does not have an independent photo stream.%0
MF_E_CAPTURE_SOURCE_NO_INDEPENDENT_PHOTO_STREAM_PRESENT = HRESULT($C00DABE6);
// MessageId: MF_E_CAPTURE_SOURCE_NO_VIDEO_STREAM_PRESENT
// MessageText:
// The current capture source does not have a video stream.%0
MF_E_CAPTURE_SOURCE_NO_VIDEO_STREAM_PRESENT = HRESULT($C00DABE7);
// MessageId: MF_E_CAPTURE_SOURCE_NO_AUDIO_STREAM_PRESENT
// MessageText:
// The current capture source does not have an audio stream.%0
MF_E_CAPTURE_SOURCE_NO_AUDIO_STREAM_PRESENT = HRESULT($C00DABE8);
// MessageId: MF_E_CAPTURE_SOURCE_DEVICE_EXTENDEDPROP_OP_IN_PROGRESS
// MessageText:
// The capture source device has an asynchronous extended property operation in progress.%0
MF_E_CAPTURE_SOURCE_DEVICE_EXTENDEDPROP_OP_IN_PROGRESS = HRESULT($C00DABE9);
// MessageId: MF_E_CAPTURE_PROPERTY_SET_DURING_PHOTO
// MessageText:
// A property cannot be set because a photo or photo sequence is in progress.%0
MF_E_CAPTURE_PROPERTY_SET_DURING_PHOTO = HRESULT($C00DABEA);
// MessageId: MF_E_CAPTURE_NO_SAMPLES_IN_QUEUE
// MessageText:
// No more samples in queue.%0
MF_E_CAPTURE_NO_SAMPLES_IN_QUEUE = HRESULT($C00DABEB);
// MessageId: MF_E_HW_ACCELERATED_THUMBNAIL_NOT_SUPPORTED
// MessageText:
// Hardware accelerated thumbnail generation is not supported for the currently selected mediatype on the mediacapture stream.%0
MF_E_HW_ACCELERATED_THUMBNAIL_NOT_SUPPORTED = HRESULT($C00DABEC);
// MessageId: MF_E_UNSUPPORTED_CAPTURE_DEVICE_PRESENT
// MessageText:
// Capture device that is present on the system is not supported by Media Foundation.%0
MF_E_UNSUPPORTED_CAPTURE_DEVICE_PRESENT = HRESULT($C00DABED);
//////////////////////////////////////////////////////////////////////////////
// Media Timeline Controller errors
//////////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_TIMELINECONTROLLER_UNSUPPORTED_SOURCE_TYPE
// MessageText:
// Media Source type is not supported in Media Timeline Controller scenarios.%0
MF_E_TIMELINECONTROLLER_UNSUPPORTED_SOURCE_TYPE = HRESULT($C00DAFC8);
// MessageId: MF_E_TIMELINECONTROLLER_NOT_ALLOWED
// MessageText:
// Operation is not allowed when Media Timeline Controller is attached.%0
MF_E_TIMELINECONTROLLER_NOT_ALLOWED = HRESULT($C00DAFC9);
// MessageId: MF_E_TIMELINECONTROLLER_CANNOT_ATTACH
// MessageText:
// Attaching Media Timeline Controller is blocked because of the current state of the object.%0
MF_E_TIMELINECONTROLLER_CANNOT_ATTACH = HRESULT($C00DAFCA);
//////////////////////////////////////////////////////////////////////////////
// MediaExtension as AppService errors
//////////////////////////////////////////////////////////////////////////////
// MessageId: MF_E_MEDIA_EXTENSION_APPSERVICE_CONNECTION_FAILED
// MessageText:
// Connection to app service providing a media extension failed.%0
MF_E_MEDIA_EXTENSION_APPSERVICE_CONNECTION_FAILED = HRESULT($C00DB3B0);
// MessageId: MF_E_MEDIA_EXTENSION_APPSERVICE_REQUEST_FAILED
// MessageText:
// App service providing a media extension failed to process the request.%0
MF_E_MEDIA_EXTENSION_APPSERVICE_REQUEST_FAILED = HRESULT($C00DB3B1);
// MessageId: MF_E_MEDIA_EXTENSION_PACKAGE_INTEGRITY_CHECK_FAILED
// MessageText:
// Package integrity check for app failed.%0
MF_E_MEDIA_EXTENSION_PACKAGE_INTEGRITY_CHECK_FAILED = HRESULT($C00DB3B2);
// MessageId: MF_E_MEDIA_EXTENSION_PACKAGE_LICENSE_INVALID
// MessageText:
// License check for app failed.%0
MF_E_MEDIA_EXTENSION_PACKAGE_LICENSE_INVALID = HRESULT($C00DB3B3);
/// ///////////////////////////////////////////////////////////////////////////
// MF Media Engine errors - see W3C definitions for details
/// ///////////////////////////////////////////////////////////////////////////
MF_INDEX_SIZE_ERR = $80700001;
MF_NOT_FOUND_ERR = $80700008;
MF_NOT_SUPPORTED_ERR = $80700009;
MF_INVALID_STATE_ERR = $8070000B;
MF_SYNTAX_ERR = $8070000C;
MF_INVALID_ACCESS_ERR = $8070000F;
MF_QUOTA_EXCEEDED_ERR = $80700016;
MF_PARSE_ERR = $80700051;
MF_TYPE_ERR = $80704005;
function STATUS_SEVERITY(Hr: HRESULT): dword; inline;
implementation
function STATUS_SEVERITY(Hr: HRESULT): dword; inline;
begin
Result := ((Hr shl 30) and $3);
end;
end.
|
unit sfBessel;
{Common code for special functions: Bessel functions and related}
interface
{$i std.inc}
{$ifdef BIT16}
{$N+}
{$endif}
{$ifdef NOBASM}
{$undef BASM}
{$endif}
(*************************************************************************
DESCRIPTION : Common code: Bessel functions and related
REQUIREMENTS : TP5.5-7, D2-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REMARK : The unit can be compiled with TP5 but some functions generate
invalid operations due to TP5's brain-damaged usage of the FPU
REFERENCES : References used in this unit, main index in amath_info.txt/references
[1] [HMF]: M. Abramowitz, I.A. Stegun. Handbook of Mathematical Functions, New York, 1970
http://www.math.sfu.ca/~cbm/aands/
[7] Cephes Mathematical Library, Version 2.8
http://www.moshier.net/#Cephes or http://www.netlib.org/cephes/
[13] [NR]: W.H. Press et al, Numerical Recipes in C, 2nd ed., Cambridge, 1992,
http://www.nrbook.com/a/bookcpdf.html
[14] SLATEC Common Mathematical Library, Version 4.1, July 1993
(general purpose mathematical and statistical routines written in Fortran 77)
http://www.netlib.org/slatec
[19] Boost C++ Libraries, Release 1.42.0, 2010.
http://www.boost.org/
[20] Special functions by Wayne Fullerton,
http://www.netlib.org/fn
Almost identical to the FNLIB subset of SLATEC [14]
[22] A.J. MacLeod, MISCFUN: A software package to compute uncommon special functions.
ACM Trans. on Math. Soft. 22 (1996), pp.288-301.
Fortran source: http://netlib.org/toms/757
[30] [NIST]: F.W.J. Olver, D.W. Lozier, R.F. Boisvert, C.W. Clark, NIST Handbook
of Mathematical Functions, Cambridge, 2010. Online resource: NIST Digital
Library of Mathematical Functions, http://dlmf.nist.gov/
[51] N.M. Temme, On the Numerical Evaluation of the Ordinary Bessel Function
of the Second Kind. J. Comput. Phys., 21(3): 343-350 (1976), section 2.
Available as http://oai.cwi.nl/oai/asset/10710/10710A.pdf
[52] N.M. Temme, On the Numerical Evaluation of the Modified Bessel
Function of the Third Kind, 2nd edition. Preprint, available
as http://oai.cwi.nl/oai/asset/7885/7885A.pdf
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00.00 17.08.10 W.Ehrhardt Common version number after split
1.00.01 11.09.10 we Improved arg checking and NAN/INF handling
1.00.02 12.09.10 we Extended over/underflow check in sfc_jn
1.02.00 31.10.10 we sfc_yn: improved pre-checks
1.02.01 01.11.10 we sfc_jv, sfc_yv, sfc_bess_jyv
1.02.02 03.11.10 we sfc_iv, sfc_kv, sfc_bess_ikv
1.02.03 04.11.10 we NAN/INF handling for real order functions
1.02.04 05.11.10 we Airy functions Ai, Ai', Bi, Bi'
1.02.05 06.11.10 we sfc_sph_jn, sfc_sph_yn
1.02.06 06.11.10 we increased MAXIT in CF1_j
1.02.07 14.11.10 we Fixed sfc_i0e for small x
1.02.08 15.11.10 we sfc_ive, sfc_kve
1.04.00 10.02.11 we Improved J0,J1 for |x| >= 500; Y0,Y1 for x >= 1600
1.05.00 10.04.11 we Zero order Kelvin functions ber,bei,ker,kei
1.05.01 10.04.11 we sfc_kei(0) = -Pi/4
1.06.00 05.05.11 we sfc_struve_h0
1.06.01 05.05.11 we sfc_struve_h1
1.06.02 06.05.11 we sfc_struve_l1
1.06.03 07.05.11 we sfc_struve_l0
1.06.04 26.05.11 we fix for very large x in kelvin_large
1.08.00 13.08.11 we special cases |v|=0,1 in sfc_kve
1.08.01 13.08.11 we v=-1 in sfc_iv/e
1.10.00 28.12.11 we sfc_sph_in, sfc_sph_ine
1.10.01 29.12.11 we sfc_sph_kn, sfc_sph_kne
1.10.02 29.12.11 we Fix bug for small negative x in sfc_sph_ine
1.15.00 19.02.13 we improved quick check in sfc_jn
1.15.01 20.02.13 we Yv_series
1.15.02 20.02.13 we handle some near overflows in bessel_jy
1.15.03 20.02.13 we improved check in sfc_yn
1.18.00 09.05.13 we Airy/Scorer functions sfc_airy_gi/hi
1.18.01 09.05.13 we Prevent some wrong compiler optimizations for div by 3
1.19.00 06.06.13 we Fix typo in h1v_large
1.19.01 08.06.13 we sfc_bess_kv2
1.19.02 27.06.13 we Check overflow / return INF in bessel_jy
1.24.00 26.03.14 we sfc_yn with LnPi from AMath
1.28.00 08.08.14 we Iv := PosInf_x if Kv,Kv1=0 in bessel_ik or if x >= IvMaxXH in sfc_iv
1.33.00 07.06.15 we new IJ_series replaces Jv_series
1.33.01 07.06.15 we rewrite of sfc_in: use IJ_series and CF1_I
1.33.02 08.06.15 we improved bess_m0p0/bess_m1p1 with rem_2pi_sym and Kahan summation
1.33.03 09.06.15 we sfc_struve_l
1.33.04 10.06.15 we sfc_struve_h
1.33.05 10.06.15 we sfc_struve_l0/1 use sfc_struve_l
1.33.06 14.06.15 we sfc_struve_h/l with real v >= 0
1.33.07 19.06.15 we scaled Airy functions sfc_airy_ais, sfc_airy_bis
1.34.00 05.07.15 we special cases Yv(+- 1/2, x)
1.34.01 06.07.15 we sfc_struve_h for v < 0
1.34.02 07.07.15 we sfc_struve_l for v < 0
1.34.03 09.07.15 we fix sfc_struve_h/l(v,0) for v<=-1
1.35.00 26.08.15 we sfBessel: Sqrt2 in kelvin functions (anti-'optimizing')
***************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2015 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
(*-------------------------------------------------------------------------
This Pascal code uses material and ideas from open source and public
domain libraries, see the file '3rdparty.ama' for the licenses.
---------------------------------------------------------------------------*)
function sfc_i0(x: extended): extended;
{-Return I0(x), the modified Bessel function of the 1st kind, order zero}
function sfc_i0e(x: extended): extended;
{-Return I0(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order zero}
function sfc_i1(x: extended): extended;
{-Return I1(x), the modified Bessel function of the 1st kind, order one}
function sfc_i1e(x: extended): extended;
{-Return I1(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order one}
function sfc_in(n: integer; x: extended): extended;
{-Return I_n(x), the modified Bessel function of the 1st kind, order n.}
function sfc_j0(x: extended): extended;
{-Return J0(x), the Bessel function of the 1st kind, order zero}
function sfc_j1(x: extended): extended;
{-Return J1(x), the Bessel function of the 1st kind, order one}
function sfc_jn(n: integer; x: extended): extended;
{-Return J_n(x), the Bessel function of the 1st kind, order n; not suitable for large n or x.}
function sfc_k0(x: extended): extended;
{-Return K0(x), the modified Bessel function of the 2nd kind, order zero, x>0}
function sfc_k0e(x: extended): extended;
{-Return K0(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order zero, x>0}
function sfc_k1(x: extended): extended;
{-Return K1(x), the modified Bessel function of the 2nd kind, order one, x>0}
function sfc_k1e(x: extended): extended;
{-Return K1(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order one, x>0}
function sfc_kn(n: integer; x: extended): extended;
{-Return K_n(x), the modified Bessel function of the 2nd kind, order n, x>0, not suitable for large n}
function sfc_y0(x: extended): extended;
{-Return Y0(x), the Bessel function of the 2nd kind, order zero; x>0}
function sfc_y1(x: extended): extended;
{-Return Y1(x), the Bessel function of the 2nd kind, order one; x>0}
function sfc_yn(n: integer; x: extended): extended;
{-Return Y_n(x), the Bessel function of the 2nd kind, order n, x>0, not suitable for large n or x}
function sfc_jv(v, x: extended): extended;
{-Return J_v(x), the Bessel function of the 1st kind, order v; not suitable for large v.}
function sfc_yv(v, x: extended): extended;
{-Return Y_v(x), the Bessel function of the 2nd kind, order v; x > 0; not suitable for large v.}
function sfc_iv(v, x: extended): extended;
{-Return I_v(x), the modified Bessel function of the 1st kind, order v.}
function sfc_kv(v, x: extended): extended;
{-Return K_v(x), the modified Bessel function of the 2nd kind, order v, x>0}
function sfc_ive(v, x: extended): extended;
{-Return I_v(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order v.}
function sfc_kve(v, x: extended): extended;
{-Return K_v(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order v, x>0}
procedure sfc_bess_ikv(v,x: extended; var Iv,Kv: extended);
{-Return I_v(x) and K_v(x), no checks, x>0, |v| < MaxLongint}
procedure sfc_bess_jyv(v,x: extended; var Jv,Yv: extended);
{-Return J_v(x) and Y_v(x), no checks, x>0, |v| < MaxLongint}
procedure sfc_bess_kv2(v,x: extended; var Kv, Kv1: extended);
{-Return K(v,x) and K(v+1,x), no checks, x>0, |v| < MaxLongint}
function sfc_sph_jn(n: integer; x: extended): extended;
{-Return j_n(x), the spherical Bessel function of the 1st kind, order n}
function sfc_sph_yn(n: integer; x: extended): extended;
{-Return y_n(x), the spherical Bessel function of the 2nd kind, order n >=0 , x<>0}
function sfc_sph_in(n: integer; x: extended): extended;
{-Return i_n(x), the modified spherical Bessel function of the 1st/2nd kind, order n}
function sfc_sph_ine(n: integer; x: extended): extended;
{-Return i_n(x)*exp(-|x|), the exponentially scaled modified spherical Bessel function of the 1st/2nd kind, order n}
function sfc_sph_kn(n: integer; x: extended): extended;
{-Return k_n(x), the modified spherical Bessel function of the 3rd kind, order n, x>0}
function sfc_sph_kne(n: integer; x: extended): extended;
{-Return k_n(x)*exp(x), the exponentially scaled modified spherical Bessel function of the 3rd kind, order n, x>0}
function sfc_airy_ai(x: extended): extended;
{-Return the Airy function Ai(x)}
function sfc_airy_aip(x: extended): extended;
{-Return the Airy function Ai'(x)}
function sfc_airy_ais(x: extended): extended;
{-Return the scaled Airy function Ai(x) if x <= 0, Ai(x)*exp(2/3*x^1.5) for x > 0}
function sfc_airy_bi(x: extended): extended;
{-Return the Airy function Bi(x)}
function sfc_airy_bip(x: extended): extended;
{-Return the Airy function Bi'(x)}
function sfc_airy_bis(x: extended): extended;
{-Return the scaled Airy function Bi(x) if x <= 0, Bi(x)*exp(-2/3*x^1.5) for x > 0}
function sfc_airy_gi(x: extended): extended;
{-Return the Airy/Scorer function Gi(x) = 1/Pi*integral(sin(x*t+t^3/3), t=0..INF)}
function sfc_airy_hi(x: extended): extended;
{-Return the Airy/Scorer function Hi(x) = 1/Pi*integral(exp(x*t-t^3/3), t=0..INF)}
function sfc_ber(x: extended): extended;
{-Return the Kelvin function ber(x)}
function sfc_bei(x: extended): extended;
{-Return the Kelvin function bei(x)}
function sfc_ker(x: extended): extended;
{-Return the Kelvin function ker(x), x > 0}
function sfc_kei(x: extended): extended;
{-Return the Kelvin function kei(x), x >= 0}
procedure sfc_ker_kei(x: extended; var kr, ki: extended);
{-Return the Kelvin functions kr=ker(x), ki=kei(x), x > 0}
procedure sfc_ber_bei(x: extended; var br, bi: extended);
{-Return the Kelvin functions br=ber(x), bi=bei(x)}
function sfc_struve_h0(x: extended): extended;
{-Return H0(x), the Struve function of order 0}
function sfc_struve_h1(x: extended): extended;
{-Return H1(x), the Struve function of order 1}
function sfc_struve_h(v,x: extended): extended;
{-Return H_v(x), the Struve function of order v, x < 0 only if v is an integer.}
function sfc_struve_l0(x: extended): extended;
{-Return L0(x), the modified Struve function of order 0}
function sfc_struve_l1(x: extended): extended;
{-Return L1(x), the modified Struve function of order 1}
function sfc_struve_l(v, x: extended): extended;
{-Return L_v(x), the modified Struve function of order v, x < 0 only if v is an integer.}
implementation
uses
AMath,
sfBasic, {Basic common code}
sfGamma; {Gamma function and related}
{---------------------------------------------------------------------------}
function IJ_series(v,x: extended; CalcJv: boolean): extended;
{-Power series for Bessel J_v(x) or I_v(x), 0 <= v < MAXGAMX-1, 0 <= x <= 2}
var
f,s,t: extended;
n: integer;
begin
f := 0.5*x;
t := power(f,v)/sfc_gamma(v+1.0);
if CalcJv then f := -f*f else f := f*f;
s := t;
n := 0;
repeat
inc(n);
t := t*f/n/(v+n);
s := s + t;
until abs(t) <= 0.5*eps_x*abs(s);
IJ_series := s;
end;
{---------------------------------------------------------------------------}
procedure CF1_j(v,x: extended; var fv: extended; var s: integer);
{-Return J_(v+1)(x) / J_v(x), efficient only if |x| <= |v|}
var
c,d,f,b,t,tiny,tol: extended;
k: longint;
const
MAXIT = longint(32000)*100; {see note below}
begin
s := 1;
{Evaluate HMF [1], 9.1.73 using modified Lentz's method. s keeps track }
{of sign changes in the denominator. Ref: NR [13] (6.7.2) and p. 244, }
{function bessjy and Boost [19] file bessel_jy.hpp, function CF1_jy. }
{Note that CF1_j needs about O(|x|) iterations if |x| > |v|. But unless}
{there is a better implementation below the asymptotic range, CF1_j is}
{is used in the last resort branch of bessel_jy. If a better algorithm }
{(like Olver/Temme uniform Airy type asymptotic expansion) is available}
{the factor 100 in the MAXIT declaration should be removed.}
tol := 2.0*eps_x;
tiny := Sqrt_MinExt;
c := tiny;
f := tiny;
d := 0.0;
for k:=1 to MAXIT do begin
b := 2.0*(v + k)/x;
c := b - 1.0/c;
d := b - d;
if c=0.0 then c := tiny;
if d=0.0 then d := tiny;
d := 1.0/d;
t := c * d;
f := f*t;
if d<0 then s := -s;
if abs(t-1.0) < tol then begin
fv := -f;
exit;
end;
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
fv := -f;
end;
{---------------------------------------------------------------------------}
procedure CF1_I(v,x: extended; var fv: extended);
{-Return I_(v+1)(x) / I_v(x) using continued fraction}
var
c,d,f,b,t,tiny,tol: extended;
k: integer;
const
MAXIT = 30000;
begin
{Evaluate NIST[30], 10.33.1 using modified Lentz's method.}
{Ref: NR [13] (6.7.21) and p.248, function bessik }
{and Boost [19] file bessel_ik.hpp, function CF1_Ik }
{If |x| <= |v|, CF1_I converges rapidly but if |x| > |v| }
{then CF1_I needs O(|x|) iterations to converge! }
tol := 2.0*eps_x;
tiny := Sqrt_MinExt;
c := tiny;
f := tiny;
d := 0.0;
for k:=1 to MAXIT do begin
b := 2.0*(v + k)/x;
c := b + 1.0/c;
d := b + d;
if c=0.0 then c := tiny;
if d=0.0 then d := tiny;
d := 1.0/d;
t := c * d;
f := f*t;
if abs(t-1.0) < tol then begin
fv := f;
exit;
end;
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
fv := f;
end;
{---------------------------------------------------------------------------}
procedure h1v_large(v, x: extended; var mv,tmx: extended);
{-Return modulus and (phase - x) of the Hankel function H1_v(x), x > 0 large}
var
s,m,m2,y: extended;
const
c56 = 5.0/6.0;
begin
{Modulus Mv: asymptotic expansion from HMF[1] 9.2.28}
y := sqr(0.5/x);
m := 4.0*sqr(v);
m2 := sqr(m);
s := 1.0 + 0.5*y*(m-1.0)*(1.0 + 0.75*y*(m-9.0)*(1.0 + c56*y*(m-25.0)));
mv := sqrt(2.0*s/(Pi*x));
{Phase theta_v - x: asymptotic expansion from HMF[1] 9.2.29}
y := 0.25*y;
s := (5.0*m*m2 - 1535.0*m2 + 54703.0*m - 375733.0)/14.0;
s := s*y + (m2 - 114.0*m + 1073)/5.0;
s := s*y + (m-25.0)/6.0;
tmx:= (m-1.0)*(s*y + 0.5)/(4.0*x) - Pi*(0.5*v+0.25)
end;
{---------------------------------------------------------------------------}
function bessj_large(v, x: extended): extended;
{-Return J_v(x) via modulus/phase asymptotic expansion, x large}
var
mv,tv,st,ct,sx,cx: extended;
begin
h1v_large(v,x,mv,tv);
sincos(tv,st,ct);
sincos(x,sx,cx);
{J_v := mv*cos(x+tv); cos(x+tv) = cos(x)cos(tv) - sin(x)sin(tv)}
bessj_large := mv*(cx*ct - sx*st);
end;
{---------------------------------------------------------------------------}
function bessy_large(v, x: extended): extended;
{-Return Y_v(x) via modulus/phase asymptotic expansion, x large}
var
mv,tv,st,ct,sx,cx: extended;
begin
h1v_large(v,x,mv,tv);
sincos(tv,st,ct);
sincos(x,sx,cx);
{Y_v := mv*sin(x+tv); sin(x+tv) = cos(x)sin(tv) + sin(x)cos(tv)}
bessy_large := mv*(st*cx + ct*sx);
end;
{---------------------------------------------------------------------------}
procedure bess_m0p0(x: extended; var m0,p0: extended);
{-Modulus and phase for J0(x) and Y0(x), x >= 9.0}
var
y,z,s: extended;
const
m0nhex: array[0..7] of THexExtW = (
($cb2b,$4b73,$8075,$8aa3,$3ff8),
($6b78,$4cc6,$25b7,$b912,$3ffb),
($cfe9,$74e0,$67a1,$b75e,$3ffe),
($b1cd,$4e5e,$2274,$b5ec,$4000),
($5e4b,$e3af,$59bb,$f409,$4001),
($b343,$2673,$4e51,$a36b,$4002),
($38a3,$a663,$7b91,$dbab,$4001),
($8559,$f552,$3a38,$ca1d,$3ffd));
m0dhex: array[0..7] of THexExtW = (
($8a83,$1b80,$003e,$adc2,$3ff8),
($ed5a,$31cd,$b3ac,$e7f3,$3ffb),
($7e3f,$b8dd,$04df,$e5fd,$3ffe),
($775a,$1b79,$7d9c,$e475,$4000),
($b837,$3075,$dbc0,$99ce,$4002),
($5e3d,$b5f4,$9848,$d032,$4002),
($4498,$3d2a,$f3fb,$91df,$4002),
($0000,$0000,$0000,$8000,$3fff));
p0nhex: array[0..5] of THexExtW = (
($4c2f,$2dd8,$79c3,$e65d,$bfe9),
($dc17,$325e,$8baf,$9d35,$bff1),
($e514,$8866,$25a9,$8309,$bff7),
($8d8a,$84e7,$dbd5,$9e75,$bffb),
($1e30,$04da,$b769,$800a,$bffe),
($5106,$12a6,$4dd2,$bc55,$bffe));
p0dhex: array[0..6] of THexExtW = (
($4c8c,$2dd8,$79c3,$e65d,$3fec),
($ac5c,$4806,$8709,$9dad,$3ff4),
($37bf,$fcc8,$9b9f,$844b,$3ffa),
($6f25,$2a95,$2dc6,$a285,$3ffe),
($4b69,$3f87,$131f,$891f,$4001),
($f3e9,$b2a5,$6652,$ec17,$4001),
($0000,$0000,$0000,$8000,$3fff));
var
m0n: array[0..7] of extended absolute m0nhex;
m0d: array[0..7] of extended absolute m0dhex;
p0n: array[0..5] of extended absolute p0nhex;
p0d: array[0..6] of extended absolute p0dhex;
begin
{Ref: Cephes [7], file ldouble\j0l.c}
{See also HMF[1], sections 9.2.17 .. 9.2.31}
{Calculate the modulus m0(x) = sqrt(J0(x)^2 + Y0(x)^2) and the}
{phase p0(x) = arctan(Y0(x)/J0(x)) with rational approximations}
{For x>=9: J0(x) = m0(x)*cos(p0(x)) and Y0(x) = m0(x)*sin(p0(x))}
z := sqr(1.0/x);
y := abs(x);
s := rem_2pi_sym(y);
p0 := PolEvalX(z,p0n,6)/PolEvalX(z,p0d,7)/y;
z := 1.0/y;
m0 := PolEvalX(z,m0n,8)/PolEvalX(z,m0d,8)/sqrt(y);
{Compute p0 := rem_2pi_sym(y) - Pi_4 + p0 with optimized Kahan}
{summation. Without rem_p2pi and Kahan we get a relative error}
{of 1.4e-18 for J0(18), with this code it is 5.4e-20.}
{Note that this improves only J0/Y0 for arguments x near the }
{zeroes. With the recurrence relations for Jn/Yn only absolute}
{(NOT relative) accuracies of order eps_x can be achieved! }
z := -Pi_4;
y := s + z;
z := (y - s) - z;
p0 := y + (p0 - z);
end;
{---------------------------------------------------------------------------}
function sfc_j0(x: extended): extended;
{-Return J0(x), the Bessel function of the 1st kind, order zero}
var
y,z: extended;
const
{Squares of first three roots of J0, calculated with Maple and t_rcalc/xh}
j1h: THexExtW = ($DBB7,$315D,$DC02,$B90F,$4001); {5.7831859629467845213}
j2h: THexExtW = ($7778,$0EEB,$2531,$F3C5,$4003); {3.0471262343662086400E+1}
j3h: THexExtW = ($40F6,$0ABB,$25C1,$95C6,$4005); {7.4887006790695183442E+1}
var
jz1: extended absolute j1h;
jz2: extended absolute j2h;
jz3: extended absolute j3h;
const
j0nhex: array[0..7] of THexExtW = (
($b96c,$c486,$fb95,$9f47,$c03a),
($4018,$ad26,$71ba,$e643,$4034),
($1b0b,$6331,$7add,$8753,$c02e),
($943a,$69b7,$36ca,$a996,$4026),
($008c,$7b60,$d119,$f792,$c01d),
($fe10,$b608,$4829,$d503,$4014),
($a9a8,$e62b,$3b28,$ca73,$c00a),
($f759,$4208,$23d6,$a5ff,$3fff));
j0dhex: array[0..8] of THexExtW = (
($00ac,$fb2b,$6f62,$804b,$4048),
($fdce,$a4ca,$2ed8,$88b8,$4041),
($3d2c,$ed55,$20e1,$9105,$4039),
($0841,$8cb6,$5a46,$c9e3,$4030),
($fed1,$086d,$3425,$cc0a,$4027),
($66d2,$93fe,$0762,$9b79,$401e),
($e1a0,$923f,$cb5c,$b1a2,$4014),
($bdfe,$c832,$5b9f,$8e9f,$400a),
($0000,$0000,$0000,$8000,$3fff));
var
j0n: array[0..7] of extended absolute j0nhex;
j0d: array[0..8] of extended absolute j0dhex;
begin
{Ref: Cephes [7], file ldouble\j0l.c}
x := abs(x);
if x < 9.0 then begin
{In the interval [0,9) a rational approximation of the form }
{J0(x) = (x^2 - r^2) (x^2 - s^2) (x^2 - t^2) P7(x^2)/Q8(x^2)}
{is used, where r, s, t are the first three zeros of J0.}
z := sqr(x);
y := (z - jz1)*(z - jz2)*(z - jz3);
sfc_j0 := y*PolEvalX(z,j0n,8)/PolEvalX(z,j0d,9);
end
else begin
{For x>=9 the common rational approximations to modulus}
{and phase are used J0(x) = modulus * cos(phase).}
if x >= 500.0 then sfc_j0 := bessj_large(0,x)
else begin
bess_m0p0(x,y,z);
sfc_j0 := y*cos(z);
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_y0(x: extended): extended;
{-Return Y0(x), the Bessel function of the 2nd kind, order zero; x>0}
var
y, z: extended;
const
{The first four roots of Y0, calculated with Maple and t_rcalc/xh}
y1h: THexExtW = ($DE10,$C2B4,$9A6C,$FD4A,$4000); {3.9576784193148578685}
y2h: THexExtW = ($1734,$3908,$EE27,$E2C0,$4001); {7.0860510603017726975}
y3h: THexExtW = ($BC69,$23EA,$B9AD,$A38E,$4002); {10.222345043496417019}
y4h: THexExtW = ($4D04,$0F3A,$0E25,$D5C7,$4002); {13.361097473872763478}
var
y0z1: extended absolute y1h;
y0z2: extended absolute y2h;
y0z3: extended absolute y3h;
y0z4: extended absolute y4h;
const
y0nhex: array[0..7] of THexExtW = (
($5fbd,$0171,$135a,$8340,$c035),
($501f,$6264,$bdf4,$9d17,$4036),
($23c9,$6b29,$4244,$c4c9,$c032),
($b219,$37ba,$5142,$9f1f,$402d),
($3e3c,$b343,$46c9,$e45f,$c026),
($2fdd,$4b27,$ca98,$a1c3,$401f),
($2ec0,$7b95,$297f,$df70,$c016),
($126c,$20be,$647f,$f344,$400c));
y0dhex: array[0..7] of THexExtW = (
($241a,$8f2b,$629a,$de4b,$4038),
($04d3,$a629,$d61d,$b410,$4032),
($6732,$8c1b,$c5ab,$9384,$402b),
($553b,$4dc8,$8695,$a0c3,$4023),
($97a4,$90fa,$a7e9,$801c,$401b),
($d938,$b6b2,$71d8,$98be,$4012),
($9057,$7f25,$59b7,$8219,$4009),
($0000,$0000,$0000,$8000,$3fff));
y059nh: array[0..9] of THexExtW = (
($f90c,$3510,$0be9,$87e7,$c012),
($fd54,$b2fe,$0a23,$e37e,$c00f),
($8c07,$29e3,$11be,$9f10,$4012),
($49e2,$fb52,$02af,$be8a,$4010),
($e8fa,$4b44,$4a39,$dc5b,$400b),
($62e0,$c25b,$2cb3,$8f12,$c00b),
($d5a3,$f673,$4e59,$9a8c,$4005),
($5504,$035a,$59fa,$ca14,$4003),
($1207,$46ea,$c3db,$bc88,$bfff),
($992f,$ab45,$90b6,$c20b,$3ff9));
y059dh: array[0..9] of THexExtW = (
($3b3b,$ea0b,$b8d1,$8bd7,$401d),
($ceb6,$3463,$5ddb,$d1b5,$401e),
($e26b,$76b9,$250a,$a7fb,$c01c),
($27ff,$ca92,$3d78,$cea1,$4019),
($ec8a,$4697,$ddde,$a742,$c016),
($e8b6,$d705,$da91,$d62c,$4012),
($a28c,$5563,$d19f,$c75e,$c00e),
($ad09,$8e6a,$a502,$8b0c,$400a),
($debf,$a468,$8a55,$f96b,$c004),
($0000,$0000,$0000,$8000,$3fff));
var
y059n: array[0..9] of extended absolute y059nh;
y059d: array[0..9] of extended absolute y059dh;
y0n: array[0..7] of extended absolute y0nhex;
y0d: array[0..7] of extended absolute y0dhex;
begin
{Ref: Cephes [7], file ldouble\j0l.c}
if x<=0.0 then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_y0 := NaN_x;
exit;
end;
if x < 9.0 then begin
z := sqr(x);
if z < 20.25 then begin
{In the interval [0,4.5) a rational approximation of the}
{form Y0(x) = P7(x)/Q7(x) + 2/Pi*ln(x)*J0(x) is used. }
y := ln(x)*sfc_j0(x)/Pi_2;
sfc_y0 := y + PolEvalX(z,y0n,8)/PolEvalX(z,y0d,8);
end
else begin
{In the interval [4.5,9) a rational approximation of the}
{form Y0(x) = (x - p)(x - q)(x - r)(x - s)P9(x)/Q9(x) is}
{is used where p, q, r, s are first four zeros of Y0(x).}
y := (x - y0z1)*(x - y0z2)*(x - y0z3)*(x - y0z4);
sfc_y0 := y * PolEvalX(x,y059n,10)/PolEvalX(x,y059d,10);
end;
end
else begin
{For x>=9 the common rational approximations to modulus}
{and phase are used Y0(x) = modulus * sin(phase).}
if x >= 1600 then sfc_y0 := bessy_large(0,x)
else begin
bess_m0p0(x,y,z);
sfc_y0 := y*sin(z);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure bess_m1p1(x: extended; var m1,p1: extended);
{-Modulus and phase for J1(x) and Y1(x), x >= 9.0}
var
y,z,s: extended;
const
m1nhex: array[0..7] of THexExtW = (
($a905,$05fb,$3101,$82c9,$3ff9),
($6de4,$8fae,$fe26,$8097,$3ffc),
($2cb0,$c657,$be70,$81e0,$3fff),
($71e6,$88a5,$0a53,$b702,$4000),
($e5e2,$6914,$3a08,$e582,$4001),
($7d55,$db8c,$e825,$a1c2,$4000),
($3111,$863a,$3a61,$c8a0,$3ffd),
($3d53,$b598,$f3bf,$a155,$c001));
m1dhex: array[0..8] of THexExtW = (
($1237,$cc6c,$7356,$a3ea,$3ff9),
($fc82,$02c7,$17a4,$a12b,$3ffc),
($37ce,$79ae,$2f15,$a24c,$3fff),
($77b6,$34e2,$501a,$e37a,$4000),
($0260,$746b,$d030,$8c14,$4002),
($6420,$97ce,$8e44,$a208,$4000),
($77b5,$8f2d,$b6bf,$ebe1,$bffe),
($2603,$640e,$7d8d,$c775,$c001),
($0000,$0000,$0000,$8000,$3fff));
p1nhex: array[0..5] of THexExtW = (
($540c,$c1d5,$b096,$e54f,$3feb),
($f74f,$be87,$7e7d,$9741,$3ff3),
($a830,$f4a3,$2c60,$f144,$3ff8),
($e907,$28b9,$7cb7,$895c,$3ffd),
($6050,$98aa,$3500,$cb2f,$3fff),
($ebc0,$5506,$512f,$80ab,$4000));
p1dhex: array[0..6] of THexExtW = (
($8d72,$2be3,$cb0f,$98df,$3fed),
($a853,$55fb,$6c79,$ca32,$3ff4),
($98f8,$d610,$3c35,$a235,$3ffa),
($c39e,$9c8c,$5428,$bb65,$3ffe),
($b1f2,$e0d2,$5ab5,$9098,$4001),
($efe3,$292c,$0d43,$d9e6,$4001),
($0000,$0000,$0000,$8000,$3fff));
var
m1n: array[0..7] of extended absolute m1nhex;
m1d: array[0..8] of extended absolute m1dhex;
p1n: array[0..5] of extended absolute p1nhex;
p1d: array[0..6] of extended absolute p1dhex;
begin
{Ref: Cephes [7], file ldouble\j1l.c}
{Calculate the modulus m1(x) = sign(x)*sqrt(J1(x)^2 + Y1(x)^2) and }
{the phase p1(x) = arctan(Y1(x)/J1(x)) with rational approximations}
{For x>=9: J1(x) = m1(x)*cos(p1(x)) and Y1(x) = m1(x)*sin(p1(x))}
z := sqr(1.0/x);
y := abs(x);
s := rem_2pi_sym(y);
p1 := PolEvalX(z,p1n,6)/PolEvalX(z,p1d,7)/y;
z := 1.0/y;
m1 := PolEvalX(z,m1n,8)/PolEvalX(z,m1d,9)/sqrt(y);
if x<0.0 then m1 := -m1;
{Compute p1 := rem_2pi_sym(y) - 3Pi_4 + p1 with optimized Kahan summation}
z := -3.0*Pi_4;
y := s + z;
z := (y - s) - z;
p1 := y + (p1 - z);
end;
{---------------------------------------------------------------------------}
function sfc_j1(x: extended): extended;
{-Return J1(x), the Bessel function of the 1st kind, order one}
var
y,z: extended;
const
{Squares of first three roots of J1, calculated with Maple and t_rcalc/xh}
j1h: THexExtW = ($5F8E,$4C11,$5A0C,$EAE9,$4002); {1.4681970642123893257E+1}
j2h: THexExtW = ($9093,$9521,$B303,$C4DF,$4004); {4.9218456321694603672E+1}
j3h: THexExtW = ($5EBF,$C2F1,$B86B,$CEFF,$4005); {1.0349945389513658033E+2}
var
jz1: extended absolute j1h;
jz2: extended absolute j2h;
jz3: extended absolute j3h;
const
j1nhex: array[0..8] of THexExtW = (
($d8d8,$7311,$a7d2,$97a4,$c039),
($d3c2,$f8f0,$f852,$c144,$4033),
($636c,$4d29,$9f71,$cebb,$c02c),
($038e,$bd23,$a7fa,$f49c,$4024),
($1ac8,$c825,$3c9c,$b0b6,$c01c),
($38f5,$f72b,$0a5c,$a122,$4013),
($29f3,$496b,$a54c,$b6d9,$c009),
($6dc3,$c850,$a096,$ee6b,$3ffe),
($f72f,$18cc,$50b2,$8a22,$bff3));
j1dhex: array[0..8] of THexExtW = (
($dd67,$f5b3,$0522,$ad0f,$404a),
($665d,$b178,$242e,$9af7,$4043),
($e6c0,$a725,$3d56,$88f7,$403b),
($0122,$56c0,$f2ef,$9d6e,$4032),
($b498,$fdd5,$209e,$820e,$4029),
($6041,$c9fe,$6890,$a033,$401f),
($6a17,$e162,$4e86,$9218,$4015),
($baf9,$146e,$df50,$b88a,$400a),
($0000,$0000,$0000,$8000,$3fff));
var
j1n: array[0..8] of extended absolute j1nhex;
j1d: array[0..8] of extended absolute j1dhex;
begin
{Ref: Cephes [7], file ldouble\j1l.c}
z := abs(x);
if z < 9.0 then begin
z := sqr(x);
{In the interval [0,9) a rational approximation of the form }
{J1(x) = x*(x^2 - r^2)*(x^2 - s^2)*(x^2 - t^2)*P8(x^2)/Q8(x^2)}
{is used, where r, s, t are the first three zeros of J1.}
y := x*(z - jz1)*(z - jz2)*(z - jz3);
sfc_j1 := y*PolEvalX(z,j1n,9)/PolEvalX(z,j1d,9);
end
else begin
{For x>=9 the common rational approximations to modulus}
{and phase are used J1(x) = modulus * cos(phase).}
if z >= 500.0 then begin
y := bessj_large(1,z);
if x<0.0 then sfc_j1 := -y else sfc_j1 := y;
end
else begin
bess_m1p1(x,y,z);
sfc_j1 := y*cos(z);
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_y1(x: extended): extended;
{-Return Y1(x), the Bessel function of the 2nd kind, order one; x>0}
var
y, z: extended;
const
{The first four roots of Y1, calculated with Maple and t_rcalc/xh}
y1h: THexExtW = ($1721,$FF92,$F6A6,$8C9D,$4000); {2.1971413260310170351}
y2h: THexExtW = ($73C0,$3D81,$F274,$ADBF,$4001); {5.4296810407941351328}
y3h: THexExtW = ($A148,$0B4D,$3D73,$8989,$4002); {8.5960058683311689268}
y4h: THexExtW = ($3022,$A190,$89C6,$BBFC,$4002); {11.749154830839881243}
var
y1z1: extended absolute y1h;
y1z2: extended absolute y2h;
y1z3: extended absolute y3h;
y1z4: extended absolute y4h;
const
y1nhex: array[0..6] of THexExtW = (
($3a10,$0848,$5930,$9965,$c035),
($7f8b,$4757,$75bd,$a196,$4033),
($69fd,$1242,$f62d,$de75,$c02e),
($5633,$aa6b,$79e5,$e62c,$4028),
($7607,$a687,$af0a,$d892,$c021),
($53e4,$194c,$befa,$bd19,$4019),
($5b16,$f7f8,$0d7e,$fbbd,$c00f));
y1dhex: array[0..7] of THexExtW = (
($7302,$b91b,$de7e,$c399,$4037),
($8c6a,$397e,$0963,$ad7a,$4031),
($aaf0,$342b,$d098,$9ca5,$402a),
($57e0,$1d92,$90a9,$bd99,$4022),
($0e86,$117b,$36d6,$a94a,$401a),
($298c,$29ef,$0630,$e482,$4011),
($dd1a,$3b8e,$ab73,$df28,$4008),
($0000,$0000,$0000,$8000,$3fff));
y159nh: array[0..9] of THexExtW = (
($539b,$f305,$c3d8,$97f6,$4011),
($f62f,$d968,$8c66,$8d15,$c013),
($3811,$a3da,$413f,$dc24,$c013),
($cd43,$2f50,$1118,$d972,$c013),
($a33b,$8229,$1561,$f1fc,$c00f),
($b2bf,$4296,$65af,$a3d1,$400d),
($df40,$226b,$7e37,$c0d9,$400b),
($e917,$8486,$0ebd,$e6c3,$c008),
($fdf1,$41e5,$4beb,$ac44,$4004),
($b5e5,$bb42,$f667,$ae3f,$bffe));
y159dh: array[0..10] of THexExtW = (
($a231,$6ab0,$7952,$cdb2,$4019),
($b3ad,$1c6d,$0f07,$8ba8,$c01d),
($8e0e,$e148,$5ab3,$ff44,$401e),
($a46a,$0273,$bc0f,$c358,$c01c),
($6de5,$b797,$ea1c,$e66b,$4019),
($e5e5,$4172,$8863,$b4a0,$c016),
($3c4f,$dc46,$b802,$e107,$4012),
($bed4,$3ad5,$2da1,$cc1d,$c00e),
($d0fe,$2487,$01c0,$8be3,$400a),
($1a6c,$1c93,$612a,$f742,$c004),
($0000,$0000,$0000,$8000,$3fff));
var
y159n: array[0..9] of extended absolute y159nh;
y159d: array[0..10] of extended absolute y159dh;
y1n: array[0..6] of extended absolute y1nhex;
y1d: array[0..7] of extended absolute y1dhex;
begin
{Ref: Cephes [7], file ldouble\j1l.c}
if x<=0.0 then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_y1 := NaN_x;
exit;
end;
if x < 9.0 then begin
z := sqr(x);
if z < 20.25 then begin
{In the interval [0,4.5) a rational approximation of the form}
{Y1(x) = x*P6(x)/Q7(x) + 2/Pi*(ln(x)*J1(x) - 1/x) is used.}
y := (ln(x)*sfc_j1(x) - 1.0/x)/Pi_2;
sfc_y1 := y + x*PolEvalX(z,y1n,7)/PolEvalX(z,y1d,8);
end
else begin
{In the interval [4.5,9) a rational approximation of the form}
{Y1(x) = (x - p)*(x - q)*(x - r)*(x - s)*P9(x)/Q10(x) is used}
{where p, q, r, s are first four zeros of Y1(x).}
y := (x - y1z1)*(x - y1z2)*(x - y1z3)*(x - y1z4);
sfc_y1 := y * PolEvalX(x,y159n,10)/PolEvalX(x,y159d,11);
end;
end
else begin
{For x>=9 the common rational approximations to modulus}
{and phase are used Y1(x) = modulus * sin(phase).}
if x >= 1600 then sfc_y1 := bessy_large(1,x)
else begin
bess_m1p1(x,y,z);
sfc_y1 := y*sin(z);
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_jn(n: integer; x: extended): extended;
{-Return J_n(x), the Bessel function of the 1st kind, order n; not suitable for large n or x.}
var
curr,prev,q,temp,init,xh: extended;
k: integer;
neg: boolean;
const
small = 7.143435E-1651; {~ cbrt(succx(0))}
lnsml = ln_succx0;
begin
{Based on boost_1_42_0\boost\math\special_functions\detail\bessel_jn.hpp [19]}
{Copyright 2006 Xiaogang Zhang, see 3rdparty.ama for Boost license}
init := Sqrt_MinExt;
{Flag to negate result for |n|}
neg := (n<0) and odd(n);
n := abs(n);
if n=0 then curr := sfc_j0(x)
else if n=1 then curr := sfc_j1(x)
else if abs(x) <= small then begin
if (x=0.0) or (n>2) then curr := 0.0
else curr := 0.125*sqr(x);
end
else begin
xh := 0.5*x;
if abs(x) > n then begin
{forward recurrence}
prev := sfc_j0(x);
curr := sfc_j1(x);
for k:=1 to n-1 do begin
temp := curr*k/xh - prev;
prev := curr;
curr := temp;
end;
end
else begin
{Quick check if |J_n(x)| < MinExtended from HMF[1] 9.1.63}
{solution of z*exp(sqrt(1-z^2))=1 is z = 0.39989.. }
q := abs(x/n);
if n<=100 then temp := 1e-40
else if n<1000 then temp := 1e-4
else if n<5000 then temp := 0.07
else temp := 0.3999;
if q < temp then begin
{Jn(x) <= [q*exp(sqrt(1-q^2))/(1+sqrt(1-q^2))]^n}
temp := sqrt(1.0 - q*q);
temp := ln(q/(1.0+temp)) + temp;
if temp < lnsml/n then begin
sfc_jn := 0.0;
exit;
end;
end;
{set overflow threshold for iteration}
q := 0.5*MaxExtended*q;
{backward recurrence}
CF1_j(n,x,prev,k);
prev := prev*init;
curr := init;
for k:=n downto 1 do begin
if abs(curr) > q then begin
{prevent overflow and set result to zero}
sfc_jn := 0.0;
exit;
end;
temp := curr*k/xh - prev;
prev := curr;
curr := temp;
end;
curr := (init/curr)*sfc_j0(x);
end;
end;
if neg then sfc_jn := -curr else sfc_jn := curr;
end;
{---------------------------------------------------------------------------}
function sfc_yn(n: integer; x: extended): extended;
{-Return Y_n(x), the Bessel function of the 2nd kind, order n, x>0, not suitable for large n or x}
var
yn,yn1,t: extended;
k: integer;
neg: boolean;
begin
{Flag to negate result for |n|}
neg := (n<0) and odd(n);
n := abs(n);
if x<=0.0 then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_yn := NaN_x;
exit;
end;
if n=0 then yn := sfc_y0(x)
else if n=1 then yn := sfc_y1(x)
else if (n>MAXGAMX) and (x<=2.0) then yn := NegInf_x
else begin
if x<1.0 then begin
{NIST[30] 10.7.4}
t := sfc_lnfac(n-1) - n*ln(0.5*x) - LnPi;
if t > ln_MaxExt then begin
if neg then sfc_yn := PosInf_x else sfc_yn := NegInf_x;
exit;
end;
end;
{forward recurrence}
yn1 := sfc_y0(x);
yn := sfc_y1(x);
x := 0.5*x;
for k:=1 to n-1 do begin
t := yn*k/x - yn1;
yn1:= yn;
yn := t;
end;
end;
if neg then sfc_yn := -yn else sfc_yn := yn;
end;
{---------------------------------------------------------------------------}
function bess_i0_small(x: extended): extended;
{-Return Bessel function I0(x) for abs(x)<=3, x assumed >= 0}
const
xsml = 0.65854450798271924667e-9; {sqrt(4*eps_x)}
const
nbi0 = 13;
bi0h : array[0..nbi0-1] of THexExtW = (
($4003,$A1EE,$5479,$9CE3,$BFFB), {-0.7660547252839144951081894976243285e-1}
($48B3,$5F19,$0294,$F6B3,$3FFF), {+0.1927337953993808269952408750881196e+1}
($B8D1,$AF86,$2883,$E9BE,$3FFC), {+0.2282644586920301338937029292330415e+0}
($B9F3,$936B,$1D6F,$D5CB,$3FF8), {+0.1304891466707290428079334210691888e-1}
($5C27,$B9AE,$D127,$E3C3,$3FF3), {+0.4344270900816487451378682681026107e-3}
($F200,$B849,$01B0,$9E16,$3FEE), {+0.9422657686001934663923171744118766e-5}
($CFA2,$6F56,$AA2C,$99F9,$3FE8), {+0.1434006289510691079962091878179957e-6}
($189D,$34A0,$4423,$DDCE,$3FE1), {+0.1613849069661749069915419719994611e-8}
($DA55,$222E,$86B5,$F5B3,$3FDA), {+0.1396650044535669699495092708142522e-10}
($4C24,$393C,$C78C,$D7B5,$3FD3), {+0.9579451725505445344627523171893333e-13}
($B4AE,$B291,$D6DC,$99BD,$3FCC), {+0.5333981859862502131015107744000000e-15}
($1BB6,$1CA4,$D573,$B56B,$3FC4), {+0.2458716088437470774696785919999999e-17}
($1BB2,$06F5,$B92D,$B41F,$3FBC));{+0.9535680890248770026944341333333333e-20}
var
bi0: array[0..nbi0-1] of extended absolute bi0h;
begin
{Ref: W. Fullerton [14] and [20], files dbesi0.f and dbsi0e.f}
{Hex Chebyshev values calculated with mp_arith/t_rcalc}
if x<=xsml then bess_i0_small := 1.0
else bess_i0_small := 2.75 + CSEvalX(x*x/4.5-1.0,bi0,nbi0);
end;
{---------------------------------------------------------------------------}
function sfc_i0e(x: extended): extended;
{-Return I0(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order zero}
const
xsml = 0.23283064365386962891e-9; {sqrt(0.5*eps_x)}
const
nai0 = 28;
ai0: array[0..nai0-1] of extended = (
+0.7575994494023795942729872037438e-1,
+0.7591380810823345507292978733204e-2,
+0.4153131338923750501863197491382e-3,
+0.1070076463439073073582429702170e-4,
-0.7901179979212894660750319485730e-5,
-0.7826143501438752269788989806909e-6,
+0.2783849942948870806381185389857e-6,
+0.8252472600612027191966829133198e-8,
-0.1204463945520199179054960891103e-7,
+0.1559648598506076443612287527928e-8,
+0.2292556367103316543477254802857e-9,
-0.1191622884279064603677774234478e-9,
+0.1757854916032409830218331247743e-10,
+0.1128224463218900517144411356824e-11,
-0.1146848625927298877729633876982e-11,
+0.2715592054803662872643651921606e-12,
-0.2415874666562687838442475720281e-13,
-0.6084469888255125064606099639224e-14,
+0.3145705077175477293708360267303e-14,
-0.7172212924871187717962175059176e-15,
+0.7874493403454103396083909603327e-16,
+0.1004802753009462402345244571839e-16,
-0.7566895365350534853428435888810e-17,
+0.2150380106876119887812051287845e-17,
-0.3754858341830874429151584452608e-18,
+0.2354065842226992576900757105322e-19,
+0.1114667612047928530226373355110e-19,
-0.5398891884396990378696779322709e-20);
const
nai2 = 33;
ai02: array[0..nai2-1] of extended = (
+0.5449041101410883160789609622680e-1,
+0.3369116478255694089897856629799e-2,
+0.6889758346916823984262639143011e-4,
+0.2891370520834756482966924023232e-5,
+0.2048918589469063741827605340931e-6,
+0.2266668990498178064593277431361e-7,
+0.3396232025708386345150843969523e-8,
+0.4940602388224969589104824497835e-9,
+0.1188914710784643834240845251963e-10,
-0.3149916527963241364538648629619e-10,
-0.1321581184044771311875407399267e-10,
-0.1794178531506806117779435740269e-11,
+0.7180124451383666233671064293469e-12,
+0.3852778382742142701140898017776e-12,
+0.1540086217521409826913258233397e-13,
-0.4150569347287222086626899720156e-13,
-0.9554846698828307648702144943125e-14,
+0.3811680669352622420746055355118e-14,
+0.1772560133056526383604932666758e-14,
-0.3425485619677219134619247903282e-15,
-0.2827623980516583484942055937594e-15,
+0.3461222867697461093097062508134e-16,
+0.4465621420296759999010420542843e-16,
-0.4830504485944182071255254037954e-17,
-0.7233180487874753954562272409245e-17,
+0.9921475412173698598880460939810e-18,
+0.1193650890845982085504399499242e-17,
-0.2488709837150807235720544916602e-18,
-0.1938426454160905928984697811326e-18,
+0.6444656697373443868783019493949e-19,
+0.2886051596289224326481713830734e-19,
-0.1601954907174971807061671562007e-19,
-0.3270815010592314720891935674859e-20);
begin
{Ref: W. Fullerton [14] and [20], file dbsi0e.f}
x := abs(x);
if x<=3.0 then begin
{Note that there is bug in dbsi0e.f from [20] for small x. We use the}
{Taylor series for I(0,x)*exp(-x) = 1 - x + 3/4*x^2 -5/12*x^3 + O(x^4)}
if x<=xsml then sfc_i0e := 1 - x
else sfc_i0e := exp(-x)*bess_i0_small(x);
end
else if x<=8.0 then begin
sfc_i0e := (0.375 + CSEvalX((48.0/x-11.0)/5.0, ai0, nai0))/sqrt(x);
end
else begin
sfc_i0e := (0.375 + CSEvalX(16.0/x-1.0, ai02, nai2))/sqrt(x);
end;
end;
{---------------------------------------------------------------------------}
function sfc_i0(x: extended): extended;
{-Return I0(x), the modified Bessel function of the 1st kind, order zero}
begin
x := abs(x);
if x<=3.0 then sfc_i0 := bess_i0_small(x)
else if x>ln_MaxExt then sfc_i0 := PosInf_x
else sfc_i0 := sfc_i0e(x)*exp(x);
end;
{---------------------------------------------------------------------------}
function bess_i1_small(x: extended): extended;
{-Return Bessel function I1(x) for abs(x)<=3}
var
y: extended;
const
xsml = 0.23283064365386962891e-9; {sqrt(0.5*eps_x)}
const
nbi1 = 12;
bi1: array[0..nbi1-1] of extended = (
-0.19717132610998597316138503218149e-2,
+0.40734887667546480608155393652014e+0,
+0.34838994299959455866245037783787e-1,
+0.15453945563001236038598401058489e-2,
+0.41888521098377784129458832004120e-4,
+0.76490267648362114741959703966069e-6,
+0.10042493924741178689179808037238e-7,
+0.99322077919238106481371298054863e-10,
+0.76638017918447637275200171681349e-12,
+0.47414189238167394980388091948160e-14,
+0.24041144040745181799863172032000e-16,
+0.10171505007093713649121100799999e-18);
begin
{Ref: W. Fullerton [14] and [20], files dbesi1.f and dbsi1e.f}
y := abs(x);
if y=0.0 then bess_i1_small := 0.0
else if y<=xsml then bess_i1_small := 0.5*x
else bess_i1_small := x*(0.875 + CSEvalX(x*x/4.5-1.0,bi1,nbi1));
end;
{---------------------------------------------------------------------------}
function sfc_i1e(x: extended): extended;
{-Return I1(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order one}
var
y: extended;
const
nai1 = 28;
ai1: array[0..nai1-1] of extended = (
-0.2846744181881478674100372468307e-1,
-0.1922953231443220651044448774979e-1,
-0.6115185857943788982256249917785e-3,
-0.2069971253350227708882823777979e-4,
+0.8585619145810725565536944673138e-5,
+0.1049498246711590862517453997860e-5,
-0.2918338918447902202093432326697e-6,
-0.1559378146631739000160680969077e-7,
+0.1318012367144944705525302873909e-7,
-0.1448423418183078317639134467815e-8,
-0.2908512243993142094825040993010e-9,
+0.1266388917875382387311159690403e-9,
-0.1664947772919220670624178398580e-10,
-0.1666653644609432976095937154999e-11,
+0.1242602414290768265232168472017e-11,
-0.2731549379672432397251461428633e-12,
+0.2023947881645803780700262688981e-13,
+0.7307950018116883636198698126123e-14,
-0.3332905634404674943813778617133e-14,
+0.7175346558512953743542254665670e-15,
-0.6982530324796256355850629223656e-16,
-0.1299944201562760760060446080587e-16,
+0.8120942864242798892054678342860e-17,
-0.2194016207410736898156266643783e-17,
+0.3630516170029654848279860932334e-18,
-0.1695139772439104166306866790399e-19,
-0.1288184829897907807116882538222e-19,
+0.5694428604967052780109991073109e-20);
const
nai2 = 33;
ai12: array[0..nai2-1] of extended = (
+0.2857623501828012047449845948469e-1,
-0.9761097491361468407765164457302e-2,
-0.1105889387626237162912569212775e-3,
-0.3882564808877690393456544776274e-5,
-0.2512236237870208925294520022121e-6,
-0.2631468846889519506837052365232e-7,
-0.3835380385964237022045006787968e-8,
-0.5589743462196583806868112522229e-9,
-0.1897495812350541234498925033238e-10,
+0.3252603583015488238555080679949e-10,
+0.1412580743661378133163366332846e-10,
+0.2035628544147089507224526136840e-11,
-0.7198551776245908512092589890446e-12,
-0.4083551111092197318228499639691e-12,
-0.2101541842772664313019845727462e-13,
+0.4272440016711951354297788336997e-13,
+0.1042027698412880276417414499948e-13,
-0.3814403072437007804767072535396e-14,
-0.1880354775510782448512734533963e-14,
+0.3308202310920928282731903352405e-15,
+0.2962628997645950139068546542052e-15,
-0.3209525921993423958778373532887e-16,
-0.4650305368489358325571282818979e-16,
+0.4414348323071707949946113759641e-17,
+0.7517296310842104805425458080295e-17,
-0.9314178867326883375684847845157e-18,
-0.1242193275194890956116784488697e-17,
+0.2414276719454848469005153902176e-18,
+0.2026944384053285178971922860692e-18,
-0.6394267188269097787043919886811e-19,
-0.3049812452373095896084884503571e-19,
+0.1612841851651480225134622307691e-19,
+0.3560913964309925054510270904620e-20);
begin
{Ref: W. Fullerton [14] and [20], file dbsi1e.f}
y := abs(x);
if y<=3.0 then sfc_i1e := exp(-y)*bess_i1_small(x)
else begin
if y<=8.0 then begin
y := (0.375 + CSEvalX((48.0/y-11.0)/5.0, ai1, nai1))/sqrt(y)
end
else begin
y := (0.375 + CSEvalX(16.0/y-1.0, ai12, nai2))/sqrt(y);
end;
if x>0 then sfc_i1e := y else sfc_i1e := -y;
end;
end;
{---------------------------------------------------------------------------}
function sfc_i1(x: extended): extended;
{-Return I1(x), the modified Bessel function of the 1st kind, order one}
var
y: extended;
begin
y := abs(x);
if y<=3.0 then sfc_i1 := bess_i1_small(x)
else if x>ln_MaxExt then sfc_i1 := PosInf_x
else sfc_i1 := sfc_i1e(x)*exp(y);
end;
{---------------------------------------------------------------------------}
function bess_k0_small(x: extended): extended;
{-Return Bessel function K0(x) for 0 < x <= 2}
var
y: extended;
const
xsml = 0.46566128730773925781e-9; {sqrt(2*eps_x)}
const
nbk0 = 12;
bk0: array[0..nbk0-1] of extended = (
-0.353273932339027687201140060063153e-1,
+0.344289899924628486886344927529213e+0,
+0.359799365153615016265721303687231e-1,
+0.126461541144692592338479508673447e-2,
+0.228621210311945178608269830297585e-4,
+0.253479107902614945730790013428354e-6,
+0.190451637722020885897214059381366e-8,
+0.103496952576336245851008317853089e-10,
+0.425981614279108257652445327170133e-13,
+0.137446543588075089694238325440000e-15,
+0.357089652850837359099688597333333e-18,
+0.763164366011643737667498666666666e-21);
begin
{Ref: W. Fullerton [14] and [20], files dbesk0.f and dbsk0e.f}
if x>xsml then y := x*x
else begin
if x=0.0 then begin
bess_k0_small := PosInf_x;
exit;
end
else y := 0.0;
end;
bess_k0_small := -ln(0.5*x)*bess_i0_small(x) - 0.25 + CSEvalX(0.5*y-1.0,bk0,nbk0);
end;
{---------------------------------------------------------------------------}
function sfc_k0e(x: extended): extended;
{-Return K0(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order zero, x>0}
const
nak0 = 22;
ak0: array[0..nak0-1] of extended = (
-0.7643947903327941424082978270088e-1,
-0.2235652605699819052023095550791e-1,
+0.7734181154693858235300618174047e-3,
-0.4281006688886099464452146435416e-4,
+0.3081700173862974743650014826660e-5,
-0.2639367222009664974067448892723e-6,
+0.2563713036403469206294088265742e-7,
-0.2742705549900201263857211915244e-8,
+0.3169429658097499592080832873403e-9,
-0.3902353286962184141601065717962e-10,
+0.5068040698188575402050092127286e-11,
-0.6889574741007870679541713557984e-12,
+0.9744978497825917691388201336831e-13,
-0.1427332841884548505389855340122e-13,
+0.2156412571021463039558062976527e-14,
-0.3349654255149562772188782058530e-15,
+0.5335260216952911692145280392601e-16,
-0.8693669980890753807639622378837e-17,
+0.1446404347862212227887763442346e-17,
-0.2452889825500129682404678751573e-18,
+0.4233754526232171572821706342400e-19,
-0.7427946526454464195695341294933e-20);
const
nak2 = 18;
ak02: array[0..nak2-1] of extended = (
-0.1201869826307592239839346212452e-1,
-0.9174852691025695310652561075713e-2,
+0.1444550931775005821048843878057e-3,
-0.4013614175435709728671021077879e-5,
+0.1567831810852310672590348990333e-6,
-0.7770110438521737710315799754460e-8,
+0.4611182576179717882533130529586e-9,
-0.3158592997860565770526665803309e-10,
+0.2435018039365041127835887814329e-11,
-0.2074331387398347897709853373506e-12,
+0.1925787280589917084742736504693e-13,
-0.1927554805838956103600347182218e-14,
+0.2062198029197818278285237869644e-15,
-0.2341685117579242402603640195071e-16,
+0.2805902810643042246815178828458e-17,
-0.3530507631161807945815482463573e-18,
+0.4645295422935108267424216337066e-19,
-0.6368625941344266473922053461333e-20);
begin
{Ref: W. Fullerton [14] and [20], file dbsk0e.f}
if x<=2.0 then sfc_k0e := exp(x)*bess_k0_small(x)
else if x<=8.0 then begin
sfc_k0e := (1.25 + CSEvalX((16.0/x-5.0)/THREE, ak0, nak0))/sqrt(x);
end
else begin
sfc_k0e := (1.25 + CSEvalX(16.0/x-1.0, ak02, nak2))/sqrt(x);
end;
end;
{---------------------------------------------------------------------------}
function sfc_k0(x: extended): extended;
{-Return K0(x), the modified Bessel function of the 2nd kind, order zero, x>0}
begin
if x<=2.0 then sfc_k0 := bess_k0_small(x)
else sfc_k0 := sfc_k0e(x)*exp(-x);
end;
{---------------------------------------------------------------------------}
function bess_k1_small(x: extended): extended;
{-Return Bessel function K1(x) for 0 < x <= 2}
var
y: extended;
const
xsml = 0.46566128730773925781e-9; {sqrt(2*eps_x)}
const
nbk1 = 12;
bk1: array[0..nbk1-1] of extended = (
+0.25300227338947770532531120868533e-1,
-0.35315596077654487566723831691801e+0,
-0.12261118082265714823479067930042e+0,
-0.69757238596398643501812920296083e-2,
-0.17302889575130520630176507368979e-3,
-0.24334061415659682349600735030164e-5,
-0.22133876307347258558315252545126e-7,
-0.14114883926335277610958330212608e-9,
-0.66669016941993290060853751264373e-12,
-0.24274498505193659339263196864853e-14,
-0.70238634793862875971783797120000e-17,
-0.16543275155100994675491029333333e-19);
begin
{Ref: W. Fullerton [14] and [20], files dbesk1.f and dbsk1e.f}
if x>xsml then y := x*x
else begin
if x=0.0 then begin
bess_k1_small := PosInf_x;
exit;
end
else y := 0.0;
end;
bess_k1_small := ln(0.5*x)*bess_i1_small(x) + (0.75 + CSEvalX(0.5*y-1.0,bk1,nbk1))/x;
end;
{---------------------------------------------------------------------------}
function sfc_k1e(x: extended): extended;
{-Return K1(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order one, x>0}
const
nak1 = 22;
ak1: array[0..nak1-1] of extended = (
+0.27443134069738829695257666227266e+0,
+0.75719899531993678170892378149290e-1,
-0.14410515564754061229853116175625e-2,
+0.66501169551257479394251385477036e-4,
-0.43699847095201407660580845089167e-5,
+0.35402774997630526799417139008534e-6,
-0.33111637792932920208982688245704e-7,
+0.34459775819010534532311499770992e-8,
-0.38989323474754271048981937492758e-9,
+0.47208197504658356400947449339005e-10,
-0.60478356628753562345373591562890e-11,
+0.81284948748658747888193837985663e-12,
-0.11386945747147891428923915951042e-12,
+0.16540358408462282325972948205090e-13,
-0.24809025677068848221516010440533e-14,
+0.38292378907024096948429227299157e-15,
-0.60647341040012418187768210377386e-16,
+0.98324256232648616038194004650666e-17,
-0.16284168738284380035666620115626e-17,
+0.27501536496752623718284120337066e-18,
-0.47289666463953250924281069568000e-19,
+0.82681500028109932722392050346666e-20);
const
nak2 = 18;
ak12: array[0..nak2-1] of extended = (
+0.6379308343739001036600488534102e-1,
+0.2832887813049720935835030284708e-1,
-0.2475370673905250345414545566732e-3,
+0.5771972451607248820470976625763e-5,
-0.2068939219536548302745533196552e-6,
+0.9739983441381804180309213097887e-8,
-0.5585336140380624984688895511129e-9,
+0.3732996634046185240221212854731e-10,
-0.2825051961023225445135065754928e-11,
+0.2372019002484144173643496955486e-12,
-0.2176677387991753979268301667938e-13,
+0.2157914161616032453939562689706e-14,
-0.2290196930718269275991551338154e-15,
+0.2582885729823274961919939565226e-16,
-0.3076752641268463187621098173440e-17,
+0.3851487721280491597094896844799e-18,
-0.5044794897641528977117282508800e-19,
+0.6888673850418544237018292223999e-20);
begin
{Ref: W. Fullerton [14] and [20], file dbsk1e.f}
if x<=2.0 then sfc_k1e := exp(x)*bess_k1_small(x)
else if x<=8.0 then begin
sfc_k1e := (1.25 + CSEvalX((16.0/x-5.0)/THREE, ak1, nak1))/sqrt(x);
end
else begin
sfc_k1e := (1.25 + CSEvalX(16.0/x-1.0, ak12, nak2))/sqrt(x);
end;
end;
{---------------------------------------------------------------------------}
function sfc_k1(x: extended): extended;
{-Return K1(x), the modified Bessel function of the 2nd kind, order one, x>0}
begin
if x<=2.0 then sfc_k1 := bess_k1_small(x)
else sfc_k1 := sfc_k1e(x)*exp(-x);
end;
{---------------------------------------------------------------------------}
function sfc_in(n: integer; x: extended): extended;
{-Return I_n(x), the modified Bessel function of the 1st kind, order n}
var
curr,prev,temp,init,y: extended;
k: integer;
const
NMax = 256; {double: 160}
XMax = 1024.0; {double: 512}
begin
{HMF[1], 9.6.6: I(-n,x) = I(n,x)}
n := abs(n);
if n=0 then sfc_in := sfc_i0(x)
else if n=1 then sfc_in := sfc_i1(x)
else if x=0.0 then sfc_in := 0.0
else begin
y := abs(x);
{If n or x are not small then use real order function}
if (n>NMax) or (y>XMax) then sfc_in := sfc_iv(n,x)
else begin
{Simplified calculation for I_n only with existing functions}
if y <= 2.0 then begin
curr := IJ_series(n,y,false);
end
else begin
{I_(n+1)(y)/I_n(y) using continued fraction and recurse backwards}
CF1_I(n,y,temp);
y := 0.5*y;
init := Sqrt_MinExt;
curr := init;
prev := init*temp;
for k:=n downto 1 do begin
temp := curr*k/y + prev;
prev := curr;
curr := temp;
end;
curr := (init/curr)*sfc_i0(x);
end;
{Adjust sign}
if (x<0.0) and odd(n) then curr := -curr;
sfc_in := curr;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_kn(n: integer; x: extended): extended;
{-Return K_n(x), the modified Bessel function of the 2nd kind, order n, x>0, not suitable for large n}
var
kn,knm1,knm2: extended;
k: integer;
begin
{HMF[1], 9.6.6: K(-n,x) = K(n,x)}
n := abs(n);
{Range error for x<=0 is generated in k0 or k1}
if n=0 then kn := sfc_k0(x)
else if n=1 then kn := sfc_k1(x)
else begin
{$ifdef Delphi}
{avoid false warning "Variable 'kn' might not have been initialized"}
kn := 0.0;
{$endif}
{forward recurrence, K(n+1,x) = 2n/x*K(n,x) + K(n-1,x)}
knm2 := sfc_k0(x);
knm1 := sfc_k1(x);
x := 0.5*x;
for k:=1 to n-1 do begin
kn := knm1*k/x + knm2;
knm2 := knm1;
knm1 := kn;
end;
end;
sfc_kn := kn;
end;
{---------------------------------------------------------------------------}
{-------------------- Bessel functions of real order -----------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
procedure temme_y(v,x: extended; var Y,Y1: extended);
{-Calculate Y(v, x) and Y(v+1, x) by Temme's method for small |x|}
var
k,g,h,p,q,f,c,d,s,s1,tol,a,e: extended;
g1,g2,gp,gm,v2: extended;
const
MAXIT = 30000;
begin
{$ifdef debug}
if (abs(v) > 0.5) or (abs(x) > 2) then begin
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
end;
{$endif}
{N.M.Temme [51], On the Numerical Evaluation of the Ordinary}
{Bessel Function of the Second Kind, Section 2.}
gp := sfc_gamma1pm1(v);
gm := sfc_gamma1pm1(-v);
a := ln(0.5*x);
s := -a*v;
if abs(v) < eps_x then begin
e := 0.5*v*sqr(Pi);
d := 1.0/Pi;
end
else begin
e := 2.0*sqr(sinpi(0.5*v))/v;
d := v/sinpi(v);
end;
if v=0.0 then g1 := -EulerGamma
else g1 := 0.5*(gp-gm)/((1.0+gp)*(1.0+gm)*v);
g2 := 0.5*(2.0+gp+gm)/((1.0+gp)*(1.0+gm));
f := 2.0*(g1*cosh(s) - g2*a*sinhc(s))*d;
c := power(0.5*x, v);
p := d/(c*(1.0 + gm));
q := d*c/(1.0 + gp);
g := f + e*q;
c := 1.0;
s := c*g;
s1:= c*p;
v2 := v*v;
d := -0.25*x*x;
{series summation}
tol := 0.5*eps_x;
{use extended k because otherwise k*k may overflow}
k := 1.0;
while k <= MAXIT do begin
c := c*d/k;
f := (k*f + p + q) / (k*k - v2);
p := p/(k - v);
q := q/(k + v);
g := f + e*q;
h := p - k*g;
s := s + c*g;
s1:= s1 + c*h;
if abs(c*g) < abs(s)*tol then begin
Y := -s;
Y1 := -2.0*s1/x;
exit;
end;
k := k + 1.0;
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
Y := -s;
Y1 := -2.0*s1/x;
end;
{---------------------------------------------------------------------------}
procedure CF2_jy(v,x: extended; var p,q: extended);
{-Return the continued fraction p + i*q = (J' + iY') / (J + iY)}
var
a,br,bi,cr,ci,dr,di,er,ei,fr,fi,t: extended;
i: integer;
const
MAXIT = 30000;
begin
{Ref: Numerical Recipes [13], ch. 6.7, p.244, function bessjy}
{Evaluate the continued fraction p + iq = (J' + iY') / (J + iY)}
{NR [13] (6.7.3) using the (complex) modified Lentz's method.}
{$ifdef debug}
if abs(x) < 1.0 then begin
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
end;
{$endif}
t := 1.0/x;
a := 0.25-v*v;
fr := -0.5*t;
fi := 1.0;
br := 2.0*x;
bi := 2.0;
t := a*t/(fr*fr+fi*fi);
cr := br+t*fi;
ci := bi+t*fr;
t := br*br+bi*bi;
dr := +br/t;
di := -bi/t;
er := cr*dr-ci*di;
ei := cr*di+ci*dr;
t := fr*er-fi*ei;
fi := fr*ei+fi*er;
fr := t;
for i:=1 to MAXIT do begin
a := a + 2.0*i;
bi := bi + 2.0;
dr := a*dr+br;
di := a*di+bi;
if abs(dr)+abs(di) = 0.0 then dr := Sqrt_MinExt;
t := a/(cr*cr+ci*ci);
cr := br+t*cr;
ci := bi-t*ci;
if abs(cr)+abs(ci) = 0.0 then cr := Sqrt_MinExt;
t := dr*dr+di*di;
dr := +dr/t;
di := -di/t;
er := cr*dr-ci*di;
ei := cr*di+ci*dr;
t := fr*er-fi*ei;
fi := fr*ei+fi*er;
fr := t;
if abs(er-1.0)+abs(ei) < 8*eps_x then begin
p := fr;
q := fi;
exit;
end;
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
p := fr;
q := fi;
end;
{---------------------------------------------------------------------------}
function Yv_series(v,x: extended): extended;
{-Series for Yv for 'small' x < 1; frac(v)<>0}
var
h,k,v1,v2,t1,t2,xx,Yv: extended;
const
hsmall: THexExtW = ($4153,$E4E4,$9836,$0A2F,$0000); {2.675476672E-4933 = ~ 1/(MaxExtended*Pi)}
begin
{Use Yv(x) = ( Jv(v,x)cos(vx) - Jv(-v,x) )/sin(vx) }
{and Gamma reflection to sum the two series for Jv }
if v<MAXGAMX then h := power(0.5*x, v)/sfc_gamma(v)
else h := exp(v*ln(0.5*x) - sfc_lngamma(v));
if h <= extended(hsmall) then begin
{1.0/(h*Pi) will overflow}
Yv_series := NegInf_x;
exit;
end;
sincosPi(v, v1, v2);
t2 := 1.0/(h*Pi);
t1 := h*(v2/(v*v1));
Yv := t1-t2;
xx := 0.25*x*x;
v2 := v;
v1 := v;
k := 0.0;
repeat
k := k + 1.0;
v1 := v1 + 1.0;
v2 := v2 - 1.0;
t1 := -t1*xx/(k*v1);
t2 := t2*xx/(k*v2);
h := t1 - t2;
Yv := Yv + h;
until (abs(h)<eps_x*abs(Yv));
Yv_series := Yv;
end;
const
BT_J = 1; BT_Y = 2;
{---------------------------------------------------------------------------}
procedure bessel_jy(v,x: extended; BT: byte; var Jv,Yv: extended);
{-Return J_v(x) and/or Y_v(x) depending on BT, x>0, |v| < MaxLongint, INF if overflow}
var
n,k: longint;
u, Ju, Yv1, Yu, Yu1, fv, fu: extended;
w, p, q, g, curr, prev, next, init, t, x2: extended;
reflect: boolean;
s: integer;
const
lnepsh = -44.3614195558364998; {ln(0.5*eps_x)}
{--------------------------------------------}
function rec_overflow(a,b: extended): boolean;
{-Test if a*b overflows, if yes set Yv and Jv = PosInf_x}
begin
if (abs(a) > 1.0) and (abs(b) >= MaxExtended/abs(a)) then begin
rec_overflow := true;
Jv := PosInf_x;
Yv := PosInf_x;
end
else rec_overflow := false;
end;
begin
{Ref: Boost [19] file bessel_jy.hpp, function bessel_jy}
{and NR [13], Ch.6.7, section Ordinary Bessel Functions}
{For x < 0 the functions Jv and Yv are in general complex; and Yv}
{is singular for x=0. |v| < MaxLongint is assumed, so we can work}
{with longint in the recurrence iterative, but these routines are}
{are not suitable for large v values anyway.}
reflect := v < 0.0;
if reflect then begin
v := -v;
BT := BT_J + BT_Y; {J and Y needed for reflection formula}
end;
x2 := 0.5*x;
n := round(v);
u := v-n;
w := 2.0/(Pi*x); {Wronskian}
if x<=2.0 then begin
if v>MAXGAMX then begin
Yv := PosInf_x;
if reflect then Jv := PosInf_x else Jv := 0.0;
exit;
end
else begin
{Check very 'small' x and v case with (near) overflow for Yv}
if (x<1.0) and (u<>0.0) and (lnepsh > v*ln(0.25*sqr(x)/v)) then begin
if BT and BT_J <> 0 then Jv := IJ_series(v, x, true);
if BT and BT_Y <> 0 then Yv := Yv_series(v, x);
end
else begin
temme_y(u, x, Yu,Yu1);
if n=0 then begin
Yv := Yu;
Yv1 := Yu1;
end
else begin
prev := Yu;
curr := Yu1;
{skip last next calculation if J is not needed: it}
{overflows in some cases like bessel_yv(1755.45,2)}
{bessel_jv(1755.45,2) will produce an overflow! }
for k:=1 to n-1 do begin
{forward recurrence for Y}
t := (u+k)/x2;
if rec_overflow(t,curr) then exit;
next := t*curr - prev;
prev := curr;
curr := next;
end;
Yv := curr;
if BT and BT_J = 0 then Yv1 := 0.0 {keep some compilers quiet!}
else Yv1 := ((u+n)/x2)*curr - prev;
end;
if BT and BT_J <> 0 then begin
CF1_j(v, x, fv, s);
Jv := w/(Yv*fv - Yv1); {Wronskian relation}
end;
end;
end;
end
else begin
{calculate the lower limit t=t(v) for asymptotic range}
if BT=BT_Y then t:= 1552
else begin
t := maxx(3.0, v*v)*121.0;
if BT and BT_Y <> 0 then t := maxx(t,1552);
end;
if x>t then begin
{Use asymptotic expansion of Hankel function H1v(x)}
if BT and BT_J <> 0 then Jv := bessj_large(v, x);
if BT and BT_Y <> 0 then begin
Yu := bessy_large(u, x);
Yu1 := bessy_large(u + 1, x);
end;
end
else begin
CF1_j(v, x, fv, s);
{tiny initial value to prevent overflow}
init := Sqrt_MinExt;
curr := s*init;
prev := fv*curr;
for k:=n downto 1 do begin
{backward recurrence for J}
t := (u+k)/x2;
if rec_overflow(t,curr) then exit;
next := t*curr - prev;
prev := curr;
curr := next;
end;
CF2_jy(u, x, p, q);
fu := prev/curr;
t := u/x - fu; {t = J'/J}
g := (p-t)/q;
Ju := sqrt(w/(q + g*(p-t)));
if curr<0.0 then Ju := -Ju;
Jv := s*Ju*(init/curr); {normalization}
Yu := g*Ju;
Yu1:= Yu*(u/x - p - q/g);
end;
if BT and BT_Y <> 0 then begin
prev := Yu;
curr := Yu1;
if n=0 then Yv := prev
else begin
for k:=1 to n-1 do begin
{forward recurrence for Y}
t := (u+k)/x2;
if rec_overflow(t,curr) then exit;
next := t*curr - prev;
prev := curr;
curr := next;
end;
Yv := curr;
end;
end;
end;
if reflect then begin
{For negative v use reflection formula NR [13], 6.7.19}
{J(-v,x) = cos(Pi*v)*J(v,x) - sin(Pi*v)*Y(v,x)}
{Y(-v,x) = sin(Pi*v)*J(v,x) + cos(Pi*v)*Y(v,x)}
sincosPi(v,p,q);
t := q*Jv - p*Yv;
Yv := p*Jv + q*Yv;
Jv := t;
end;
end;
{---------------------------------------------------------------------------}
procedure sfc_bess_jyv(v,x: extended; var Jv,Yv: extended);
{-Return J_v(x) and Y_v(x), no checks, x>0, |v| < MaxLongint}
begin
bessel_jy(v,x, BT_J + BT_Y, jv,yv);
end;
{---------------------------------------------------------------------------}
function sfc_jv(v, x: extended): extended;
{-Return J_v(x), the Bessel function of the 1st kind, order v; not suitable for large v.}
var
r,n: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) then begin
sfc_jv := NaN_x;
exit;
end;
n := int(v);
if x<0.0 then begin
if n=v then begin
r := sfc_jv(v, -x);
if frac(0.5*v)<>0 then r := -r;
sfc_jv := r;
end
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_jv := NaN_x;
end;
end
else if x=0.0 then begin
if v=0.0 then sfc_jv := 1.0
else if v>0.0 then sfc_jv := 0.0
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_jv := NaN_x;
end;
end
else begin
{here x > 0}
if n=v then begin
{integer order}
if abs(n)<200.0 then begin
if x > maxx(3.0, v*v)*121.0 then begin
r := bessj_large(abs(v),x);
if frac(0.5*v)<0.0 then r := -r;
sfc_jv := r;
end
else sfc_jv := sfc_jn(round(n),x);
exit;
end;
end;
{Here v no integer or |v| > 200}
if ((v >= 0.0) and (v<MAXGAMX-1)) and ((x < 1.0) or (v > 0.25*x*x)) then begin
sfc_jv := IJ_series(v, x, true);
end
else begin
bessel_jy(v,x,BT_J,r,n);
sfc_jv := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_yv(v, x: extended): extended;
{-Return Y_v(x), the Bessel function of the 2nd kind, order v; x > 0; not suitable for large v.}
var
r,n: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) or (x<=0.0) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_yv := NaN_x;
exit;
end;
r := abs(v);
if r=0.5 then begin
r := sqrt(Pi_2*x);
if v<0.0 then sfc_yv := sin(x)/r
else sfc_yv := -cos(x)/r;
end
else if frac(v) = -0.5 then begin
{Reflection would be used but cos(Pi*v)=0: Y(v,x) = sin(Pi*v)*J(-v,x)}
n := sfc_jv(-v,x);
if frac(0.5*(r-0.5))=0.0 then sfc_yv := n else sfc_yv := -n;
end
else begin
n := int(v);
if n=v then begin
{integer order}
if (x>1552.0) and (x>5.0*abs(v)) then begin
r := bessy_large(abs(v),x);
if frac(0.5*v)<0.0 then r := -r;
sfc_yv := r;
end
else if abs(n)<2000 then begin
sfc_yv := sfc_yn(round(n),x);
end
else begin
{Call general routine but avoid Jv calculation for v<0}
bessel_jy(abs(v),x,BT_Y,n,r);
if frac(0.5*v)<0.0 then r := -r;
sfc_yv := r;
end;
exit;
end
else begin
bessel_jy(v,x,BT_Y,n,r);
sfc_yv := r;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure temme_k(v,x: extended; var K0,K1: extended);
{-Calculate K(v, x) and K(v+1, x) by Temme's method for small |x|}
var
k,h,p,q,f,c,d,s,s1,tol,a: extended;
g1,g2,gp,gm: extended;
const
MAXIT = 30000;
begin
{$ifdef debug}
if (abs(v) > 0.5) or (abs(x) > 2.0) then begin
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
end;
{$endif}
{N.M. Temme [52], On the numerical evaluation of the }
{modified Bessel function of the third kind. See also}
{Boost [19], file bessel_ik.hpp / function temme_ik }
gp := sfc_gamma1pm1(v);
gm := sfc_gamma1pm1(-v);
a := ln(0.5*x);
s := -a*v;
h := exp(a*v);
if abs(v) < eps_x then begin
c := 1.0;
g1 := -EulerGamma;
end
else begin
c := sinPi(v)/(v*Pi);
g1 := (0.5*c/v)*(gp-gm);
end;
g2 := 0.5*c*(2.0+gp+gm);
{initial values}
p := 0.5*(1.0+gp)/h;
q := 0.5*(1.0+gm)*h;
f := (g1*cosh(s) - a*g2*sinhc(s))/c;
h := p;
c := 1.0;
s := c*f;
s1:= c*h;
a := v*v;
d := 0.25*x*x;
{series summation}
tol := 0.5*eps_x;
k := 1.0;
while k <= MAXIT do begin
f := (k*f + p + q) / (k*k - a);
p := p/(k - v);
q := q/(k + v);
h := p - k*f;
c := c*d/k;
s := s + c*f;
s1:= s1 + c*h;
if abs(c*f) < abs(s)*tol then begin
K0 := s;
K1 := 2.0*s1/x;
exit;
end;
k := k + 1.0;
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
K0 := s;
K1 := 2.0*s1/x;
end;
{---------------------------------------------------------------------------}
procedure CF2_K(v,x: extended; escale: boolean; var K0,K1: extended);
{-Compute K(v,x) and K(v+1,x) via continued fraction, |v| <= 0.5, |x| > 1}
{ If escale=true the values are multiplied by exp(x)}
var
a,a1,b,c,d,dh,ds,h,q,q1,q2,s,t: extended;
k: integer;
const
MAXIT = 30000;
label
done;
begin
{Ref: Numerical Recipes [13], Ch. 6.7, section Modified Bessel Functions}
{and p.249, function bessik. It is based on I.J. Thompson, A.R. Barnett,}
{1987, Computer Physics Communications, vol. 47, pp. 245-257. }
{$ifdef debug}
if (abs(v) > 0.5) or (abs(x) <= 1.0) then begin
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
end;
{$endif}
b := 2.0*(1.0+x);
d := 1.0/b;
h := d;
dh := d;
q1 := 0.0;
q2 := 1.0;
a := v*v - 0.25;
a1 := -a;
q := a1;
c := a1;
s := 1.0+q*dh;
for k:=2 to MAXIT do begin
a := a - 2*(k-1);
c := -a*c/k;
t := (q1-b*q2)/a;
q1 := q2;
q2 := t;
q := q + c*t;
b := b + 2.0;
d := 1.0/(b+a*d);
dh := (b*d-1.0)*dh;
h := h + dh;
ds := q*dh;
s := s + ds;
if abs(ds) < abs(s)*eps_x then goto done
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
done:
K0 := sqrt(Pi_2/x)/s;
if not escale then K0 := K0*exp(-x);
K1 := K0*(v+x+0.5-a1*h)/x;
end;
{---------------------------------------------------------------------------}
function bess_i_large(v,x: extended; var Ivs: extended): boolean;
{-Compute I_v(x) for large x >= 100, sqrt(x) >= 2v. Return true}
{ if 'convergence' within 50 iterations, Ivs = I_v(x)*exp(-x)*sqrt(2Pix)}
var
s,t,u,w: extended;
k: integer;
begin
{Hankel expansion of Iv, NIST[30], 10.40.1 and 10.17.1}
u := 4.0*sqr(v);
w := 8.0*x;
{Typical values: w >= 800, u/w < 1/8}
t := 1.0;
s := 1.0;
bess_i_large := false;
for k:=1 to 50 do begin
t := t*(sqr(2*k-1)-u)/k/w;
s := s + t;
if abs(t)<eps_x then begin
bess_i_large := true;
Ivs := s;
exit;
end;
end;
Ivs := s;
end;
{---------------------------------------------------------------------------}
procedure bessel_ik(v,x: extended; CalcI, escale: boolean; var Iv,Kv: extended);
{-Return I_v(x) and/or K_v(x) depending on CalcI, x>0, |v| < MaxLongint}
{ If escale=true the values are exponentially scaled.}
var
n,k: longint;
u, Kv1, Ku, Ku1, fv: extended;
w, curr, prev, next, t, x2: extended;
reflect,OK,kzero: boolean;
begin
{Ref: Boost [19] file bessel_ik.hpp, function bessel_ik}
{and NR [13], Ch.6.7, section Modified Bessel Functions}
reflect := v < 0.0;
v := abs(v);
x2 := 0.5*x;
n := round(v);
u := v-n;
if x <= 2.0 then begin
temme_k(u, x, Ku, Ku1);
if escale then begin
fv := exp(x);
Ku := Ku*fv;
Ku1:= Ku1*fv;
end;
end
else CF2_K(u, x, escale, Ku, Ku1);
kzero := (abs(Ku1)+abs(Ku))=0.0;
if not kzero then begin
prev := Ku;
curr := Ku1;
for k:=1 to n do begin
{forward recurrence for K}
t := (u+k)/x2;
if (t > 1.0) and (curr >= MaxExtended/t) then begin
Kv := PosInf_x;
if CalcI then begin
if Reflect then Iv := PosInf_x else Iv := 0.0;
end;
exit;
end;
next := t*curr + prev;
prev := curr;
curr := next;
end;
Kv := prev;
Kv1 := curr;
kzero := (abs(Kv1)+abs(Kv))=0.0;
end
else begin
Kv := 0.0;
Kv1 := 0.0;
end;
if CalcI then begin
if (x >= 100.0) and (2.0*v <= sqrt(x)) then begin
{Asymptotic expansion HMF[1], 9.7.1 or NIST[30], 10.40.4}
OK := bess_i_large(v,x,t);
if not escale then begin
{Even if no convergence the result is used for ovrflow check}
if (t <= 0.0) or (x+ln(t)-0.5*ln(TwoPi*x) >= ln_MaxExt) then begin
Iv := PosInf_x;
exit;
end;
end;
if OK then begin
if escale then Iv := t/sqrt(TwoPi*x)
else begin
u := exp(0.5*x);
Iv := u*(u*(t/sqrt(TwoPi*x)));
end;
end;
end
else begin
if kzero then begin
Iv := PosInf_x;
exit;
end;
CF1_I(v, x, fv);
w := 1.0/x;
Iv := w/(Kv*fv + Kv1); {Wronskian relation}
end;
if reflect then begin
{Kv contribution to reflection}
t := sinPi(v)*Kv/Pi_2;
{Note: Kv is scaled with exp(|x|), so we have to multiply with exp(-2|x|)}
if escale then t := t*exp(-2.0*abs(x));
Iv := Iv + t;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_iv(v, x: extended): extended;
{-Return I_v(x), the modified Bessel function of the 1st kind, order v.}
var
r,t: extended;
const
IvMaxXH: THexExtW = ($7D70,$8F6F,$7209,$B188,$400C); {+1.1362111364594631013E+4}
begin
if IsNaNorInf(x) or IsNaNorInf(v) then begin
sfc_iv := NaN_x;
exit;
end;
if x<0.0 then begin
{if v is not an integer I(v, x) is complex}
if frac(v)=0.0 then begin
r := sfc_iv(v,-x);
if frac(0.5*v)<>0 then r := -r;
sfc_iv := r;
end
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_iv := NaN_x;
end;
end
else if abs(v)=0.5 then begin
{NIST[30] 10.39.1: I(0.5,x)=sinh(x)/R, I(-0.5,x)=cosh(x)/R, R=sqrt(Pi*x/2)}
if x >= Ln_MaxExt then begin
if x >= extended(IvMaxXH) then sfc_iv := PosInf_x
else begin
{Avoid overflow for x in range 11356.52 .. 11362.11}
r := exp(0.5*x);
sfc_iv := r*(r/sqrt(TwoPi*x));
end;
end
else begin
r := sqrt(Pi_2*x);
if v<0.0 then sfc_iv := cosh(x)/r
else sfc_iv := sinh(x)/r;
end;
end
else if x=0.0 then begin
if v=0.0 then sfc_iv := 1.0
else sfc_iv := 0.0;
end
else begin
{x>0}
if v=0.0 then sfc_iv := sfc_i0(x)
else if abs(v)=1.0 then sfc_iv := sfc_i1(x)
else if x >= extended(IvMaxXH) then sfc_iv := PosInf_x
else begin
bessel_ik(v,x,true,false,r,t);
sfc_iv := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_kv(v, x: extended): extended;
{-Return K_v(x), the modified Bessel function of the 2nd kind, order v, x>0}
var
r,t: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) then begin
sfc_kv := NaN_x;
exit;
end;
if (frac(v)=0.0) and (v<MaxInt) then sfc_kv := sfc_kn(round(v),x)
else if x<=0.0 then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_kv := NaN_x;
end
else begin
if abs(v)=0.5 then begin
{NIST[30] 10.39.2: K(0.5,x) = K(-0.5,x) = exp(-x)*sqrt(Pi/2/x)}
sfc_kv := exp(-x)*sqrt(Pi_2/x);
end
else begin
bessel_ik(v, x, false, false, t, r);
sfc_kv := r;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure sfc_bess_kv2(v,x: extended; var Kv, Kv1: extended);
{-Return K(v,x) and K(v+1,x), no checks, x>0, |v| < MaxLongint}
var
n,k: longint;
u, Ku, Ku1: extended;
curr, prev, next, t, x2: extended;
begin
{Ref: Boost [19] file bessel_ik.hpp, function bessel_ik}
{and NR [13], Ch.6.7, section Modified Bessel Functions}
u := v;
if v < -0.5 then u := abs(u) - 1.0;
x2 := 0.5*x;
n := round(u);
u := u-n;
if x <= 2.0 then temme_k(u, x, Ku, Ku1)
else CF2_K(u, x, false, Ku, Ku1);
prev := Ku;
curr := Ku1;
for k:=1 to n do begin
{forward recurrence for K}
t := (u+k)/x2;
if (t > 1.0) and (curr >= MaxExtended/t) then begin
Kv := PosInf_x;
Kv1 := PosInf_x;
exit;
end;
next := t*curr + prev;
prev := curr;
curr := next;
end;
if v < -0.5 then begin
Kv1 := prev;
Kv := curr;
end
else begin
Kv := prev;
Kv1 := curr;
end;
end;
{---------------------------------------------------------------------------}
function sfc_ive(v, x: extended): extended;
{-Return I_v(x)*exp(-|x|), the exponentially scaled modified Bessel function of the 1st kind, order v.}
var
r,t: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) then begin
sfc_ive := NaN_x;
exit;
end;
if x<0.0 then begin
{if v is not an integer I(v, x) is complex}
if frac(v)=0.0 then begin
r := sfc_ive(v,-x);
if frac(0.5*v)<>0 then r := -r;
sfc_ive := r;
end
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_ive := NaN_x;
end;
end
else if x=0.0 then begin
if v=0.0 then sfc_ive := 1.0
else sfc_ive := 0.0;
end
else begin
{x>0}
if v=0.0 then sfc_ive := sfc_i0e(x)
else if abs(v)=1.0 then sfc_ive := sfc_i1e(x)
else begin
bessel_ik(v,x,true,true,r,t);
sfc_ive := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_kve(v, x: extended): extended;
{-Return K_v(x)*exp(x), the exponentially scaled modified Bessel function of the 2nd kind, order v, x>0}
var
r,t: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) then begin
sfc_kve := NaN_x;
exit;
end;
if x<=0.0 then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_kve := NaN_x;
end
else begin
v := abs(v);
if v=0.0 then sfc_kve := sfc_k0e(x)
else if v=1.0 then sfc_kve := sfc_k1e(x)
else if abs(v)=0.5 then begin
{NIST[30] 10.39.1: K(0.5,x) = K(-0.5,x) = exp(-x)*sqrt(Pi/2/x)}
sfc_kve := sqrt(Pi_2/x);
end
else begin
bessel_ik(v, x, false, true, t, r);
sfc_kve := r;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure sfc_bess_ikv(v,x: extended; var Iv,Kv: extended);
{-Return I_v(x) and K_v(x), no checks, x>0, |v| < MaxLongint}
begin
bessel_ik(v,x,true,false,Iv,Kv);
end;
{---------------------------------------------------------------------------}
function sfc_sph_jn(n: integer; x: extended): extended;
{-Return j_n(x), the spherical Bessel function of the 1st kind, order n}
var
r,z: extended;
begin
if IsNaNorInf(x) then begin
sfc_sph_jn := NaN_x;
exit;
end;
if n=0 then sfc_sph_jn := sinc(x)
else begin
if x=0.0 then sfc_sph_jn := 0.0
else begin
z := abs(x);
r := sqrt(Pi_2/z)*sfc_jv(0.5+n,z);
if (x<0.0) and odd(n) then r := -r; {NIST 10.47.14}
sfc_sph_jn := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_sph_yn(n: integer; x: extended): extended;
{-Return y_n(x), the spherical Bessel function of the 2nd kind, order n >=0 , x<>0}
var
r,z: extended;
begin
if IsNaNorInf(x) then begin
sfc_sph_yn := NaN_x;
exit;
end;
z := abs(x);
if x=0.0 then r := NegInf_x
else r := sqrt(Pi_2/z)*sfc_yv(0.5+n,z);
if (x<0.0) and odd(n+1) then r := -r; {NIST 10.47.14}
sfc_sph_yn := r;
end;
{---------------------------------------------------------------------------}
function sfc_sph_in(n: integer; x: extended): extended;
{-Return i_n(x), the modified spherical Bessel function of the 1st/2nd kind, order n}
var
r: extended;
begin
if IsNaNorInf(x) then begin
sfc_sph_in := NaN_x;
exit;
end;
if n=0 then sfc_sph_in := sinhc(x) {i_0 = sinh(x)/x}
else begin
if x=0.0 then begin
if n>0 then sfc_sph_in := 0.0
else if odd(n) then sfc_sph_in := PosInf_x
else sfc_sph_in := NegInf_x
end
else begin
r := abs(x);
r := sqrt(Pi_2/r)*sfc_iv(0.5+n,r);
if (x<0.0) and odd(n) then r := -r; {NIST 10.47.16}
sfc_sph_in := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_sph_ine(n: integer; x: extended): extended;
{-Return i_n(x)*exp(-|x|), the exponentially scaled modified spherical Bessel function of the 1st/2nd kind, order n}
var
r,z: extended;
begin
if IsNaNorInf(x) then begin
sfc_sph_ine := NaN_x;
exit;
end;
z := abs(x);
if n=0 then begin
{i_0e = exp(-z)*sinh(z)/z}
if z<=1e-10 then begin
{exp(-z)*sinh(z)/z = 1 - z + 2/3*z^2 - 1/3*z^3 + 2/15*z^4 + O(z^5)}
sfc_sph_ine := 1.0 - z;
end
else begin
{exp(-z)*sinh(z)/z = -0.5*(exp(-2z)-1)/z}
if z>=25 then sfc_sph_ine := 0.5/z
else sfc_sph_ine := (-0.5)*expm1(-2.0*z)/z;
end;
end
else begin
if x=0.0 then begin
if n>0 then sfc_sph_ine := 0.0
else if odd(n) then sfc_sph_ine := PosInf_x
else sfc_sph_ine := NegInf_x
end
else begin
r := sqrt(Pi_2/z)*sfc_ive(0.5+n,z);
if (x<0.0) and odd(n) then r := -r; {NIST 10.47.16}
sfc_sph_ine := r;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_sph_kn(n: integer; x: extended): extended;
{-Return k_n(x), the modified spherical Bessel function of the 3rd kind, order n, x>0}
begin
if IsNaNorInf(x) then begin
sfc_sph_kn := NaN_x;
exit;
end;
if x<0.0 then begin
sfc_sph_kn := NaN_x;
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
exit;
end;
if n<0 then n := -n-1; {NIST 10.47.9}
if n=0 then sfc_sph_kn := Pi_2*exp(-x)/x
else sfc_sph_kn := sqrt(Pi_2/x)*sfc_kv(0.5+n,x);
end;
{---------------------------------------------------------------------------}
function sfc_sph_kne(n: integer; x: extended): extended;
{-Return k_n(x)*exp(x), the exponentially scaled modified spherical Bessel function of the 3rd kind, order n, x>0}
begin
if IsNaNorInf(x) then begin
sfc_sph_kne := NaN_x;
exit;
end;
if x<0.0 then begin
sfc_sph_kne := NaN_x;
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
exit;
end;
if n<0 then n := -n-1; {NIST 10.47.9}
if n=0 then sfc_sph_kne := Pi_2/x
else sfc_sph_kne := sqrt(Pi_2/x)*sfc_kve(0.5+n,x);
end;
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function Airy_small(x,f0,f1: extended): extended;
{-Compute Ai(x) or Bi(x) via Maclaurin series, x small, f0=f(0), f1=f'(0)}
var
ai,da,t1,t2,x3: extended;
k: integer;
const
MAXIT3 = 120;
begin
{Maclaurin series NIST[30], 9.4.1/9.4.3}
t1 := f0;
t2 := f1*x;
ai := t1 + t2;
x3 := x*sqr(x);
k := 3;
while k<MAXIT3 do begin
t1 := t1*x3/(k*(k-1));
t2 := t2*x3/(k*(k+1));
da := t1 + t2;
ai := ai + da;
if abs(da) < abs(ai)*eps_x then begin
Airy_small := ai;
exit;
end;
inc(k,3);
end;
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
Airy_small := ai;
end;
const
{ Ai(0) = 0.35502805388781723926 = 3^(-2/3)/gamma(2/3) NIST[30], 9.2.3}
{ Ai'(0) = -0.25881940379280679840 = -3^(-1/3)/gamma(1/3) NIST[30], 9.2.4}
{ Bi(0) = 0.61492662744600073516 = 3^(-1/6)/gamma(2/3) NIST[30], 9.2.5}
{ Bi'(0) = 0.44828835735382635789 = 3^(+1/6)/gamma(1/3) NIST[30], 9.2.6}
rt3h: THexExtW = ($539E,$C265,$D742,$DDB3,$3FFF); {+1.7320508075688772936}
ai0h: THexExtW = ($C2F5,$38AD,$3CB1,$B5C6,$3FFD); {+3.5502805388781723926E-1}
ai1h: THexExtW = ($545D,$B87C,$FA15,$8483,$BFFD); {-2.5881940379280679839E-1}
bi0h: THexExtW = ($4BAB,$51F5,$D4DA,$9D6B,$3FFE); {+6.1492662744600073516E-1}
bi1h: THexExtW = ($0458,$0645,$0D34,$E586,$3FFD); {+4.4828835735382635791E-1}
var
rt3: extended absolute rt3h; { = 3^0.5 }
ai0: extended absolute ai0h; { = Ai(0) }
ai1: extended absolute ai1h; { = Ai'(0) }
bi0: extended absolute bi0h; { = Bi(0) }
bi1: extended absolute bi1h; { = Bi'(0) }
{---------------------------------------------------------------------------}
function sfc_airy_ai(x: extended): extended;
{-Return the Airy function Ai(x)}
var
z,Jv,Yv: extended;
begin
if IsNaNorInf(x) then begin
sfc_airy_ai := NaN_x;
exit;
end;
if (x <= 1.0) and (x >= -2.0) then begin
sfc_airy_ai := Airy_small(x,ai0,ai1);
end
else begin
z := abs(x);
z := 2.0*z*sqrt(z)/THREE;
if x>0.0 then begin
{NR[13], 6.7.41}
z := sfc_kv(1.0/3.0, z);
sfc_airy_ai := sqrt(x/THREE)*z/Pi;
end
else begin
{NR[13], 6.7.46}
sfc_bess_jyv(1.0/3.0, z, Jv, Yv);
z := Jv - Yv/rt3;
sfc_airy_ai := 0.5*sqrt(-x)*z;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_bi(x: extended): extended;
{-Return the Airy function Bi(x)}
var
z,bij,bky: extended;
begin
if IsNaNorInf(x) then begin
sfc_airy_bi := NaN_x;
exit;
end;
z := abs(x);
if z < 1.0 then begin
sfc_airy_bi := Airy_small(x,bi0,bi1);
end
else begin
z := 2.0*z*sqrt(z)/THREE;
if x>0.0 then begin
{NR[13], 6.7.44}
sfc_bess_ikv(1.0/3.0,z,bij,bky);
z := 2.0*bij/rt3 + bky/Pi;
sfc_airy_bi := sqrt(x)*z;
end
else begin
{NR[13], 6.7.46}
sfc_bess_jyv(1.0/3.0, z, bij, bky);
z := bij/rt3 + bky;
sfc_airy_bi := (-0.5)*sqrt(-x)*z;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_ais(x: extended): extended;
{-Return the scaled Airy function Ai(x) if x <= 0, Ai(x)*exp(2/3*x^1.5) for x > 0}
var
z: extended;
const
xs = 1.0; { if x<=xs use Ai(x) else BesselK}
xl = 2199023255552.0; {> (3d_1/eps)^(2/3)}
begin
if IsNaNorInf(x) then begin
sfc_airy_ais := NaN_x;
exit;
end;
if x<=0.0 then sfc_airy_ais := sfc_airy_ai(x)
else if x < xl then begin
z := 2.0*x*sqrt(x)/THREE;
if x<=xs then begin
z := exp(z);
sfc_airy_ais := sfc_airy_ai(x)*z;
end
else begin
z := sfc_kve(1.0/3.0, z);
sfc_airy_ais := sqrt(x/THREE)*z/Pi;
end;
end
else begin
{HMF[1], 10.4.59}
z := sqrt(x);
sfc_airy_ais := 0.5/sqrtPi/sqrt(z);
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_bis(x: extended): extended;
{-Return the scaled Airy function Bi(x) if x <= 0, Bi(x)*exp(-2/3*x^1.5) for x > 0}
var
z,bij,bky: extended;
const
xt = 1e-20; {for 0<=x<xt, exp(..)=1 }
xk = 12.0; {K(1/3,..) negligible if x>xk }
xl = 2199023255552.0; {> (3d_1/eps)^(2/3) }
begin
if IsNaNorInf(x) then begin
sfc_airy_bis := NaN_x;
exit;
end;
if x<=xt then sfc_airy_bis := sfc_airy_bi(x)
else if x<xl then begin
z := 2.0*x*sqrt(x)/THREE;
bessel_ik(1.0/3.0,z,true,true,bij,bky);
bij := 2.0*bij/rt3;
if x<xk then
bij := bij + bky/Pi*exp(-2*z);
sfc_airy_bis := sqrt(x)*bij;
end
else begin
z := sqrt(x);
sfc_airy_bis := 1.0/sqrtPi/sqrt(z);
end;
end;
{---------------------------------------------------------------------------}
function AiryP_small(x,f0,f1: extended): extended;
{-Compute Ai'(x) or Bi'(x) via Maclaurin series, x small, f0=f(0), f1=f'(0)}
var
ai,da,t1,t2,x3: extended;
k: integer;
const
MAXIT3 = 120;
begin
{Maclaurin series NIST[30], 9.4.2/9.4.4}
t1 := f1;
t2 := 0.5*f0*x*x;
ai := t1 + t2;
x3 := x*sqr(x);
k := 3;
while k<MAXIT3 do begin
t1 := t1*x3/(k*(k-2));
t2 := t2*x3/(k*(k+2));
da := t1 + t2;
ai := ai + da;
if abs(da) < abs(ai)*eps_x then begin
AiryP_small := ai;
exit;
end;
inc(k,3);
end;
AiryP_small := ai;
end;
{---------------------------------------------------------------------------}
function sfc_airy_aip(x: extended): extended;
{-Return the Airy function Ai'(x)}
var
z,Jv,Yv: extended;
begin
if IsNaNorInf(x) then begin
sfc_airy_aip := NaN_x;
exit;
end;
z := abs(x);
if z <= 1.0 then begin
sfc_airy_aip := AiryP_small(x,ai0,ai1);
end
else begin
z := 2.0*z*sqrt(z)/THREE;
if x>0.0 then begin
{NR[13], 6.7.45}
z := sfc_kv(2.0/THREE, z);
sfc_airy_aip := -x/rt3*z/Pi;
end
else begin
{NR[13], 6.7.46}
sfc_bess_jyv(2.0/THREE, z, Jv, Yv);
z := Jv + Yv/rt3;
sfc_airy_aip := (-0.5)*x*z;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_bip(x: extended): extended;
{-Return the Airy function Bi'(x)}
var
z,bij,bky: extended;
begin
if IsNaNorInf(x) then begin
sfc_airy_bip := NaN_x;
exit;
end;
z := abs(x);
if z <= 1.0 then begin
sfc_airy_bip := AiryP_small(x,bi0,bi1);
end
else begin
z := 2.0*z*sqrt(z)/THREE;
if x>0.0 then begin
{NR[13], 6.7.45}
sfc_bess_ikv(2.0/THREE,z,bij,bky);
z := 2.0*bij/rt3 + bky/Pi;
sfc_airy_bip := x*z;
end
else begin
{NR[13], 6.7.46}
sfc_bess_jyv(2.0/THREE, z, bij, bky);
z := bij/rt3 - bky;
sfc_airy_bip := (-0.5)*x*z;
end;
end;
end;
{---------------------------------------------------------------------------}
function gipos7(x: extended): extended;
{-Return Airy/Scorer Gi(x) for x >= 7}
const
ntip2 = 30;
argip2: array[0..ntip2-1] of extended = (
2.00473712275801486391e0,
0.294184139364406724e-2,
0.71369249006340167e-3,
0.17526563430502267e-3,
0.4359182094029882e-4,
0.1092626947604307e-4,
0.272382418399029e-5,
0.66230900947687e-6,
0.15425323370315e-6,
0.3418465242306e-7,
0.728157724894e-8,
0.151588525452e-8,
0.30940048039e-9,
0.6149672614e-10,
0.1202877045e-10,
0.233690586e-11,
0.43778068e-12,
0.7996447e-13,
0.1494075e-13,
0.246790e-14,
0.37672e-15,
0.7701e-16,
0.354e-17,
-0.49e-18,
0.62e-18,
-0.40e-18,
-0.1e-19,
0.2e-19,
-0.3e-19,
0.1e-19);
const
xmax = 2642245.94963; {> cbrt(2/eps_x); double: 208063.8307}
var
x3, t: extended;
begin
{Ref: MacLeod's [22], MISCFUN, function airy_gi}
gipos7 := 0.0;
if x<7.0 then exit
else if x <= xmax then begin
x3 := x*x*x;
t := (1200.0 - x3)/(514.0 + x3);
t := CSEvalX(t, argip2, ntip2);
gipos7 := t/x/Pi;
end
else gipos7 := 1.0/Pi/x;
end;
{---------------------------------------------------------------------------}
function hineg8(x: extended): extended;
{-Return Airy/Scorer Hi(x) for x <= -8}
var
x3, t: extended;
const
xmin = -2642245.9496; {< cbrt(2/eps_x); double: -208063.831}
const
ntin2 = 16;
arhin2: array[0..ntin2-1] of extended = (
1.99647720399779650525e0,
-0.187563779407173213e-2,
-0.12186470897787339e-3,
-0.814021609659287e-5,
-0.55050925953537e-6,
-0.3763008043303e-7,
-0.258858362365e-8,
-0.17931829265e-9,
-0.1245916873e-10,
-0.87171247e-12,
-0.6084943e-13,
-0.431178e-14,
-0.29787e-15,
-0.2210e-16,
-0.136e-17,
-0.14e-18);
begin
{Ref: MacLeod's [22], MISCFUN, function airy_hi}
hineg8 := 0.0;
if x > -8.0 then exit;
if x <= xmin then hineg8 := (-1.0)/Pi/x
else begin
x3 := x*x*x;
t := (x3 + 1200.0)/(176.0 - x3);
t := CSEvalX(t, arhin2, ntin2);
hineg8 := -t/Pi/x;
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_hi(x: extended): extended;
{-Return the Airy/Scorer function Hi(x) = 1/Pi*integral(exp(x*t-t^3/3), t=0..INF)}
const
hizero = 0.4099510849640004901; {Hi(0) = 2/Gamma(2/3)/3^(7/6)}
var
t: extended;
const
ntin4 = 22;
arhin1: array[0..ntin4-1] of extended = (
0.31481017206423404116e0,
-0.16414499216588964341e0,
0.6176651597730913071e-1,
-0.1971881185935933028e-1,
0.536902830023331343e-2,
-0.124977068439663038e-2,
0.24835515596994933e-3,
-0.4187024096746630e-4,
0.590945437979124e-5,
-0.68063541184345e-6,
0.6072897629164e-7,
-0.367130349242e-8,
0.7078017552e-10,
0.1187894334e-10,
-0.120898723e-11,
0.1189656e-13,
0.594128e-14,
-0.32257e-15,
-0.2290e-16,
0.253e-17,
0.9e-19,
-0.2e-19);
const
ntip1 = 32;
arhip : array[0..ntip1-1] of extended = (
1.24013562561762831114,
0.64856341973926535804,
0.55236252592114903246,
0.20975122073857566794,
0.12025669118052373568,
0.3768224931095393785e-1,
0.1651088671548071651e-1,
0.455922755211570993e-2,
0.161828480477635013e-2,
0.40841282508126663e-3,
0.12196479721394051e-3,
0.2865064098657610e-4,
0.742221556424344e-5,
0.163536231932831e-5,
0.37713908188749e-6,
0.7815800336008e-7,
0.1638447121370e-7,
0.319857665992e-8,
0.61933905307e-9,
0.11411161191e-9,
0.2064923454e-10,
0.360018664e-11,
0.61401849e-12,
0.10162125e-12,
0.1643701e-13,
0.259084e-14,
0.39931e-15,
0.6014e-16,
0.886e-17,
0.128e-17,
0.18e-18,
0.3e-19);
const
xmax = 662.1358350378; {overflow threshold}
begin
{Pascal port of A.J. MacLeod's [22] MISCFUN function airy_hi. }
{AMath uses airy_bi instead of another Chebyshev approximation}
if x < 0.0 then begin
if x > -eps_x then sfc_airy_hi := hizero
else if x <= -8.0 then sfc_airy_hi := hineg8(x)
else begin
t := (4.0*x + 12.0)/(x - 12.0);
sfc_airy_hi := CSEvalX(t,arhin1, ntin4);
end
end
else begin
if x < eps_x then sfc_airy_hi := hizero
else if x > 7.0 then begin
if x>xmax then sfc_airy_hi := PosInf_x
else begin
t := gipos7(x);
sfc_airy_hi := sfc_airy_bi(x) - t;
end;
end
else begin
t := 2.0*x/7.0 - 1.0;
t := CSEvalX(t,arhip, ntip1);
sfc_airy_hi := t*exp(1.5*x);
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_airy_gi(x: extended): extended;
{-Return the Airy/Scorer function Gi(x) = 1/Pi*integral(sin(x*t+t^3/3), t=0..INF)}
const
ntin3 = 43;
argin1: array[0..ntin3-1] of extended = (
-0.20118965056732089130e0,
-0.7244175303324530499e-1,
0.4505018923894780120e-1,
-0.24221371122078791099e0,
0.2717884964361678294e-1,
-0.5729321004818179697e-1,
-0.18382107860337763587e0,
0.7751546082149475511e-1,
0.18386564733927560387e0,
0.2921504250185567173e-1,
-0.6142294846788018811e-1,
-0.2999312505794616238e-1,
0.585937118327706636e-2,
0.822221658497402529e-2,
0.132579817166846893e-2,
-0.96248310766565126e-3,
-0.45065515998211807e-3,
0.772423474325474e-5,
0.5481874134758052e-4,
0.1245898039742876e-4,
-0.246196891092083e-5,
-0.169154183545285e-5,
-0.16769153169442e-6,
0.9636509337672e-7,
0.3253314928030e-7,
0.5091804231e-10,
-0.209180453553e-8,
-0.41237387870e-9,
0.4163338253e-10,
0.3032532117e-10,
0.340580529e-11,
-0.88444592e-12,
-0.31639612e-12,
-0.1505076e-13,
0.1104148e-13,
0.246508e-14,
-0.3107e-16,
-0.9851e-16,
-0.1453e-16,
0.118e-17,
0.67e-18,
0.6e-19,
-0.1e-19);
const
ntip1 = 31;
argip1: array[0..ntip1-1] of extended = (
0.26585770795022745082e0,
-0.10500333097501922907e0,
0.841347475328454492e-2,
0.2021067387813439541e-1,
-0.1559576113863552234e-1,
0.564342939043256481e-2,
-0.59776844826655809e-3,
-0.42833850264867728e-3,
0.22605662380909027e-3,
-0.3608332945592260e-4,
-0.785518988788901e-5,
0.473252480746370e-5,
-0.59743513977694e-6,
-0.15917609165602e-6,
0.6336129065570e-7,
-0.276090232648e-8,
-0.256064154085e-8,
0.47798676856e-9,
0.4488131863e-10,
-0.2346508882e-10,
0.76839085e-12,
0.73227985e-12,
-0.8513687e-13,
-0.1630201e-13,
0.356769e-14,
0.25001e-15,
-0.10859e-15,
-0.158e-17,
0.275e-17,
-0.5e-19,
-0.6e-19);
const
gizero = 0.204975542482000245050307456365; {Gi(0) = 1/Gamma(2/3)/3^(7/6)}
var
t: extended;
begin
{Pascal port of A.J. MacLeod's [22] MISCFUN function airy_gi. }
{AMath uses airy_bi instead of another Chebyshev approximation}
if x < -8.0 then begin
t := hineg8(x);
sfc_airy_gi := sfc_airy_bi(x) - t;
end
else if x <= -eps_x then begin
t := -(x+4.0)/4.0;
sfc_airy_gi := CSEvalX(t,argin1, ntin3);
end
else if x < eps_x then begin
{abs(x) < eps_x}
sfc_airy_gi := gizero;
end
else if x < 7.0 then begin
t := (9.0*x - 28.0)/(x + 28.0);
sfc_airy_gi := CSEvalX(t,argip1,ntip1);
end
else begin
{x > 7}
sfc_airy_gi := gipos7(x);
end;
end;
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function ber_sm(x: extended): extended;
{-Return the Kelvin function ber(x), 0<=x<20}
var
f,s,t,x4: extended;
k: integer;
begin
{Ref: HMF [1], 9.9.10}
k := 1;
s := 1.0;
t := 1.0;
x4:= -0.0625*sqr(sqr(x));
repeat
f := sqr(2*k);
f := f*sqr(2*k-1);
t := t/f*x4;
s := s+t;
k := k+1;
until abs(t) < eps_x*abs(s);
ber_sm := s;
end;
{---------------------------------------------------------------------------}
function bei_sm(x: extended): extended;
{-Return the Kelvin function bei(x), 0<=x<20}
var
f,s,t,x4: extended;
k: integer;
begin
{Ref: HMF [1], 9.9.10}
k := 1;
t := 0.25*sqr(x);
s := t;
x4:= -sqr(t);
repeat
f := sqr(2*k);
f := f*sqr(2*k+1);
t := t/f*x4;
s := s+t;
k := k+1;
until abs(t) < eps_x*abs(s);
bei_sm := s;
end;
{---------------------------------------------------------------------------}
function ker_sm(x: extended): extended;
{-Return the Kelvin function ker(x), 0<x<3}
var
f,h,s,t,x4: extended;
k: integer;
begin
{Ref: HMF [1], 9.9.12}
k := 1;
h := 0.0;
t := 1.0;
x := abs(x);
x4:= -0.0625*sqr(sqr(x));
s := Pi_4*bei_sm(x);
f := ln(0.5*x) + EulerGamma;
{bei/ber are accurate, but the cancellation for s is too large for x>3}
s := s - f*ber_sm(x);
repeat
f := sqr(2*k);
f := f*sqr(2*k-1);
t := t/f*x4;
h := h + (1.0/(2*k) + 1.0/(2*k-1));
f := t*h;
s := s+f;
k := k+1;
until abs(f) < eps_x*abs(s);
ker_sm := s;
end;
{---------------------------------------------------------------------------}
function kei_sm(x: extended): extended;
{-Return the Kelvin function kei(x), 0<x<3}
var
f,h,s,t,x4: extended;
k: integer;
begin
{Ref: HMF [1], 9.9.12}
k := 1;
h := 1.0;
t := 0.25*sqr(x);
x := abs(x);
x4:= -sqr(t);
f := ln(0.5*x) + EulerGamma;
s := t - Pi_4*ber_sm(x);
{bei/ber are accurate, but the cancellation for s is too large for x>3}
s := s - f*bei_sm(x);
repeat
f := sqr(2*k);
f := f*sqr(2*k+1);
t := t/f*x4;
h := h + (1.0/(2*k) + 1.0/(2*k+1));
f := t*h;
s := s+f;
k := k+1;
until abs(f) < eps_x*abs(s);
kei_sm := s;
end;
{---------------------------------------------------------------------------}
procedure kelvin_large(x: extended; cb: boolean; var br, bi, kr, ki: extended);
{-Return all four Kelvin functions for x >= 20 using asymptotic expansions}
{ ker/kei are always calculated, ber/bei only if cb=true}
var
f0p, {f0(+x)}
f0n, {f0(-x)}
g0p, {g0(+x)}
g0n, {g0(-x)}
tk, {term k}
tc, {cos() term}
ts, {sin() term}
fac,xt: extended;
k: integer;
cbp, {calc f0p,f0p}
ckn: boolean; {calc f0n,g0n}
const
kmax = 40; {Note: for k > 2*x the terms are increasing}
xlarge = 16060.55; {>~ ln_MaxExt*sqrt(2)}
const
skp4hx: array[0..7] of THexExtW = ( { sin(k*Pi/4), k=0..7 }
($0000,$0000,$0000,$0000,$0000), { 0.0000000000000000000}
($6484,$F9DE,$F333,$B504,$3FFE), { 0.7071067811865475244}
($0000,$0000,$0000,$8000,$3FFF), { 1.0000000000000000000}
($6484,$F9DE,$F333,$B504,$3FFE), { 0.7071067811865475244}
($0000,$0000,$0000,$0000,$0000), { 0.0000000000000000000}
($6484,$F9DE,$F333,$B504,$BFFE), {-0.7071067811865475244}
($0000,$0000,$0000,$8000,$BFFF), {-1.0000000000000000000}
($6484,$F9DE,$F333,$B504,$BFFE)); {-0.7071067811865475244}
var
sinkp4: array[0..7] of extended absolute skp4hx;
begin
if x > xlarge then begin
kr := 0.0;
ki := 0.0;
if cb then begin
{may nan_x?}
br := PosInf_x;
bi := PosInf_x;
end;
exit;
end;
{The functions are calculated using formula from HMF[1], section 9.10}
{with nu=0 and x >= 20.}
f0p := 1.0; {k=0 term of sum for function f0(+x): 9.10.6}
f0n := 1.0; {k=0 term of sum for function f0(-x): 9.10.6}
g0p := 0.0; {k=0 term of sum for function g0(+x): 9.10.7}
g0n := 0.0; {k=0 term of sum for function g0(-x): 9.10.7}
tk := 1.0; {term k of sum = prod(2j-1, j=1..k)/k!/(8x)^k}
fac := 1.0; {factor (+-)^k}
cbp := cb; {calc ber/bei}
ckn := true; {calc ker/kei}
xt := 8.0*x;
k := 0;
while (k<kmax) and (cbp or ckn) do begin
fac := -fac;
inc(k);
tk := tk*sqr(2*k-1)/xt/k; {term k = prod(2j-1, j=1..k)/k!/(8x)^k}
tc := tk*sinkp4[(k+2) and 7]; {tk*cos(k*Pi/4)}
ts := tk*sinkp4[k and 7]; {tk*sin(k*Pi/4)}
if ckn then begin
f0n := f0n + fac*tc; {update and conv check f0(-x), g0(-x)}
g0n := g0n + fac*ts;
ckn := tk >= eps_x*minx(abs(f0n), abs(g0n));
end;
if cbp then begin
f0p := f0p + tc; {update and conv check f0(+x), g0(+x)}
g0p := g0p + ts;
cbp := tk >= eps_x*minx(abs(f0p),abs(g0p));
end;
end;
xt := x/Sqrt2;
if xt>=ln_MaxExt then tk := PosInf_x else tk := exp(xt);
{get sin(beta), cos(beta), beta = x/sqrt(2) + Pi/8, HMF 9.10.5}
sincos(xt + 0.125*Pi, ts, tc);
fac := sqrt(Pi_2/x)/tk;
kr := fac*(f0n*tc - g0n*ts); {HMF 9.10.3}
ki := -fac*(f0n*ts + g0n*tc); {HMF 9.10.4}
if cb then begin
{get sin(alpha), cos(alpha), alpha = x/sqrt(2) - Pi/8, HMF 9.10.5}
sincos(xt - 0.125*Pi, ts, tc);
fac := tk/sqrt(TwoPi*x);
br := fac*(f0p*tc + g0p*ts) - ki/Pi; {HMF 9.10.1}
bi := fac*(f0p*ts - g0p*tc) + kr/Pi; {HMF 9.10.2}
end;
end;
{---------------------------------------------------------------------------}
procedure ker_kei_med(x: extended; var kr, ki: extended);
{-Return Kelvin function kr=ker(x), ki=kei(x), 3<=x<=20}
var
fac,ts,tc,f0,g0,z: extended;
const
csfh: array[0..25] of THexExtW = (
($506A,$C602,$4284,$B261,$BFFC), {-1.7419914183983770261E-1}
($37E4,$0D89,$9DC9,$D2BF,$3FF5), {+1.6078834637723389439E-3}
($B72F,$221B,$B883,$8A8D,$3FF3), {+2.6427001320521815227E-4}
($7504,$9B4C,$5152,$C85E,$BFF0), {-4.7771555992520623486E-5}
($A6EA,$3952,$4677,$D2A5,$3FED), {+6.2777282736162430502E-6}
($3707,$0164,$D168,$C112,$BFEA), {-7.1925486544564774167E-7}
($4D18,$0370,$0118,$8FF8,$3FE7), {+6.7040681229020080687E-8}
($7415,$1767,$0678,$B619,$BFE2), {-2.6498710934646215641E-9}
($FEC8,$4C88,$946A,$8596,$BFE1), {-9.7198209650154837839E-10}
($E222,$BBE5,$0103,$DBFA,$3FDF), {+4.0013506437635697668E-10}
($4AE8,$FC28,$ADF6,$E954,$BFDD), {-1.0610655385424269996E-10}
($A63B,$64ED,$B4A5,$D09E,$3FDB), {+2.3717341712233160606E-11}
($586B,$FBCD,$9CA8,$A4CB,$BFD9), {-4.6837658144710679937E-12}
($CD0E,$0302,$4074,$E09E,$3FD6), {+7.9800404853834490867E-13}
($8DEB,$A62B,$4A33,$E479,$BFD3), {-1.0146274419705259356E-13}
($9F62,$F52D,$5074,$B70A,$3FCD), {+1.2700971536601990071E-15}
($6511,$0AEE,$C2FA,$BFBF,$3FCF), {+5.3221057799364269748E-15}
($413D,$7650,$9726,$BA4C,$BFCE), {-2.5854205078178475222E-15}
($2E9B,$951C,$02B0,$82A2,$3FCD), {+9.0644751109753703700E-16}
($BCE2,$D446,$1B75,$9DF4,$BFCB), {-2.7400572090870253519E-16}
($CC25,$B66D,$E144,$AC37,$3FC9), {+7.4687773792482686324E-17}
($4BC9,$34AF,$577E,$A9FB,$BFC7), {-1.8429464094897889406E-17}
($69D4,$72A0,$72B6,$933D,$3FC5), {+3.9909490541622123671E-18}
($079B,$B0F6,$92EA,$C713,$BFC2), {-6.7449728433925005994E-19}
($6C07,$F752,$0C2B,$B1FE,$3FBE), {+3.7691351120612689369E-20}
($0B6E,$6263,$A0E4,$B1CA,$3FBE)); {+3.7648818270236777832E-20}
const
csgh: array[0..26] of THexExtW = (
($2C6C,$7C98,$35C1,$A0FA,$BFFC), {-1.5720447534035757322E-1}
($1BB1,$7184,$DFBC,$968E,$3FF8), {+9.1893372462197369193E-3}
($5940,$1F5D,$C613,$948D,$BFF4), {-5.6668778850565061864E-4}
($AED3,$254C,$35E7,$FED3,$3FEF), {+3.0377512126347748295E-5}
($FEB1,$50B7,$D101,$D390,$BFE8), {-1.9703590233373688640E-7}
($868B,$90B5,$2B3C,$C764,$BFE9), {-3.7139520931598000832E-7}
($0D6C,$2DF4,$EB31,$CE90,$3FE7), {+9.6189830799939401844E-8}
($7AA9,$25FC,$4836,$9EB6,$BFE5), {-1.8476513139939364061E-8}
($6C6A,$1B34,$E66D,$D293,$3FE2), {+3.0643093454233132330E-9}
($467C,$8D52,$1ED2,$EFDD,$BFDF), {-4.3630962238885554609E-10}
($1D8F,$78AC,$219D,$C8E6,$3FDC), {+4.5679132751061958419E-11}
($A387,$C1DC,$D1E6,$D64D,$3FD3), {+9.5170086962745579158E-14}
($7363,$CD4C,$A383,$8CF3,$BFD8), {-2.0030443265088914950E-12}
($B346,$C4C0,$457A,$E4DC,$3FD6), {+8.1307559857898340689E-13}
($2AE0,$9369,$58AB,$895D,$BFD5), {-2.4400860754197408382E-13}
($223A,$973B,$0306,$8EAB,$3FD3), {+6.3357326016347255195E-14}
($4DC2,$F451,$CC15,$84B5,$BFD1), {-1.4733785897064301269E-14}
($7B1B,$CCA2,$8E46,$DA49,$3FCE), {+3.0293452082666044179E-15}
($EA69,$9E74,$328C,$9268,$BFCC), {-5.0795139386674074074E-16}
($23CA,$CB49,$432B,$D00B,$3FC8), {+4.5112349988246225192E-17}
($623D,$DBB3,$E9F1,$F918,$3FC6), {+1.3503592759696792310E-17}
($88F8,$A531,$E00E,$C0B5,$BFC6), {-1.0446854432502786340E-17}
($DB22,$B28E,$3865,$A6CC,$3FC5), {+4.5210616813281396687E-18}
($51BE,$BCAA,$F012,$EE1D,$BFC3), {-1.6135431781668171227E-18}
($FEAA,$9029,$7A0E,$97EC,$3FC2), {+5.1473764432777121521E-19}
($43D2,$C671,$99B4,$B156,$BFC0), {-1.5021136840019478519E-19}
($DA1A,$83DE,$2FDA,$BCD0,$3FBE)); {+3.9982756711602287398E-20}
var
csf0: array[0..25] of extended absolute csfh;
csg0: array[0..26] of extended absolute csgh;
begin
{Medium range ker/kei: 3 <= x <= 20. The series for small x become}
{inaccurate for x >= 3 due to the difference of the ber/bei terms.}
z := x/Sqrt2;
{get sin(beta), cos(beta), beta = x/sqrt(2) + Pi/8}
sincos(z + 0.125*Pi, ts, tc);
fac:= sqrt(Pi_2/x)*exp(-z);
{get (asymptotic functions) f0,g0 via Chebyshev expansions}
z := 6.0/x - 1.0;
f0 := 1.0 + CSEvalX(z,csf0,26)/x;
g0 := CSEvalX(z,csg0,27)/x;
kr := fac*(f0*tc - g0*ts);
ki := -fac*(f0*ts + g0*tc);
end;
{---------------------------------------------------------------------------}
procedure sfc_ker_kei(x: extended; var kr, ki: extended);
{-Return the Kelvin functions kr=ker(x), ki=kei(x), x > 0}
var
br, bi: extended;
const
Omg = 0.422784335098467139393488; {1-gamma}
begin
if IsNaN(x) or (x<=0.0) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
kr := NaN_x;
ki := NaN_x;
end
else if x<=1e-10 then begin
kr := -(ln(0.5*x)+EulerGamma);
ki := -Pi_4;
end
else if x<=1e-5 then begin
{ker(x) = -gamma - ln(x/2) + 1/16*(Pi-3/8*x^2)*x^2 }
{kei(x) = 0.25*(-Pi + (1-gamma-ln(x/2))*x^2) }
br := ln(0.5*x);
x := sqr(x);
kr := -Eulergamma - br + 0.0625*(Pi-0.375*x)*x;
ki := 0.25*((Omg - br)*x - Pi);
end
else if x<3.0 then begin
kr := ker_sm(x);
ki := kei_sm(x);
end
else if x<=20.0 then ker_kei_med(x,kr,ki)
else kelvin_large(x,false,br,bi,kr,ki);
end;
{---------------------------------------------------------------------------}
procedure sfc_ber_bei(x: extended; var br, bi: extended);
{-Return the Kelvin functions br=ber(x), bi=bei(x)}
var
kr, ki: extended;
begin
if IsNaNorInf(x) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
br := NaN_x;
bi := NaN_x;
end
else begin
x := abs(x);
if x<=1e-5 then begin
br := 1.0;
bi := 0.25*sqr(x);
end
else if x<20.0 then begin
br := ber_sm(x);
bi := bei_sm(x);
end
else kelvin_large(x,true,br,bi,kr,ki);
end;
end;
{---------------------------------------------------------------------------}
function sfc_ber(x: extended): extended;
{-Return the Kelvin function ber(x)}
var
br,bi,kr,ki: extended;
begin
if IsNaNorInf(x) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_ber := NaN_x;
end
else begin
x := abs(x);
if x<=1e-5 then sfc_ber := 1.0
else if x<20.0 then sfc_ber := ber_sm(x)
else begin
kelvin_large(x,true,br,bi,kr,ki);
sfc_ber := br;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_bei(x: extended): extended;
{-Return the Kelvin function bei(x)}
var
br,bi,kr,ki: extended;
begin
if IsNaNorInf(x) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_bei := NaN_x;
end
else begin
x := abs(x);
if x<=1e-5 then sfc_bei := 0.25*sqr(x)
else if x<20.0 then sfc_bei := bei_sm(x)
else begin
kelvin_large(x,true,br,bi,kr,ki);
sfc_bei := bi;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_ker(x: extended): extended;
{-Return the Kelvin function ker(x), x > 0}
var
kr, ki: extended;
begin
if IsNaN(x) or (x<=1e-5) or (x>=3.0) then begin
sfc_ker_kei(x,kr,ki);
sfc_ker := kr;
end
else sfc_ker := ker_sm(x);
end;
{---------------------------------------------------------------------------}
function sfc_kei(x: extended): extended;
{-Return the Kelvin function kei(x), x >= 0}
var
kr, ki: extended;
begin
if IsNaN(x) or (x<=1e-5) or (x>=3.0) then begin
if x=0.0 then sfc_kei := -Pi_4
else begin
sfc_ker_kei(x,kr,ki);
sfc_kei := ki;
end;
end
else sfc_kei := kei_sm(x);
end;
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function sfc_struve_h0(x: extended): extended;
{-Return H0(x), the Struve function of order 0}
var
t,y: extended;
const
xlow = 0.69849193096160888673e-9; {3*sqrt(eps_x/2)}
const
nh0 = 20;
axh0: array[0..nh0-1] of THexExtW = (
($9F2C,$C6D9,$0F59,$92ED,$3FFD), {+0.28696487399013225740e0}
($DE82,$3B23,$4714,$8213,$BFFD), {-0.25405332681618352305e0}
($8711,$10A5,$DD5A,$D4B9,$3FFC), {+0.20774026739323894439e0}
($F9CC,$10C4,$14E7,$D087,$BFFC), {-0.20364029560386585140e0}
($C7CC,$F1A2,$5930,$83FA,$3FFC), {+0.12888469086866186016e0}
($87A0,$18A8,$6D74,$C5A8,$BFFA), {-0.4825632815622261202e-1}
($31A7,$87EF,$DE12,$BF77,$3FF8), {+0.1168629347569001242e-1}
($460F,$1F15,$B522,$81D6,$BFF6), {-0.198118135642418416e-2 }
($3178,$47EF,$0ED9,$828B,$3FF3), {+0.24899138512421286e-3 }
($0E9A,$7FFB,$EF15,$CAE7,$BFEF), {-0.2418827913785950e-4 }
($D62A,$7E05,$0D14,$FB93,$3FEB), {+0.187437547993431e-5 }
($EF41,$7DB2,$690C,$FEFA,$BFE7), {-0.11873346074362e-6 }
($E718,$3DD5,$2DC9,$D76E,$3FE3), {+0.626984943346e-8 }
($CC7A,$7D13,$9920,$9A2E,$BFDF), {-0.28045546793e-9 }
($9EE3,$921E,$1EBE,$BD75,$3FDA), {+0.1076941205e-10 }
($3BC6,$C05F,$428C,$CA20,$BFD5), {-0.35904793e-12 }
($EA6E,$8AF3,$3358,$BD0D,$3FD0), {+0.1049447e-13 }
($C405,$2B9A,$9488,$9C54,$BFCB), {-0.27119e-15 }
($D8CE,$9204,$223A,$E637,$3FC5), {+0.624e-17 }
($E5DF,$B6AD,$16D1,$997A,$BFC0)); {-0.13e-18 }
const
nh0a = 21;
axh0a: array[0..nh0a-1] of THexExtW = (
($C0A6,$509B,$F712,$FF17,$3FFF), {+1.99291885751992305515e0}
($657A,$1628,$8B76,$FBCF,$BFF6), {-0.384232668701456887e-2 }
($7575,$3164,$0B09,$AC58,$BFF3), {-0.32871993712353050e-3 }
($ED70,$1238,$62AA,$F6B9,$BFEF), {-0.2941181203703409e-4 }
($B3B1,$FF97,$6D82,$B364,$BFEC), {-0.267315351987066e-5 }
($F307,$0D0B,$59CF,$8481,$BFE9), {-0.24681031075013e-6 }
($B8D3,$814C,$E917,$C523,$BFE5), {-0.2295014861143e-7 }
($BE24,$6B2C,$3830,$9437,$BFE2), {-0.215682231833e-8 }
($1EBF,$E875,$4A46,$DF3D,$BFDE), {-0.20303506483e-9 }
($12D5,$7691,$C488,$AA2A,$BFDB), {-0.1934575509e-10 }
($4A93,$FC5B,$7B86,$809D,$BFD8), {-0.182773144e-11 }
($EFF0,$0A68,$FECE,$C80D,$BFD4), {-0.17768424e-12 }
($A940,$9638,$D370,$9403,$BFD1), {-0.1643296e-13 }
($5CDC,$E8C4,$C9E6,$F741,$BFCD), {-0.171569e-14 }
($B4D6,$0EAD,$5F39,$9A1F,$BFCA), {-0.13368e-15 }
($98EC,$FEA2,$C6A2,$BF91,$BFC7), {-0.2077e-16 }
($1AEB,$9211,$0864,$BCE5,$3FBD), {+0.2e-19 }
($B322,$6D86,$D336,$A254,$BFC2), {-0.55e-18 }
($61A5,$B695,$4A7D,$EC1E,$3FBF), {+0.10e-18 }
($1AEB,$9211,$0864,$BCE5,$BFBE), {-0.4e-19 }
($1AEB,$9211,$0864,$BCE5,$3FBC)); {+0.1e-19 }
var
arrh0: array[0..nh0-1] of extended absolute axh0;
arrh0a: array[0..nh0a-1] of extended absolute axh0a;
begin
if IsNaN(x) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_h0 := NaN_x;
exit;
end;
{See MISCFUN [22], function STRVH0 for Chebyshev coefficients and hints. }
{As pointed out the phase of Y0(x) is very sensitive for |x| > 1/eps_x. }
{Therefore in high accuracy tests x must have exactly the same value in }
{both calculations. My implementation uses Y0, [22] has two other series.}
t := abs(x);
if t <= 11.0 then begin
if t<xlow then begin
{H0(x) = 2/Pi*x*(1-1/9*x^2+1/225*x^4+O(x^5))}
sfc_struve_h0 := x/Pi_2;
end
else begin
t := sqr(x)/60.5 - 1.0;
t := CSEvalX(t,arrh0,nh0);
sfc_struve_h0 := 2.0*x*t/Pi;
end;
end
else begin
y := sfc_y0(t);
{Correct sign if x<0 since H0 is an odd function}
if x<0.0 then y := -y;
if t >= 1e10 then begin
{Avoid squaring overflow and/or unnecessary calculations}
{H0(x) = Y0(x) + 2/Pi/x*(1 - 1/x^2 + ..}
sfc_struve_h0 := y + 2.0/Pi/x;
end
else begin
t := sqr(x);
t := (302.5 - t) / (60.5 + t);
t := CSEvalX(t,arrh0a,nh0a);
t := t/Pi_2/x;
sfc_struve_h0 := y + t;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_struve_h1(x: extended): extended;
{-Return H1(x), the Struve function of order 1}
var
t,y: extended;
const
xlow = 0.9017492053581906681e-9; {sqrt(15*eps_x/2)}
const
arrh1: array[0..17] of extended = (
+0.17319061083675439319e0,
-0.12606917591352672005e0,
0.7908576160495357500e-1,
-0.3196493222321870820e-1,
0.808040581404918834e-2,
-0.136000820693074148e-2,
0.16227148619889471e-3,
-0.1442352451485929e-4,
0.99219525734072e-6,
-0.5441628049180e-7,
0.243631662563e-8,
-0.9077071338e-10,
0.285926585e-11,
-0.7716975e-13,
0.180489e-14,
-0.3694e-16,
0.67e-18,
-0.1e-19);
arrh1a: array[0..21] of extended = (
+2.01083504951473379407e0,
0.592218610036099903e-2,
0.55274322698414130e-3,
0.5269873856311036e-4,
0.506374522140969e-5,
0.49028736420678e-6,
0.4763540023525e-7,
0.465258652283e-8,
0.45465166081e-9,
0.4472462193e-10,
0.437308292e-11,
0.43568368e-12,
0.4182190e-13,
0.441044e-14,
0.36391e-15,
0.5558e-16,
-0.4e-19,
0.163e-17,
-0.34e-18,
0.13e-18,
-0.4e-19,
0.1e-19);
begin
if IsNaN(x) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_h1 := NaN_x;
exit;
end;
{See MISCFUN [22], function STRVH1 for Chebyshev coefficients and hints.}
{As pointed out the phase of Y1(x) is very sensitive for |x| > 1/eps_x. }
{Therefore in high accuracy tests x must have exactly the same value in }
{both calculations; for |x| > 1/eps_x^2 the uncertainty vanishes and the}
{value of H1 is 2/Pi to machine precision, not 0 as in [22]. My function}
{uses Y1, whereas MISCFUN has two other Chebyshev series.}
t := abs(x);
if t <= 9.0 then begin
y := sqr(t);
if t < xlow then begin
{H1(x) = 2/Pi*x^2*(1/3 - 1/45*x^2 + O(x^4))}
{Note that the factor 1/3 is missing in [22], but xlow is correct}
sfc_struve_h1 := y/THREE/Pi_2;
end
else begin
t := y/40.5 - 1.0;
t := CSEvalX(t,arrh1,18);
sfc_struve_h1 := y*t/Pi_2;
end;
end
else begin
if t >= 1e40 then begin
{Avoid squaring overflow and/or unnecessary calculations}
{H1(x) = Y1(x) + 2/Pi(1 - 1/x^2 + ...) }
{H1(x) = 2/Pi - (2/Pi)^(1/2)*sin(x+Pi/4)*(1/x)^(1/2) + O((1/x)^(3/2))}
sfc_struve_h1 := 2.0/Pi;
end
else begin
y := sfc_y1(t);
t := sqr(t);
t := (202.5 - t) / (40.5 + t);
t := CSEvalX(t,arrh1a,22);
sfc_struve_h1 := y + t/Pi_2;
end;
end;
end;
{---------------------------------------------------------------------------}
function strv_sum(c, x: extended; var err: extended): extended;
{-Sum from Struve power series: sum(x^k/((1.5)_k*(c)_k)}
var
bn,cn,max,z,sum,t: extended;
e,y,w: extended;
n: integer;
const
NMAX = 200;
label
done;
begin
n := 0;
t := 1.0;
e := 0.0;
bn := 1.5;
cn := c;
sum := 1.0;
max := 0.0;
{Kahan summation}
while n<NMAX do begin
z := bn*cn;
t := t*(x/z);
w := t - e;
y := sum + w;
e := (y - sum) - w;
sum := y;
z := abs(t);
if z>max then max := z;
if z <= eps_x*abs(sum) then goto done;
bn := bn+1.0;
cn := cn+1.0;
inc(n);
end;
done:
if n>=NMAX then begin
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
end;
err := max*eps_x/abs(sum);
strv_sum := sum;
end;
{---------------------------------------------------------------------------}
function strv_ae(v,x: extended): extended;
{-Asymptotic expansion for H_v and L_v, x large (about 40 for H_v, 30 for L_v)}
var
s,b,c,max,z,sum,conv,conv1: extended;
k: integer;
const
KMAX = 1000;
label
done;
begin
k := 0;
b := 0.5;
c := 0.5-v;
s := 1.0;
sum := 1.0;
max := 0.0;
conv := MaxExtended;
conv1 := conv;
while k<KMAX do begin
s := s*b*c*x;
sum := sum + s;
z := abs(s);
if z > max then max := z
else if (z >= conv) and (z > conv1) then goto done;
if z <= eps_x*abs(sum) then goto done;
conv1 := conv;
conv := z;
b := b+1.0;
c := c+1.0;
k := k+1;
end;
done:
if k>=KMAX then begin
{No convergence}
if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence));
end;
strv_ae := sum;
end;
{---------------------------------------------------------------------------}
procedure strv_int(v, x: extended; var result,abserr: extended; var ier: integer);
{-Compute integral(e^(-xt)(1+t^2)^(v-0.5), t=0..INF) with custom version of }
{ AMTools.fdidei: Automatic quadrature over (a,INF) using Double Exponential.}
const
mmax = 2*64;
efs = 0.1;
hoff = 11.0;
var
eps: extended;
neval: longint;
function f(t: extended): extended;
var
d,z: extended;
begin
z := -t*x;
if z >= ln_MinExt then begin
inc(neval);
d := exp(z);
z := power(1+t*t,v-0.5);
f := d*z;
end
else f := 0;
end;
var
m: integer;
var
epsln,epsh,h0,ehp,ehm,epst,ir,iv,h,iback,irback,
t,ep,em,xp,xm,fp,fm,err,errt,errh,errd: extended;
begin
result := 0.0;
abserr := 0.0;
neval := 0;
ier := 0;
eps := 10*eps_x;
epsln := 1.0 - ln(efs*eps);
epsh := sqrt(efs*eps);
h0 := hoff/epsln;
ehp := exp(h0);
ehm := 1.0/ehp;
epst := exp(-ehm*epsln);
ir := f(1.0);
neval := 1;
iv := ir*pi_2;
err := abs(iv)*epst;
errh := 0.0;
h := 2.0*h0;
m := 1;
repeat
iback := iv;
irback := ir;
t := 0.5*h;
repeat
em := exp(t);
ep := pi_4*em;
em := pi_4/em;
repeat
xp := exp(ep-em);
xm := 1.0/xp;
fp := f(xp);
fm := f(xm);
fp := fp*xp;
fm := fm*xm;
ir := ir + (fp+fm);
iv := iv + (fp+fm)*(ep+em);
errt:= (abs(fp) + abs(fm))*(ep+em);
if m=1 then err := err + errt*epst;
ep := ep*ehp;
em := em*ehm;
until (errt <= err) and (xm <= epsh);
t := t + h;
until t >= h0;
if m=1 then begin
errh := (err/epst)*epsh*h0;
errd := 1.0 + 2.0*errh;
end
else errd := h*(abs(iv - 2.0*iback) + 4.0*abs(ir - 2.0*irback));
h := 0.5*h;
m := m+m;
until (errd <= errh) or (m >= mmax);
result := h*iv;
if errd > errh then begin
ier := 3;
abserr := errd*m;
end
else abserr := 0.5*errh*epsh*m/efs;
end;
{---------------------------------------------------------------------------}
function sfc_struve_h(v,x: extended): extended;
{-Return H_v(x), the Struve function of order v, x < 0 only if v is an integer.}
var
g,p,f,y,z,err: extended;
ier: integer;
begin
if IsNaNorInf(x) or IsNaNorInf(v) or ((x<0.0) and (frac(v)<>0.0)) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_h := NaN_x;
exit;
end;
if x=0.0 then begin
if (v>-1.0) or (frac(v)=-0.5) then sfc_struve_h := 0.0
else if v=-1.0 then sfc_struve_h := 2.0/Pi {http://functions.wolfram.com/03.09.03.0018.01}
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_h := NaN_x;
end;
end
else if v=0.0 then sfc_struve_h := sfc_struve_h0(x)
else if v=1.0 then sfc_struve_h := sfc_struve_h1(x)
else if v=0.5 then sfc_struve_h := vers(x)/sqrt(Pi_2*x) {HMF[1],12.1.16}
else if frac(v)=-0.5 then sfc_struve_h := sfc_yv(v,x)
else begin
{First compute H_v for |x|}
z := abs(x);
y := abs(v);
p := power(0.5*z, v-1.0);
if (z>=maxx(20,y)) or (z >= maxx(4,3*y)) then begin
g := sfc_gamma(v+0.5);
if z < maxx(40, 1.5*y) then begin
strv_int(v,z,f,err,ier);
f := z*f*p/(sqrtPI*g);
end
else begin
f := strv_ae(v, -sqr(2.0/z));
f := f*p/(sqrtPI*g);
end;
y := sfc_yv(v,z);
f := f + y;
end
else begin
y := 0.25*z*z;
f := strv_sum(1.5+v, -y, err);
g := sfc_gamma(v + 1.5);
f := y*p*f/(0.5*sqrtPI*g);
end;
if (x<0.0) and (f<>0.0) and (frac(0.5*v)=0.0) then f := -f;
sfc_struve_h := f;
end;
end;
{---------------------------------------------------------------------------}
function sfc_struve_l(v, x: extended): extended;
{-Return L_v(x), the modified Struve function of order v, x < 0 only if v is an integer.}
var
f,g,z,p,err: extended;
begin
if IsNaNorInf(x) or IsNaNorInf(v) or ((x<0.0) and (frac(v)<>0.0)) then begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_l := NaN_x;
exit;
end;
if x=0.0 then begin
if (v>-1.0) or (frac(v)=-0.5) then sfc_struve_l := 0.0
else if v=-1.0 then sfc_struve_l := 2.0/Pi {http://functions.wolfram.com/03.10.03.0018.01}
else begin
{$ifopt R+}
if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange));
{$endif}
sfc_struve_l := NaN_x;
end;
end
else if v=0.5 then sfc_struve_l := coshm1(x)/sqrt(Pi_2*x) {NIST[30],11.4.7}
else if frac(v)=-0.5 then sfc_struve_l := sfc_iv(-v,x)
else begin
z := abs(x);
p := power(0.5*z, v-1.0);
if z >= maxx(30,1.5*abs(v)) then begin
g := sfc_gamma(v+0.5);
f := strv_ae(v,sqr(2.0/z));
f := f*p/(sqrtPI*g);
z := sfc_iv(-v,z);
f := z - f;
end
else begin
g := sfc_gamma(v + 1.5);
z := sqr(0.5*z);
f := strv_sum(1.5+v, z, err);
f := f*p*z/(0.5*SqrtPi*g);
end;
if (x<0.0) and (f<>0.0) and (frac(0.5*v)=0.0) then f := -f;
sfc_struve_l := f;
end;
end;
{---------------------------------------------------------------------------}
function sfc_struve_l0(x: extended): extended;
{-Return L0(x), the modified Struve function of order 0}
begin
sfc_struve_l0 := sfc_struve_l(0,x);
end;
{---------------------------------------------------------------------------}
function sfc_struve_l1(x: extended): extended;
{-Return L1(x), the modified Struve function of order 1}
begin
sfc_struve_l1 := sfc_struve_l(1,x);
end;
end.
|
{Faça um programa em Pascal que leia um número n do teclado e decida se ele é positivo ou negativo. Seu programa deve imprimir a mensagem “par” ou “impar” conforme o caso}
program parOuImpar;
var
numero, par: Integer;
begin
read(numero);
par := numero MOD 2;
if par = 0 then
writeln('par')
else
writeln('impar');
end. |
PROGRAM EfficientRecursion (Input,Output);
{****************************************************************************
Author: Scott Janousek
Student ID: 4361106
Program Assignment 4
Due: Wed April 21, 1993
Section: 1 MWF 10:10
Instructor: Cris Pedgregal
Program Desciption: in this assignment, two routines have been implemented
which count the number of ways possible to move in a 2x2 dimensional square
Matrix starting from the first Row, First Column, to some Value of N. Steps
are restricted to to traveling up or to the right (not diagonally, left, or
down). Both Versions are of course recursive in their implementation.
The following program requires these Specifications:
NumPaths (Row, Col, N) : which returns an integer
Function: this function returns the possible paths to move in a 2x2 Matrix
from a starting Row/col to Row N/Col N.
Input: Row (integer) : starting row
Col (integer) : starting column
N (integer) : maximum row/column
Output: NumPaths (integer)
Preconditions: 1 <= Row <= N
1 <= Col <= N
Postconditions: NumPaths will be equal to the number of paths possbile to
move from starting point (Row/Col) to the end (Value of Row N/ Col N).
Assumptions: the input (N) in this program must be an integer, otherwise
the program crashes. N should be a positive number 1 to 20.
**Important!** : I have attempted the extra credit, but my solution is not
the most efficient implementation. I have no clue on how to accomplish it in
standard pascal. But in Turbo Pascal it is possible to use a built in MAXINT
function to check for arithmetic overflow. Obviously it won't work in Vax
Pascal. So I attempted my own error checking to some extent.
Also, please note that even though my Values for NumPaths2 are off
by a few Values (in terms of CallCount2) , the operation is still more
efficient than NumPaths1. Examine the session output and read my design
document and you will see that my program demonstrates this increase in
efficiency.
****************************************************************************}
CONST
MAXINT = 65535; {* Presumed Maxinteger *}
MaxSize = 25; {* Maximum Bounds *}
Exceeded = '** CallCount Exceeded the MAXINT **';
TYPE
Size = 1 .. MaxSize; {* Bounds of Array Index *}
MatrixType = ARRAY [Size, Size] OF Integer;
{* 2x2 Array for NumPaths2 implementation *}
VAR
CallCount1, CallCount2 : Integer; {* CallCount Variables *}
BeyondMaxInt1 : Boolean; {* MAXINT NumPath1 Flag *}
BeyondMaxInt2 : Boolean; {* MAXINT NumPath2 Flag *}
Matrix : MatrixType; {* Matrix for NumPaths2 *}
Quit : Boolean; {* Quit Program Flag *}
Solution : Integer; {* Used Check MAXINT *}
{***************************************************************************}
FUNCTION NumPaths1 (Row,
Col,
N : Integer) : Integer;
{* The Function demonstrates the Brute Force Approach Solution.
The efficiency of this opertaion is a poor solution to the problem
if the value of N is large. NumPaths1 may calculate values more than
once because of the way it is implemented. In this way, it is very
inefficient.
Also, please note that in a Call exceeds the MAXINT (65535) then
the program will respond with the appropriate error message instead of
crashing. *}
BEGIN {** of NumPaths1 **}
IF Callcount1 > MAXINT
THEN BeyondMaxInt1 := True {* Check MAXINT *}
ELSE
BEGIN {** CallCount1 within Bounds **}
IF (Row = N) OR (Col = N) {* Base Case *}
THEN NumPaths1 := 1
ELSE NumPaths1 := NumPaths1 (Row, Col + 1, N) +
NumPaths1 (Row + 1, Col, N);
{* General Case/Smaller Caller *}
CallCount1 := CallCount1 + 1; {* Increment Calls by + 1 *}
END; {** CallCount1 within Bounds **}
END; {** of NumPaths1 **}
{***************************************************************************}
FUNCTION PathCount1 (Row, Col, N : Integer) : Integer;
{* This operation allows us to invoke NumPaths1. If the CallCount does
not exceed MAXINT then the information (N, Calls, NumPaths) will be
printed onto the screen. Otherwise, an error messasge will result from
reaching MAXINT.
*}
BEGIN {** of PathCount **}
PathCount1 := NumPaths1 (Row, Col, N); {** Invoke NumPaths1 **}
IF BeyondMaxInt1 = TRUE THEN {** Print Error Message **}
Writeln (Exceeded:40)
ELSE
Write ('N =', N:3, 'CallCount1 = ':20,CallCount1:5, 'NumPaths1 = ':15);
END; {** of PathCount **}
{***************************************************************************}
FUNCTION NumPaths2 (Row,
Col,
N : Integer) : Integer;
{* This is the more efficient version of NumPaths. By using an intermediate
in a 2x2 array (Matrix) we can avoid from making calls that have already
been computed. This generally increases the speed of the Operation.
NumPaths1 provides a simpler and more effective solution. Execution-
time is improved drastically in comparision to NumPaths1 (see design
document for more details).
*}
BEGIN {** of NumPaths2 **}
IF CallCount2 > MAXINT {* Check MAXINT *}
THEN BeyondMaxInt2 := TRUE
ELSE
BEGIN {** CallCount2 within Bounds **}
IF (Matrix [Row, Col] = 0) THEN
IF (Row = N) OR (Col = N)
THEN Matrix [Row, Col] := 1 {* Path not taken yet,
set position to One *}
ELSE Matrix [Row, Col] := NumPaths2 (Row, Col + 1, N) +
NumPaths2 (Row + 1, Col, N);
{* General Case/Smaller Caller,
Set postion to Values *}
CallCount2 := CallCount2 +1; {* Increment Call + 1 *}
NumPaths2 := Matrix [Row, Col]; {* Set Matrix to Values *}
END; {** CallCount2 within Bounds **}
END; {** of NumPaths2 **}
{***************************************************************************}
FUNCTION PathCount2 (Row, Col, N : Integer) : Integer;
{* This operation allows us to invoke NumPaths2 amd if the CallCount does
not exceed MAXINT then the information (N, Calls, NumPaths) will be
printed onto the screen. Otherwise, an error messasge will result from
reaching MAXINT. *}
BEGIN {** of PathCount2 **}
PathCount2 := NumPaths2 (Row, Col, N); {** Invoke NumPaths2 **}
IF BeyondMaxInt2 = TRUE THEN {** Print Error Message **}
Writeln (Exceeded:40)
ELSE
Write ('N =', N:3, 'CallCount2 = ':20, Callcount2:5, 'NumPaths2 = ':15);
END; {** of PathCount2 **}
{***************************************************************************}
PROCEDURE CreateTheMatrix
(VAR Matrix : MatrixType;
Row, Col, N : integer);
{* This procedure creates the Matrix (2x2 Array) needed for the
storage of values computed by Numpaths2. The Matrix is filled
with Zeros. These indicate all the paths that have not been
already taken inside NumPaths2. Also, this Procedure Initializes
all variables within the program to their base conditions.
*}
VAR
x,y : integer;
BEGIN {** of Create the Matrix **}
Col := N; {* Column set to the value of N *}
Row := N; {* Row set to Value of N *}
CallCount1 := 0; {* Calls1 made initialized to Zero *}
CallCount2 := 0; {* Calls2 made initialized to Zero *}
Quit := FALSE; {* Quit Flag set to False *}
BeyondMaxInt1 := FALSE; {* Max integer1 Flag for NumPaths1 *}
BeyondMaxInt2 := FALSE; {* Max integer2 Flag for NumPaths2 *}
FOR x := 1 TO N DO
FOR y := 1 TO N DO
Matrix [x,y] := 0; {* Array Positions set to Zero,
which indicates not paths not taken *}
END; {** of Create the Matrix **}
{***************************************************************************}
PROCEDURE TestDriver;
{* The procedure is the Test Driver for NumPaths1 and NumPaths2. The user
is first prompted to enter a value for N (Ending Point in Matrix). If it
is a negative number, or above 20 then this program will not calculate
the paths. Valid values for N are between 0 and 20 for the purposes of
this Test Driver.
The operation CreateMatrix is called within this procedure. This
assigns the inital values to all global variables used within the
program. Then creates the Matrix for use in NumPaths2 (see program design).
*}
VAR
N, Row, Col : Integer;
BEGIN {*** of Test Driver ***}
writeln;
write ('Enter the Value of N = '); readln (N); writeln;
IF N = 0 THEN quit := TRUE
ELSE IF N > 20 THEN
Writeln ('** Value of N to large to compute! **')
ELSE IF N < 0 THEN
Writeln ('** Value of N needs to be positive! **')
ELSE
BEGIN {** Values to Calculate for NumPath Tests **}
CreatetheMatrix (Matrix, 1, 1, N); {* Creates the Matrix for NumPaths2 *}
writeln; writeln;
writeln ('= Brute Force Approach vs. More Efficient Version =');
writeln; writeln;
writeln ('(Value) (Calls Made) (Number of Paths)');
writeln;
Solution := PathCount1 (1, 1, N);
IF (BeyondMaxInt1 = FALSE) AND (Solution < MAXINT)
THEN writeln (Solution:5);
Solution := PathCount2 (1, 1, N);
IF (BeyondMaxInt2 = FALSE) AND (Solution < MAXINT)
THEN writeln (Solution:5);
IF Solution > MAXINT THEN
writeln ('Exceeded MAXINT');
writeln;
END; {** Values to Calculate for NumPath Tests **}
END; {*** of Test Driver ***}
{***************************************************************************}
BEGIN {***** Main Program *****}
writeln;
writeln ('Enter the Size of the Matrix at the prompt below.');
writeln ('Valid values for N are 0 to 20. Type 0 to Quit.');
REPEAT
TestDriver;
{* Test the Two Versions of NumPaths *}
UNTIL quit = TRUE;
writeln; writeln('Thank you for using this program.');
writeln('Goodbye.'); writeln;
END. {***** Main Program *****}
|
namespace org.me.listviewapp;
{
This makes a preference screen, automatically mapping shared preferences from the
default shared preferences file onto the widgets as defined in the related XML file.
The single preference represented here, and used by the two ListViewActivities
is 'use_custom_adapter_preference'
}
interface
uses
java.util,
android.app,
android.content,
android.os,
android.preference,
android.view,
android.widget,
android.util
;
type
ListViewActivitySettingsActivity = public class(PreferenceActivity)
protected
method onCreate(savedInstanceState: Bundle); override;
public
const AdapterPreference = 'use_custom_adapter_preference';
end;
implementation
method ListViewActivitySettingsActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
addPreferencesFromResource(R.xml.listviewactivitypreferences);
end;
end. |
unit uMultiCPUThreadManager;
interface
uses
System.Types,
System.Math,
System.Classes,
System.SyncObjs,
System.SysUtils,
Winapi.Windows,
Vcl.Forms,
Dmitry.Utils.System,
uMemory,
uTime,
uGOM,
uLogger,
uGUIDUtils,
uThreadEx,
uThreadForm;
type
TMultiCPUThread = class(TThreadEx)
private
FMode: Integer;
FSyncEvent: Integer;
FWorkingInProgress: Boolean;
FThreadNumber: Integer;
FOwner: TMultiCPUThread;
FValid: Boolean;
procedure DoMultiProcessorWork;
protected
procedure DoMultiProcessorTask; virtual; abstract;
procedure CheckThreadPriority; override;
public
constructor Create(AOwnerForm: TThreadForm; AState: TGUID);
destructor Destroy; override;
procedure StartMultiThreadWork;
property Mode: Integer read FMode write FMode;
property SyncEvent: Integer read FSyncEvent write FSyncEvent;
property WorkingInProgress: Boolean read FWorkingInProgress write FWorkingInProgress;
property Owner: TMultiCPUThread read FOwner write FOwner;
property Valid: Boolean read FValid write FValid;
end;
type
TThreadPoolCustom = class(TObject)
private
FAvaliableThreadList: TList;
FBusyThreadList: TList;
FTerminating : Boolean;
FSync: TCriticalSection;
FIsStated: Boolean;
function GetAvaliableThreadsCount: Integer;
function GetBusyThreadsCount: Integer;
protected
//
procedure ThreadsCheck(Thread: TMultiCPUThread); virtual;
procedure AddAvaliableThread(Thread: TMultiCPUThread);
procedure CheckBusyThreads;
procedure Lock;
procedure Unlock;
protected
procedure AddNewThread(Thread: TMultiCPUThread); virtual; abstract;
function GetAvaliableThread(Sender: TMultiCPUThread): TMultiCPUThread;
procedure StartThread(Sender, Thread: TMultiCPUThread);
public
constructor Create;
destructor Destroy; override;
procedure CloseAndWaitForAllThreads;
function GetBusyThreadsCountForThread(Thread: TMultiCPUThread): Integer;
property AvaliableThreadsCount : Integer read GetAvaliableThreadsCount;
property BusyThreadsCount : Integer read GetBusyThreadsCount;
end;
const
MAX_THREADS_USE = 4;
var
MultiThreadManagers : TList = nil;
implementation
{ TThreadPoolCustom }
function GUIDToString(GUID: TGUID): string;
begin
Result := Format('%d%d%d%d%d%d%d%d%d%d%d', [GUID.D1, GUID.D2, GUID.D3,
GUID.D4[0], GUID.D4[1], GUID.D4[2], GUID.D4[3], GUID.D4[4],
GUID.D4[5], GUID.D4[6], GUID.D4[7]]);
end;
procedure ValidateThread(Thread: TMultiCPUThread);
begin
if not Thread.Valid then
raise Exception.Create('Thread validation failed!');
end;
procedure TThreadPoolCustom.AddAvaliableThread(Thread: TMultiCPUThread);
begin
FBusyThreadList.Add(Thread);
Thread.FThreadNumber := FAvaliableThreadList.Count + FBusyThreadList.Count;
Thread.Valid := True;
end;
constructor TThreadPoolCustom.Create;
begin
FSync := TCriticalSection.Create;
FAvaliableThreadList := TList.Create;
FBusyThreadList := TList.Create;
FTerminating := False;
FIsStated := False;
MultiThreadManagers.Add(Self);
end;
procedure TThreadPoolCustom.CloseAndWaitForAllThreads;
var
I: Integer;
FThreads, FWaitThreads : TList;
begin;
FTerminating := True;
FThreads := TList.Create;
FWaitThreads := TList.Create;
try
//wait for all threads
while True do
begin
Sleep(10);
Application.ProcessMessages;
FSync.Enter;
try
if FAvaliableThreadList.Count + FBusyThreadList.Count + FWaitThreads.Count = 0 then
Break;
CheckBusyThreads;
//remove all avaliable thread from pool
FThreads.Assign(FAvaliableThreadList);
FAvaliableThreadList.Clear;
for I := 0 to FThreads.Count - 1 do
begin
if GOM.IsObj(FThreads[I]) then
begin
try
TMultiCPUThread(FThreads[I]).FMode := 0;
TMultiCPUThread(FThreads[I]).Priority := tpTimeCritical;
except
//thread could be finished, so SetPriority can throw an exception
end;
end;
end;
finally
FSync.Leave;
end;
//call thread to terminate
for I := 0 to FThreads.Count - 1 do
SetEvent(TMultiCPUThread(FThreads[I]).FSyncEvent);
//add thread to wait list
for I := 0 to FThreads.Count - 1 do
FWaitThreads.Add(FThreads[I]);
FThreads.Clear;
//wait for all threads using GOM
for I := 0 to FWaitThreads.Count - 1 do
begin
if not GOM.IsObj(FWaitThreads[I]) then
begin
FWaitThreads.Delete(I);
Break;
end;
end;
end;
finally
F(FThreads);
F(FWaitThreads);
end;
end;
destructor TThreadPoolCustom.Destroy;
begin
F(FSync);
F(FAvaliableThreadList);
F(FBusyThreadList);
MultiThreadManagers.Remove(Self);
inherited;
end;
function TThreadPoolCustom.GetAvaliableThread(Sender: TMultiCPUThread): TMultiCPUThread;
begin
Result := nil;
while Result = nil do
begin
if FTerminating then
Exit;
ThreadsCheck(Sender);
FSync.Enter;
try
if FAvaliableThreadList.Count > 0 then
begin
Result := FAvaliableThreadList[0];
ValidateThread(Result);
Result.WorkingInProgress := True;
FAvaliableThreadList.Remove(Result);
FBusyThreadList.Add(Result);
end;
finally
FSync.Leave;
end;
end;
end;
function TThreadPoolCustom.GetAvaliableThreadsCount: Integer;
begin
FSync.Enter;
try
Result := FAvaliableThreadList.Count;
finally
FSync.Leave;
end;
end;
function TThreadPoolCustom.GetBusyThreadsCount: Integer;
begin
FSync.Enter;
try
Result := FBusyThreadList.Count;
finally
FSync.Leave;
end;
end;
function TThreadPoolCustom.GetBusyThreadsCountForThread(
Thread: TMultiCPUThread): Integer;
var
I : Integer;
begin
FSync.Enter;
try
CheckBusyThreads;
Result := 0;
for I := 0 to FBusyThreadList.Count - 1 do
begin
ValidateThread(FBusyThreadList[I]);
if TMultiCPUThread(FBusyThreadList[I]).Owner = Thread then
Inc(Result);
end;
finally
FSync.Leave;
end;
end;
procedure TThreadPoolCustom.Lock;
begin
FSync.Enter;
end;
procedure TThreadPoolCustom.StartThread(Sender, Thread: TMultiCPUThread);
begin
ValidateThread(Thread);
Thread.WorkingInProgress := True;
Thread.FOwner := Sender;
Sender.RegisterSubThread(Thread);
TW.I.Start('Resume thread:' + IntToStr(Thread.ThreadID));
SetEvent(TMultiCPUThread(Thread).SyncEvent);
ValidateThread(Thread);
end;
procedure TThreadPoolCustom.CheckBusyThreads;
var
I: Integer;
begin
for I := FBusyThreadList.Count - 1 downto 0 do
begin
ValidateThread(FBusyThreadList[I]);
if not GOM.IsObj(FBusyThreadList[I]) then
begin
FBusyThreadList.Delete(I);
Continue;
end;
if not TMultiCPUThread(FBusyThreadList[I]).FWorkingInProgress then
begin
FAvaliableThreadList.Add(FBusyThreadList[I]);
FBusyThreadList.Delete(I);
end;
end;
end;
procedure TThreadPoolCustom.ThreadsCheck(Thread: TMultiCPUThread);
var
ThreadHandles: array [0 .. MAX_THREADS_USE - 1] of THandle;
I, ThreadsCount: Integer;
S: string;
begin
FSync.Enter;
try
AddNewThread(Thread);
finally
FSync.Leave;
end;
ThreadsCount := 0;
while FAvaliableThreadList.Count = 0 do
begin
FSync.Enter;
try
CheckBusyThreads;
if FAvaliableThreadList.Count > 0 then
Break;
ThreadsCount := FBusyThreadList.Count;
for I := 0 to ThreadsCount - 1 do
begin
ValidateThread(FBusyThreadList[I]);
ThreadHandles[I] := TMultiCPUThread(FBusyThreadList[I]).FEvent;
end;
S := 'WaitForMultipleObjects: ' + IntToStr(FBusyThreadList.Count) + ' - ';
for I := 0 to ThreadsCount - 1 do
S := S + ',' + IntToStr(TMultiCPUThread(FBusyThreadList[I]).FSyncEvent);
TW.I.Start(S);
finally
FSync.Leave;
end;
if ThreadsCount > 0 then
WaitForMultipleObjects(ThreadsCount, @ThreadHandles[0], False, IIF(FIsStated, 1000, 10));
TW.I.Start('WaitForMultipleObjects END');
end;
FIsStated := True;
end;
procedure TThreadPoolCustom.Unlock;
begin
FSync.Leave;
end;
{ TMultiCPUThread }
procedure TMultiCPUThread.CheckThreadPriority;
begin
if ThreadForm.Active then
begin
if FThreadNumber = 1 then
Priority := tpNormal
else
Priority := tpLowest
end else
Priority := tpIdle;
end;
constructor TMultiCPUThread.Create(AOwnerForm: TThreadForm; AState: TGUID);
begin
inherited Create(AOwnerForm, AState);
FSyncEvent := CreateEvent(nil, False, False, PWideChar(GUIDToString(GetGUID)));
FWorkingInProgress := True;
FMode := -1;
FValid := False;
end;
destructor TMultiCPUThread.Destroy;
begin
inherited;
end;
procedure TMultiCPUThread.DoMultiProcessorWork;
begin
while True do
begin
IsTerminated := False;
try
try
try
DoMultiProcessorTask;
TW.I.Start('UnRegisterSubThread: ' + IntToStr(FEvent));
if GOM.IsObj(ParentThread) then
ParentThread.UnRegisterSubThread(Self);
Valid := True;
if Mode = 0 then
Exit;
except
on E: Exception do
EventLog('TExplorerThread.ProcessThreadImages' + E.message);
end;
finally
TW.I.Start('SetEvent: ' + IntToStr(FEvent));
WorkingInProgress := False;
if Mode > 0 then
SetEvent(FEvent);
end;
finally
TW.I.Start('Suspended: ' + IntToStr(FEvent));
if Mode <> 0 then
WaitForSingleObject(FSyncEvent, INFINITE);
TW.I.Start('Resumed: ' + IntToStr(FEvent));
WorkingInProgress := True;
end;
end;
end;
procedure TMultiCPUThread.StartMultiThreadWork;
begin
Priority := tpIdle;
FEvent := CreateEvent(nil, False, False, PWideChar(GUIDToString(GetGUID)));
TW.I.Start('CreateEvent: ' + IntToStr(FEvent));
try
DoMultiProcessorWork;
finally
CloseHandle(FEvent);
CloseHandle(FSyncEvent);
FEvent := 0;
FSyncEvent := 0;
end;
end;
initialization
MultiThreadManagers := TList.Create;
finalization
F(MultiThreadManagers);
end.
|
unit FormConfig;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TFormConfig = class(TComponent)
private
{ Private declarations }
FSystemReadOnly : Boolean;
FAutoCodeGen : Boolean;
FIsAutoIncKey : Boolean;
FPostOnInsert : Boolean;
FConfirmCancel, FConfirmPost : Boolean;
FOperacaoDefault : Boolean;
FEntidadeNome : String;
FAutoIncField : String;
FEntidadeMasculina : Boolean;
FHiddenPostOnInsert : Boolean;
FUniqueFields, FRequiredFields, FDependentTables, FDependentTableKeys : TStringList;
procedure SetRequiredFields(Value : TStringList);
procedure SetUniqueFields(Value : TStringList);
procedure SetDependentTables(Value : TStringList);
procedure SetDependentTableKeys(Value : TStringList);
protected
{ Protected declarations }
destructor Destroy; override;
constructor Create(AOwner: TComponent); override;
public
{ Public declarations }
published
{ Published declarations }
property AutoCodeGen : Boolean read FAutoCodeGen write FAutoCodeGen default True;
property IsAutoIncKey : Boolean read FIsAutoIncKey write FIsAutoIncKey;
property SystemReadOnly : Boolean read FSystemReadOnly write FSystemReadOnly default True;
property PostOnInsert : Boolean read FPostOnInsert write FPostOnInsert default False;
property ConfirmPost : Boolean read FConfirmPost write FConfirmPost default True;
property ConfirmCancel : Boolean read FConfirmCancel write FConfirmCancel default True;
property OperacaoDefault : Boolean read FOperacaoDefault write FOperacaoDefault;
property EntidadeNome : String read FEntidadeNome write FEntidadeNome;
property AutoIncField : String read fAutoIncField write fAutoIncField;
property EntidadeMasculina : Boolean read FEntidadeMasculina write FEntidadeMasculina default True;
property RequiredFields : TStringList read FRequiredFields write SetRequiredFields;
property UniqueFields : TStringList read FUniqueFields write SetUniqueFields;
property DependentTables : TStringList read FDependentTables write SetDependentTables;
property DependentTableKeys : TStringList read FDependentTableKeys write SetDependentTableKeys;
property HiddenPostOnInsert : Boolean read FHiddenPostOnInsert write FHiddenPostOnInsert default True;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NewPower', [TFormConfig]);
end;
constructor TFormConfig.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSystemReadOnly := True;
FPostOnInsert := False;
FConfirmCancel := True;
FConfirmPost := True;
FAutoCodeGen := True;
FEntidadeNome := '';
FEntidadeMasculina := True;
FRequiredFields := TStringList.Create;
FUniqueFields := TStringList.Create;
FDependentTables := TStringList.Create;
FDependentTableKeys := TStringList.Create;
end;
destructor TFormConfig.Destroy;
begin
FRequiredFields.Free;
FUniqueFields.Free;
FDependentTables.Free;
FDependentTableKeys.Free;
inherited Destroy;
end;
procedure TFormConfig.SetRequiredFields(Value : TStringList);
begin
if FRequiredFields <> Value then
FRequiredFields.Assign(Value);
end;
procedure TFormConfig.SetUniqueFields(Value : TStringList);
begin
if FUniqueFields <> Value then
FUniqueFields.Assign(Value);
end;
procedure TFormConfig.SetDependentTables(Value : TStringList);
begin
if FDependentTables <> Value then
FDependentTables.Assign(Value);
end;
procedure TFormConfig.SetDependentTableKeys(Value : TStringList);
begin
if FDependentTableKeys <> Value then
FDependentTableKeys.Assign(Value);
end;
end.
|
namespace TestApplication;
uses
RemObjects.Elements.EUnit;
type
AssertExtension = public extension class(BaseAsserts)
private
protected
public
method assertNotNull(value : Object); inline;
begin
IsNotNil(value);
end;
method assertTrue(value : Boolean);
begin
IsTrue(value);
end;
method assertFalse(value : Boolean);
begin
IsFalse(value);
end;
method assertEquals(Expected: Double; Actual: Double; Precision: Double);
begin
AreEqual(Actual, Expected, Precision);
end;
method assertEquals(Expected: Integer; Actual: Integer);
begin
AreEqual(Actual, Expected);
end;
method assertEquals(Expected: String; Actual: String);
begin
AreEqual(Actual, Expected);
end;
end;
end. |
unit backup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
type
Tbackupfrm = class(TForm)
Label1: TLabel;
GroupBox1: TGroupBox;
Label2: TLabel;
SpeedButton1: TSpeedButton;
Label3: TLabel;
Path_Edit: TEdit;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
OpenDialog1: TOpenDialog;
procedure SpeedButton1Click(Sender: TObject);
function BackupFile: Boolean;
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
backupfrm: Tbackupfrm;
implementation
{$R *.dfm}
procedure Tbackupfrm.SpeedButton1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
Path_Edit.Text := OpenDialog1.FileName;
end;
end;
function Tbackupfrm.BackupFile: Boolean;
var
ExePath: string;
begin
ExePath := ExtractFilePath(Application.ExeName);
if Path_Edit.Text = '' then
begin
Application.MessageBox('选择备份路径及文件名!', '提示', Mb_ok or Mb_IconWarning);
Exit;
end;
if FileExists(Path_Edit.Text) then
begin
if Application.MessageBox('是否覆盖原来的文件?', '提示', Mb_YesNo or Mb_Iconquestion) = idyes then
try
DeleteFile(Path_Edit.Text);
except
end;
end;
try
CopyFile(Pchar(ExePath + 'mdb\' + 'JXCGL.mdb'), Pchar(Path_Edit.Text), False);
Result := True;
Application.MessageBox('备份成功!', '提示', Mb_ok or Mb_Iconinformation);
except
Result := False;
Application.MessageBox('备份失败!', '提示', Mb_ok or Mb_Iconerror);
end;
end;
procedure Tbackupfrm.BitBtn1Click(Sender: TObject);
begin
BackupFile;
end;
procedure Tbackupfrm.BitBtn2Click(Sender: TObject);
begin
Hide;
end;
end.
|
{
@abstract(Provides Format 2.0 highlighters import and export)
@authors(Vitalik [2vitalik@gmail.com], Quadr0 [quadr02005@gmail.com])
@created(2005)
@lastmod(2006-06-30)
}
{$IFNDEF QSynUniFormatNativeXml20}
unit SynUniFormatNativeXml20;
{$ENDIF}
{$I SynUniHighlighter.inc}
interface
uses
{$IFDEF SYN_CLX}
QClasses,
QGraphics,
QSynUniFormat,
QSynUniClasses,
QSynUniRules,
QSynUniHighlighter
{$ELSE}
Classes,
Graphics,
{$IFDEF SYN_COMPILER_6_UP}
Variants,
{$ENDIF}
SynUniFormat,
SynUniFormatNativeXml,
SynUniClasses,
SynUniRules,
SynUniHighlighter,
{$IFDEF CODEFOLDING}
SynEditCodeFolding,
{$ENDIF}
{$ENDIF}
SysUtils,
{ XMLIntf; } // DW
SimpleXML;
type
TSynUniFormatNativeXml20 = class(TSynUniFormatNativeXml)
class function ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; override;
class function ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; override;
class function ImportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; override;
class function ExportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; override;
class function ImportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; override;
class function ExportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; override;
class function ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; override;
class function ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; override;
class function ImportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean; override;
class function ExportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean; override;
class function ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; override;
class function ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; override;
class function ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; override;
class function ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; override;
class function ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; override;
class function ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; override;
class function ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
class function ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
class function ImportFromStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ExportToStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ImportFromFile(AObject: TObject; AFileName: string): Boolean; override;
class function ExportToFile(AObject: TObject; AFileName: string): Boolean; override;
end;
implementation
{$IFDEF CODEFOLDING}
procedure ImportCodeFolding(AFoldRegions: TFoldRegions; ANodeList: IXMLNodeList{; ParentRegion: TFoldRegionItem = nil});
var
i: integer;
NewRegion: TFoldRegionItem;
// FoldRegionList: TFoldRegions;
begin
{ if ParentRegion = nil then
FoldRegionList := FoldRegions
else
FoldRegionList := ParentRegion.SubFoldRegions;}
for i := 0 to ANodeList.Count - 1 do
begin
with ANodeList.Item[i] do begin
NewRegion := AFoldRegions.Add(
TFoldRegionType(GetIntAttr('Type')),
EnsureChild('Properties').GetBoolAttr('AddEnding'),
EnsureChild('Properties').GetBoolAttr('AllowNoSubs'),
EnsureChild('Properties').GetBoolAttr('WholeWords'),
PChar(EnsureChild('OpenToken').GetAttr('Symbol')), //PChar
PChar(EnsureChild('CloseToken').GetAttr('Symbol'))); //PChar
with NewRegion do begin
Name := GetAttr('Name');
RegExpOpen := PChar(EnsureChild('OpenToken').GetAttr('RegExpr')); //PChar
RegExpClose := PChar(EnsureChild('CloseToken').GetAttr('RegExpr')); //PChar
RegExpUseOpen := EnsureChild('OpenToken').GetBoolAttr('UseRegExpr');
RegExpUseClose := EnsureChild('CloseToken').GetBoolAttr('UseRegExpr');
end;
ImportCodeFolding(NewRegion.SubFoldRegions, EnsureChild('SubRegions').ChildNodes);
end
end
end;
procedure ExportCodeFolding(AFoldRegions: TFoldRegions; ParentNode: IXMLNode{; ARegion: TFoldRegionItem});
var
i: integer;
NewNode: IXMLNode;
// FoldRegionList: TFoldRegions;
begin
{ if ARegion = nil then
FoldRegionList := FoldRegions
else
FoldRegionList := ARegion.SubFoldRegions;}
for i := 0 to AFoldRegions.Count - 1 do
begin
NewNode := ParentNode.AppendElement('FoldRegion');
with NewNode, AFoldRegions.Items[i] do
begin
SetVarAttr('Name',Name);
SetVarAttr('Type',Ord(FoldRegionType));
with AppendElement('OpenToken') do
begin
if StrLen(Open) > 0 then
SetVarAttr('Symbol', string(Open));
if StrLen(RegExpOpen) > 0 then
SetVarAttr('RegExpr', string(RegExpOpen));
if RegExpUseOpen then
SetVarAttr('UseRegExpr', BoolToStr(RegExpUseOpen, True));
end;
with AppendElement('CloseToken') do
begin
if StrLen(Close) > 0 then
SetVarAttr('Symbol', string(Close));
if StrLen(RegExpClose) > 0 then
SetVarAttr('RegExpr', string(RegExpClose));
if RegExpUseClose then
SetVarAttr('UseRegExpr', BoolToStr(RegExpUseClose, True));
end;
with AppendElement('Properties') do
begin
if AddEnding then
SetVarAttr('AddEnding', BoolToStr(AddEnding, True));
if NoSubFoldRegions then
SetVarAttr('AllowNoSubs', BoolToStr(NoSubFoldRegions, True));
if WholeWords then
SetVarAttr('WholeWords', BoolToStr(WholeWords, True));
end;
ExportCodeFolding(AFoldRegions.Items[i].SubFoldRegions, AppendElement('SubRegions'));
end;
end;
end;
{$ENDIF}
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
begin
with ANode do
begin
with AInfo.General, EnsureChild('General') do begin
Name := VarToStr(GetVarAttr('Name',''));
Extensions := VarToStr(GetVarAttr('Extensions',''));
Version := VarToInt(GetVarAttr('Version',''));
Revision := VarToInt(GetVarAttr('Revision',''));
Sample := VarToStr(GetVarAttr('Sample',''));
History := VarToStr(GetVarAttr('History',''));
end;
with AInfo.Author, EnsureChild('Author') do begin
Name := VarToStr(GetVarAttr('Name',''));
Email := VarToStr(GetVarAttr('Mail','')); //TODO: Переименовать обратно в 'Email', блин...
Web := VarToStr(GetVarAttr('Web',''));
Copyright := VarToStr(GetVarAttr('Copyright',''));
Company := VarToStr(GetVarAttr('Company',''));
Remark := VarToStr(GetVarAttr('Remark',''));
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
begin
with AInfo, ANode do
begin
with General, AppendElement('General') do
begin
SetVarAttr('Name',Name);
SetVarAttr('Extensions',Extensions);
SetVarAttr('Version',Version);
SetVarAttr('Revision',Revision);
SetVarAttr('Sample',Sample);
SetVarAttr('History',History);
end;
with Author, AppendElement('Author') do
begin
SetVarAttr('Name',Name);
SetVarAttr('Mail',Email); //TODO: Переименовать обратно в 'Email', блин...
SetVarAttr('Web',Web);
SetVarAttr('Copyright',Copyright);
SetVarAttr('Company',Company);
SetVarAttr('Remark',Remark);
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean;
begin
with AEditorProperties, ANode do
begin
ActiveLineColor := VarToColor(GetVarAttr('ActiveLineColor',''), clNone);
SelectedForeground := VarToColor(GetVarAttr('SelectedForeground',''), clHighlightText);
SelectedBackground := VarToColor(GetVarAttr('SelectedBackground',''), clHighlight);
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean;
begin
with AEditorProperties, ANode do
begin
if ActiveLineColor <> clNone then
SetVarAttr('ActiveLineColor',ColorToString(ActiveLineColor));
if SelectedForeground <> clHighlightText then
SetVarAttr('SelectedForeground',ColorToString(SelectedForeground));
if SelectedBackground <> clHighlight then
SetVarAttr('SelectedBackground',ColorToString(SelectedBackground));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean;
begin
with Attributes, ANode do
begin
ParentForeground := False; // Нужно ли?..
ParentBackground := False;
Foreground := VarToColor(GetVarAttr('Foreground',''), clWindowText);
Background := VarToColor(GetVarAttr('Background',''), clWindow);
ParentForeground := VarToBool(GetVarAttr('ParentForeground',''));
ParentBackground := VarToBool(GetVarAttr('ParentBackground',''));
Style := StrToFontStyle(VarToStr(GetVarAttr('Style','')));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean;
begin
with Attributes, ANode do begin
SetVarAttr('Foreground',ColorToString(Foreground));
SetVarAttr('Background',ColorToString(Background));
if ParentForeground then
SetVarAttr('ParentForeground', BoolToStr(ParentForeground, True));
if ParentBackground then
SetVarAttr('ParentBackground', BoolToStr(ParentBackground, True));
if Style <> [] then
SetVarAttr('Style',FontStyleToStr(Style));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
var
i, j: integer;
NewScheme: TSynScheme;
NewStyle: TSynAttributes;
begin
with ASchemes, ANode.ChildNodes do
begin
Clear();
for i := 0 to Count - 1 do
begin
NewScheme := AddScheme(VarToStr(Item[i].GetVarAttr('Name','')));
ImportEditorProperties(NewScheme.EditorProperties, Item[i].EnsureChild('Editor'));
with Item[i].EnsureChild('Styles').ChildNodes do
for j := 0 to Count - 1 do
begin
NewStyle := NewScheme.AddStyle(VarToStr(Item[j].GetVarAttr('Name','')),
clWindowText, clWindow, StrToFontStyle(''));
ImportAttributes(NewStyle, Item[j]);
end;
end;
//SetScheme(GetSchemeName('Default'));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
var
i, j: integer;
NewNode: IXMLNode;
begin
with ASchemes do begin
for i := 0 to Count - 1 do
with ANode.AppendElement('Scheme') do
begin
SetVarAttr('Name',Schemes[i].Name);
ExportEditorProperties(Schemes[i].EditorProperties, AppendElement('Editor'));
with AppendElement('Styles') do
for j := 0 to Schemes[i].Count - 1 do
begin
NewNode := AppendElement('Style');
NewNode.SetVarAttr('Name',Schemes[i].Styles[j].Name);
ExportAttributes(Schemes[i].Styles[j], NewNode);
end;
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
begin
with AKeyList, ANode do
begin
Name := VarToStr(GetVarAttr('Name',''));
Enabled := VarToBool(GetVarAttr('Enabled',''), True);
Style := VarToStr(GetVarAttr('Style',''));
KeyList.Text := VarToStr(GetVarAttr('Words',''));
ImportAttributes(AKeyList.Attributes, EnsureChild('Attributes'));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
begin
with AKeyList, ANode do
begin
ANode.SetVarAttr('Name',Name);
ANode.SetVarAttr('Enabled', BoolToStr(Enabled, True));
ANode.SetVarAttr('Style',Style);
ANode.SetVarAttr('Words',KeyList.Text);
ExportAttributes(AKeyList.Attributes, AppendElement('Attributes'));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin
with ASet, ANode do
begin
Name := VarToStr(GetVarAttr('Name',''));
Enabled := VarToBool(GetVarAttr('Enabled',''), True);
Style := VarToStr(GetVarAttr('Style',''));
CharSet := VarToSet(GetVarAttr('Symbols',''));
Quantity := VarToInt(GetVarAttr('Quantity',''));
ImportAttributes(ASet.Attributes, EnsureChild('Attributes'));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin
with ASet, ANode do
begin
SetVarAttr('Name', Name);
SetVarAttr('Enabled', BoolToStr(Enabled, True));
SetVarAttr('Style', Style);
SetVarAttr('Symbols', SetToStr(CharSet));
SetVarAttr('Quantity', IntToStr(Quantity));
ExportAttributes(ASet.Attributes, AppendElement('Attributes'));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean;
begin
with AToken, ANode do
begin
Clear();
FinishOnEol := VarToBool(GetVarAttr('FinishOnEol',''));
StartLine := StrToStartLine(VarToStr(GetVarAttr('StartLine','')));
StartType := StrToStartType(VarToStr(GetVarAttr('PartOfTerm','')));
BreakType := StrToBreakType(VarToStr(GetVarAttr('PartOfTerm','')));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportToken(AToken: TSynMultiToken; ANode: IXMLNode): Boolean;
begin
with AToken, ANode do
begin
if FinishOnEol then SetVarAttr('FinishOnEol', BoolToStr(FinishOnEol, True));
SetVarAttr('StartLine', StartLineToStr(StartLine));
if (StartType = stTerm) and (BreakType = btTerm) then
SetVarAttr('PartOfTerm','False')
else if (StartType = stAny) and (BreakType = btTerm) then
SetVarAttr('PartOfTerm','Left')
else if (StartType = stTerm) and (BreakType = btAny) then
SetVarAttr('PartOfTerm','Right');
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
var
i: integer;
NewRange: TSynRange;
NewKeyList: TSynKeyList;
NewSet: TSynSet;
begin
with ARange, ANode do begin
Clear;
Name := VarToStr(GetVarAttr('Name',''));
Enabled := VarToBool(GetVarAttr('Enabled',''), True);
CaseSensitive := VarToBool(GetVarAttr('CaseSensitive',''));
Style := VarToStr(GetVarAttr('Style',''));
Delimiters := VarToSet(EnsureChild('Delimiters').GetVarAttr('Value',''));
ImportAttributes(ARange.Attributes, EnsureChild('Attributes'));
//TODO: if mainrules then exit, хо? уж?врод??та?работает :)
with EnsureChild('Properties') do
begin
CloseOnEol := VarToBool(GetVarAttr('CloseOnEol',''));
CloseOnTerm := VarToBool(GetVarAttr('CloseOnTerm',''));
AllowPreviousClose := VarToBool(GetVarAttr('AllowPredClose',''));
end;
ImportToken(OpenToken, EnsureChild('OpenToken'));
ImportToken(CloseToken, EnsureChild('CloseToken'));
with EnsureChild('MultiTokens') do
for i := 0 to ChildNodes.Count-1 do
with ChildNodes[i] do
AddCoupleTokens(VarToStr(GetVarAttr('Open','')), VarToStr(GetVarAttr('Close','')));
{Sub rules}
with EnsureChild('SubRules').ChildNodes do
begin
for i := 0 to Count-1 do
begin
if Item[i].NodeName = 'Range' then
begin
NewRange := TSynRange.Create;
ImportRange(NewRange, Item[i]);
AddRange(NewRange);
end
else if Item[i].NodeName = 'KeyList' then
begin
NewKeyList := TSynKeyList.Create();
ImportKeyList(NewKeyList, Item[i]);
AddKeyList(NewKeyList);
end
else if Item[i].NodeName = 'Set' then
begin
NewSet := TSynSet.Create();
ImportSet(NewSet, Item[i]);
AddSet(NewSet);
end;
end;
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
var
i: integer;
begin
with ARange, ANode do
begin
SetVarAttr('Name',Name);
if not Enabled then
SetVarAttr('Enabled', BoolToStr(Enabled, True));
if CaseSensitive then
SetVarAttr('CaseSensitive', BoolToStr(CaseSensitive, True));
SetVarAttr('Style',Style);
ExportAttributes(ARange.Attributes, AppendElement('Attributes'));
with AppendElement('Delimiters') do
SetVarAttr('Value',SetToStr(Delimiters));
if ANode.NodeName <> 'MainRules' then
begin
ExportToken(OpenToken, AppendElement('OpenToken'));
ExportToken(CloseToken, AppendElement('CloseToken'));
with AppendElement('Properties') do
begin
if CloseOnTerm then
SetVarAttr('CloseOnTerm', BoolToStr(CloseOnTerm, True));
if CloseOnEol then
SetVarAttr('CloseOnEol', BoolToStr(CloseOnEol, True));
if AllowPreviousClose then
SetVarAttr('AllowPredClose', BoolToStr(AllowPreviousClose, True));
end;
with AppendElement('MultiTokens') do
for i := 0 to OpenToken.SymbolCount-1 do
with AppendElement('Tokens') do
begin
if OpenToken.Symbols[i] <> '' then
SetVarAttr('Open',OpenToken.Symbols[i]);
if CloseToken.Symbols[i] <> '' then
SetVarAttr('Close',CloseToken.Symbols[i]);
end;
end;
with AppendElement('SubRules') do begin
for i := 0 to RangeCount -1 do
ExportRange(Ranges[i], AppendElement('Range'));
for i := 0 to KeyListCount -1 do
ExportKeyList(KeyLists[i], AppendElement('KeyList'));
for i := 0 to SetCount -1 do
ExportSet(Sets[i], AppendElement('Set'));
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin
//TODO: Insert try..except
with ANode, SynUniSyn do
begin
Clear();
with EnsureChild('SyntaxColoring') do begin
ImportInfo(Info, EnsureChild('Info'));
ImportSchemes(Schemes, EnsureChild('Schemes'));
//# если убират?эт?строку, то перестанет работать. Замени её на чт?нить правильное ;-)
SynUniSyn.ActiveScheme := Schemes.GetSchemeName('Default');
ImportEditorProperties(EditorProperties, EnsureChild('Editor'));
ImportRange(MainRules, EnsureChild('MainRules'));
end;
{$IFDEF CODEFOLDING}
ImportCodeFolding(FoldRegions, EnsureChild('CodeFolding').ChildNodes); //###
{$ENDIF}
FormatVersion := '2.0';
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin
ANode.SetVarAttr('Version', '2.0');
with SynUniSyn do
begin
with ANode.AppendElement('SyntaxColoring') do
begin
ExportInfo(Info, AppendElement('Info'));
ExportSchemes(Schemes, AppendElement('Schemes'));
ExportEditorProperties(EditorProperties, AppendElement('Editor'));
ExportRange(MainRules, AppendElement('MainRules'));
end;
{$IFDEF CODEFOLDING}
ExportCodeFolding(FoldRegions, ANode.AppendElement('CodeFolding'));
{$ENDIF}
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportFromStream(AObject: TObject; AStream: TStream): Boolean;
begin
Result := inherited ImportFromStream(AObject, AStream);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportToStream(AObject: TObject; AStream: TStream): Boolean;
begin
Result := inherited ExportToStream(AObject, AStream);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ImportFromFile(AObject: TObject; AFileName: string): Boolean;
begin
Result := inherited ImportFromFile(AObject, AFileName);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml20.ExportToFile(AObject: TObject; AFileName: string): Boolean;
begin
Result := inherited ExportToFile(AObject, AFileName);
end;
end.
|
unit callstack;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
procedure DumpCallStack;
implementation
uses
logoutput;
procedure DumpCallStack;
var
I: Longint;
prevbp: Pointer;
CallerFrame,
CallerAddress,
bp: Pointer;
Report: string;
const
MaxDepth = 20;
begin
Report := '';
bp := get_frame;
// This trick skip SendCallstack item
// bp:= get_caller_frame(get_frame);
try
prevbp := bp - 1;
I := 0;
while bp > prevbp do begin
CallerAddress := get_caller_addr(bp);
CallerFrame := get_caller_frame(bp);
if (CallerAddress = nil) then
Break;
Report := Report + BackTraceStrFunc(CallerAddress) + LineEnding;
Inc(I);
if (I >= MaxDepth) or (CallerFrame = nil) then
Break;
prevbp := bp;
bp := CallerFrame;
end;
except
{ prevent endless dump if an exception occured }
end;
log(Report);
end;
end.
|
unit UCidade;
interface
uses UEstado;
type
TCidade = class
private
protected
FIdCidade:Integer;
FCidade:String;
FDataCadastro:String;
FDataAlteracao:String;
FEstado:TEstado;
public
constructor Create;
destructor Destroy;
procedure setIdCidade(vIdCidade:Integer);
procedure setCidade(VCidade:String);
procedure setDataCadastro(vDataCadastro:String);
procedure setDataAlteracao(vDataAlteracao:String);
procedure setEstado(vEstado:TEstado);
function getIdCidade:Integer;
function getCidade:String;
function getDataCadastro:String;
function getDataAlteracao:String;
function getEstado:TEstado;
property IdCidade:Integer read getIdCidade write setIdCidade;
property Cidade:String read getCidade write setCidade;
property DataCadastro:String read getDataCadastro write setDataCadastro;
property DataAlteracao:String read getDataCadastro write setDataAlteracao;
property Estado:TEstado read getEstado write setEstado;
end;
implementation
{ TCidade }
constructor TCidade.Create;
begin
FIdCidade:=0;
FCidade:='';
FDataCadastro:='';
FDataAlteracao:='';
FEstado:=TEstado.Create;
end;
destructor TCidade.Destroy;
begin
FEstado.Destroy;
end;
function TCidade.getCidade: String;
begin
Result:=FCidade;
end;
function TCidade.getDataAlteracao: String;
begin
Result:=FDataAlteracao;
end;
function TCidade.getDataCadastro: String;
begin
Result:=FDataCadastro;
end;
function TCidade.getEstado:TEstado;
begin
Result:=FEstado;
end;
function TCidade.getIdCidade: Integer;
begin
Result:=FIdCidade;
end;
procedure TCidade.setCidade(VCidade: String);
begin
FCidade:=VCidade;
end;
procedure TCidade.setDataAlteracao(vDataAlteracao: String);
begin
FDataAlteracao:=vDataAlteracao;
end;
procedure TCidade.setDataCadastro(vDataCadastro: String);
begin
FDataCadastro:=vDataCadastro;
end;
procedure TCidade.setEstado(vEstado: TEstado);
begin
FEstado:=vEstado;
end;
procedure TCidade.setIdCidade(vIdCidade: Integer);
begin
FIdCidade:=vIdCidade;
end;
end.
|
unit ThItemCommand;
interface
uses
FMX.Types, System.Types, System.SysUtils, FMX.Controls,
ThTypes, ThClasses, ThItem, System.Generics.Collections;
type
TUpdateState = record
Item: TThItem;
Parent, BeforeParent: TFmxObject;
Index, BeforeIndex: Integer;
public
constructor Create(AItem: TThItem);
end;
TThItemCommand = class(TInterfacedObject, IThCommand)
private
procedure UpdateState;
protected
FItems: TThItems;
FUpdateStateItems: TList<TUpdateState>;
public
constructor Create(AItem: TThItem); overload;
constructor Create(AItems: TThItems); overload;
destructor Destroy; override;
procedure Execute; virtual; abstract; // BeforeParent로 처리
procedure Rollback; virtual; abstract; // ItemHistory에서 Parent 찾기
end;
TThCommandItemAdd = class(TThItemCommand)
private
FParent: TControl;
public
constructor Create(AParent: TControl; AItem: TThItem); overload;
procedure Execute; override;
procedure Rollback; override;
property Items: TThItems read FItems;
end;
TThCommandItemDelete = class(TThItemCommand)
private
FParent: TControl;
public
constructor Create(AParent: TControl; AItems: TThItems); overload;
procedure Execute; override;
procedure Rollback; override;
end;
TThCommandItemMove = class(TThItemCommand)
private
FDistance: TPointF;
public
constructor Create(AItems: TThItems; ADistance: TPointF); overload;
destructor Destroy; override;
procedure Execute; override;
procedure Rollback; override;
end;
TThCommandItemResize = class(TThItemCommand)
private
FBeforeRect,
FAfterRect: TRectF;
public
constructor Create(AItem: TThItem; ABeforeRect: TRectF); overload;
procedure Execute; override;
procedure Rollback; override;
end;
implementation
uses
ThCanvasEditor;
{ TThAbstractCommandItem }
constructor TThItemCommand.Create(AItems: TThItems);
begin
FItems := TThItems.Create(AItems);
UpdateState;
end;
constructor TThItemCommand.Create(AItem: TThItem);
begin
FItems := TThitems.Create;
FItems.Add(AItem);
UpdateState;
end;
destructor TThItemCommand.Destroy;
begin
FItems.Free;
if Assigned(FUpdateStateItems) then
FUpdateStateItems.Free;
inherited;
end;
procedure TThItemCommand.UpdateState;
var
Item, Child: TThItem;
begin
FUpdateStateItems := TList<TUpdateState>.Create;
for Item in FItems do
begin
if Item.Parent <> Item.BeforeParent then
begin
FUpdateStateItems.Add(TUpdateState.Create(Item));
Item.BeforeParent := Item.Parent;
end;
for Child in Item.LastContainItems do
begin
if Child.Parent <> Child.BeforeParent then
begin
FUpdateStateItems.Add(TUpdateState.Create(Child));
Child.BeforeParent := Child.Parent;
end;
end;
end;
end;
{ TThCommandItemAdd }
constructor TThCommandItemAdd.Create(AParent: TControl; AItem: TThItem);
begin
inherited Create(AItem);
FParent := AParent;
end;
procedure TThCommandItemAdd.Execute;
var
Item: TThItem;
UpdateState: TUpdateState;
begin
for UpdateState in FUpdateStateItems do
UpdateState.Parent.InsertObject(UpdateState.Index, UpdateState.Item);
for Item in FItems do
Item.Selected := True;
end;
procedure TThCommandItemAdd.Rollback;
var
Item: TThItem;
UpdateState: TUpdateState;
begin
for UpdateState in FUpdateStateItems do
UpdateState.BeforeParent.InsertObject(UpdateState.BeforeIndex, UpdateState.Item);
for Item in FItems do
begin
Item.Selected := False;
Item.Parent := nil;
end;
end;
{ TThCommandItemDelete }
constructor TThCommandItemDelete.Create(AParent: TControl; AItems: TThItems);
begin
inherited Create(AItems);
FParent := AParent;
end;
procedure TThCommandItemDelete.Execute;
var
Item: TThItem;
UpdateState: TUpdateState;
begin
for UpdateState in FUpdateStateItems do
begin
UpdateState.Item.Parent := UpdateState.Parent;
UpdateState.Item.Index := UpdateState.Index;
end;
for Item in FItems do
begin
Item.Parent := nil;
Item.Selected := False;
end;
end;
procedure TThCommandItemDelete.Rollback;
var
Item: TThItem;
Canvas: TThCanvasEditor;
UpdateState: TUpdateState;
begin
for UpdateState in FUpdateStateItems do
UpdateState.BeforeParent.InsertObject(UpdateState.BeforeIndex, UpdateState.Item);
Canvas := TThCanvasEditor(FParent);
Canvas.ClearSelection;
Canvas.BeginSelect;
try
for Item in FItems do
Item.Selected := True;
finally
Canvas.EndSelect;
end;
end;
{ TThCommandItemMove }
constructor TThCommandItemMove.Create(AItems: TThItems; ADistance: TPointF);
begin
inherited Create(AItems);
FDistance := ADistance;
end;
destructor TThCommandItemMove.Destroy;
begin
inherited;
end;
procedure TThCommandItemMove.Execute;
var
Item: TThItem;
UpdateState: TUpdateState;
begin
for Item in FItems do
Item.Position.Point := Item.Position.Point + FDistance;
for UpdateState in FUpdateStateItems do
UpdateState.Parent.InsertObject(UpdateState.Index, UpdateState.Item);
end;
procedure TThCommandItemMove.Rollback;
var
Item: TThItem;
UpdateState: TUpdateState;
begin
for UpdateState in FUpdateStateItems do
UpdateState.BeforeParent.InsertObject(UpdateState.BeforeIndex, UpdateState.Item);
for Item in FItems do
Item.Position.Point := Item.Position.Point - FDistance;
end;
{ TThCommandItemResize }
constructor TThCommandItemResize.Create(AItem: TThItem; ABeforeRect: TRectF);
begin
inherited Create(AItem);
FBeforeRect := ABeforeRect;
FAfterRect := AItem.BoundsRect;
FAfterRect.Offset(AItem.Position.Point);
end;
procedure TThCommandItemResize.Execute;
var
UpdateState: TUpdateState;
Item: TThItem;
ItemContainer: IThItemContainer;
begin
for UpdateState in FUpdateStateItems do
UpdateState.Parent.InsertObject(UpdateState.Index, UpdateState.Item);
for Item in FItems do
begin
Item.SetBounds(FAfterRect.Left, FAfterRect.Top, FAfterRect.Width, FAfterRect.Height);
Item.RealignSpot;
Item.ReleaseChildren;
if Supports(Item.Parent, IThItemContainer, ItemContainer) then
ItemContainer.ContainChildren(Item);
end;
end;
procedure TThCommandItemResize.Rollback;
var
UpdateState: TUpdateState;
Item: TThItem;
ItemContainer: IThItemContainer;
begin
for UpdateState in FUpdateStateItems do
UpdateState.BeforeParent.InsertObject(UpdateState.BeforeIndex, UpdateState.Item);
for Item in FItems do
begin
Item.SetBounds(FBeforeRect.Left, FBeforeRect.Top, FBeforeRect.Width, FBeforeRect.Height);
Item.RealignSpot;
Item.ReleaseChildren;
if Supports(Item.Parent, IThItemContainer, ItemContainer) then
ItemContainer.ContainChildren(Item);
end;
end;
{ TUpdateData }
constructor TUpdateState.Create(AItem: TThItem);
begin
Item := AItem;
BeforeParent := AItem.BeforeParent;
Parent := AItem.Parent;
BeforeIndex := AItem.BeforeIndex;
Index := AItem.Index;
end;
end.
|
// TaskMaster
{: Provides Task management and scheduling services.<p>
<b>History : </b><font size=-1><ul>
<li>15/11/05 - EG - Creation
</ul></font>
}
unit TaskMaster;
interface
uses Windows, Classes, SysUtils;
type
// TTaskInfo
//
{: Descibes a task to be scheduled by a TaskMaster. }
TTaskInfo = class (TObject)
private
{ Private Declarations }
FSessionID : Cardinal;
FExecuting, FCompleted, FAborted : Boolean;
FOnExecute : TNotifyEvent;
FSender : TObject;
FMasterTask : TTaskInfo;
FLastRunTime : Int64;
FSubTasks : array of TTaskInfo;
FSubTaskCount : Integer;
FSubTasksLock : TRTLCriticalSection;
protected
{ Protected Declarations }
//: Notify task info it has been scheduled
procedure Schedule(masterTask : TTaskInfo);
//: Notify task info it has been started
procedure Start;
//: Notify task info it has stopped
procedure Stop;
//: Notify task info is has been aborted
procedure Abort;
//: Register a subtask
procedure RegisterSubTask(subTask : TTaskInfo);
//: Clear list of all subtasks
procedure ClearSubTasks;
public
{ Public Declarations }
constructor Create(eventOnExecute : TNotifyEvent; aSender : TObject);
destructor Destroy; override;
//: Last SessionID upon which this taskInfo was scheduled
property SessionID : Cardinal read FSessionID;
//: Event to execute to perform the task
property OnExecute : TNotifyEvent read FOnExecute write FOnExecute;
//: Parameter value for the execution event
property Sender : TObject read FSender write FSender;
//: Task whose completion is required to execute current task
property MasterTask : TTaskInfo read FMasterTask;
{: Returns true if this task has been scheduled for last/current session.<p>
Returned value is independant from wether the task has been completed
or not, or wether the session has completed or not. }
function Scheduled : Boolean;
{: Returns true if the task is currently executing. }
function Executing : Boolean;
{: Returns true if the task has been completed for last/current session.<p>
If the task hasn't been scheduled for last/current session, returns True. }
function Completed : Boolean;
{: Returns true if the task has been aborted for last/current session.<p>
If the task hasn't been scheduled for last/current session, returns False. }
function Aborted : Boolean;
end;
// TTaskMaster
//
{: Abstract TaskMaster class.<p>
Only one TaskMaster may be instantiated at any time, which is referred
in the vTaskMaster variable (note: this *may* be relaxed in the future,
though there will still be only one global TaskMaster) }
TTaskMaster = class (TObject)
private
{ Private Declarations }
FSessionID : Cardinal;
FSessionCount : Integer;
protected
{ Protected Declarations }
procedure ValidateThreadID;
public
{ Public Declarations }
constructor Create; virtual;
destructor Destroy; override;
//: Initiates a new execution session, during which tasks will be scheduled and executed
procedure BeginSession; virtual;
//: End an execution session, waits for completion of all tasks
procedure EndSession; virtual;
//: Terminate an execution session (ungracefully)
procedure AbortSession; virtual;
//: Is there an active execution session?
function InSession : Boolean;
//: Current session ID, valid only if InSession
property SessionID : Cardinal read FSessionID;
//: Schedule a task, specifying an optional dependency
procedure ScheduleTask(aTask : TTaskInfo;
dependsOnTask : TTaskInfo = nil); virtual; abstract;
{: Wait for the task to reach Completed or Aborted status. }
procedure WaitFor(aTask : TTaskInfo); virtual; abstract;
end;
// TSingleThreadedTaskMaster
//
{: A TaskMaster for single threaded usage.<p>
This implementation isn't threaded at all, every task is executed as
it is specified. }
TSingleThreadedTaskMaster = class (TTaskMaster)
private
{ Private Declarations }
protected
{ Protected Declarations }
public
{ Public Declarations }
procedure ScheduleTask(aTask : TTaskInfo; dependsOnTask : TTaskInfo = nil); override;
procedure WaitFor(aTask : TTaskInfo); override;
end;
ETaskMasterException = class(Exception);
function GlobalTaskMaster : TTaskMaster;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
var
vTaskMaster : TTaskMaster;
vValidSchedulingThreadID : Cardinal;
// GlobalTaskMaster
//
function GlobalTaskMaster : TTaskMaster;
begin
Result:=vTaskMaster;
end;
// RDTSC
//
function RDTSC : Int64;
asm
db $0f, $31
end;
// RaiseTaskMasterException
//
procedure RaiseTaskMasterException(const msg : String);
begin
raise ETaskMasterException.Create(msg);
end;
// ------------------
// ------------------ TTaskInfo ------------------
// ------------------
// Create
//
constructor TTaskInfo.Create(eventOnExecute : TNotifyEvent; aSender : TObject);
begin
FOnExecute:=eventOnExecute;
FSender:=aSender;
InitializeCriticalSection(FSubTasksLock);
end;
// Destroy
//
destructor TTaskInfo.Destroy;
begin
if vTaskMaster.InSession then
RaiseTaskMasterException('Destroying a Task during an Execution is not allowed');
DeleteCriticalSection(FSubTasksLock);
end;
// Scheduled
//
function TTaskInfo.Scheduled : Boolean;
begin
Result:=(FSessionID=vTaskMaster.SessionID);
end;
// Executing
//
function TTaskInfo.Executing : Boolean;
begin
Result:=FExecuting;
end;
// Completed
//
function TTaskInfo.Completed : Boolean;
begin
Result:=FCompleted or (FSessionID<vTaskMaster.SessionID);
end;
// Aborted
//
function TTaskInfo.Aborted : Boolean;
begin
Result:=FAborted and (FSessionID<vTaskMaster.SessionID);
end;
// Schedule
//
procedure TTaskInfo.Schedule(masterTask : TTaskInfo);
begin
FSessionID:=vTaskMaster.SessionID;
FMasterTask:=masterTask;
if masterTask<>nil then
masterTask.RegisterSubTask(Self);
FAborted:=False;
FCompleted:=False;
FExecuting:=False;
ClearSubTasks;
end;
// Start
//
procedure TTaskInfo.Start;
begin
FExecuting:=True;
FLastRunTime:=RDTSC;
end;
// Stop
//
procedure TTaskInfo.Stop;
begin
FExecuting:=False;
FCompleted:=True;
FLastRunTime:=RDTSC-FLastRunTime;
end;
// Abort
//
procedure TTaskInfo.Abort;
begin
FExecuting:=False;
FAborted:=True;
FLastRunTime:=0;
end;
// RegisterSubTask
//
procedure TTaskInfo.RegisterSubTask(subTask : TTaskInfo);
var
n : Integer;
begin
EnterCriticalSection(FSubTasksLock);
n:=Length(FSubTasks);
if FSubTaskCount<=n then
SetLength(FSubTasks, 2*n+1);
FSubTasks[FSubTaskCount]:=subTask;
Inc(FSubTaskCount);
LeaveCriticalSection(FSubTasksLock);
end;
// ClearSubTasks
//
procedure TTaskInfo.ClearSubTasks;
begin
// shouldn't require a lock here, it's invoked from main thread only via Schedule
// and scheduling hasn't been completed yet, so no new subtask can be attached
FSubTaskCount:=0;
end;
// ------------------
// ------------------ TTaskMaster ------------------
// ------------------
// Create
//
constructor TTaskMaster.Create;
begin
ValidateThreadID;
if vTaskMaster<>nil then
RaiseTaskMasterException('Only ONE TaskMaster may be instantiated at any time');
vTaskMaster:=Self;
end;
// Destroy
//
destructor TTaskMaster.Destroy;
begin
if vTaskMaster<>Self then
RaiseTaskMasterException('TaskMaster instancing anomaly');
if InSession then
AbortSession;
vTaskMaster:=nil;
end;
// BeginSession
//
procedure TTaskMaster.BeginSession;
begin
ValidateThreadID;
if FSessionCount>=1 then
RaiseTaskMasterException('Nested sessions not supported');
Inc(FSessionCount);
Inc(FSessionID);
end;
// EndSession
//
procedure TTaskMaster.EndSession;
begin
ValidateThreadID;
if FSessionCount<=0 then
RaiseTaskMasterException('Unbalanced EndSession');
Dec(FSessionCount);
end;
// AbortSession
//
procedure TTaskMaster.AbortSession;
begin
ValidateThreadID;
if FSessionCount<=0 then
RaiseTaskMasterException('Unbalanced AbortSession');
Dec(FSessionCount);
end;
// InSession
//
function TTaskMaster.InSession : Boolean;
begin
Result:=(FSessionCount>0);
end;
// ValidateThreadID
//
procedure TTaskMaster.ValidateThreadID;
begin
Assert(vValidSchedulingThreadID=GetCurrentThreadID,
'TaskMaster can only be controled from the main thread!');
end;
// ------------------
// ------------------ TSingleThreadedTaskMaster ------------------
// ------------------
// ScheduleTask
//
procedure TSingleThreadedTaskMaster.ScheduleTask(aTask : TTaskInfo; dependsOnTask : TTaskInfo = nil);
begin
ValidateThreadID;
if not InSession then
RaiseTaskMasterException('Can only schedule task in an execution session!');
if dependsOnTask<>nil then
if dependsOnTask.SessionID<>SessionID then
RaiseTaskMasterException('Depended-on task must be schedule first!');
if aTask.SessionID>=SessionID then
RaiseTaskMasterException('Task has already been scheduled in this session!');
aTask.Schedule(dependsOnTask);
aTask.Start;
try
aTask.OnExecute(aTask.Sender);
aTask.Stop;
except
aTask.Abort;
end;
end;
// WaitFor
//
procedure TSingleThreadedTaskMaster.WaitFor(aTask : TTaskInfo);
begin
ValidateThreadID;
if not aTask.Completed then begin
if aTask.Aborted then
RaiseTaskMasterException('Task has been aborted')
else RaiseTaskMasterException(ClassName+' has a big bug!');
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
vValidSchedulingThreadID:=GetCurrentThreadID;
TSingleThreadedTaskMaster.Create;
finalization
vTaskMaster.Free;
end.
|
//=============================================================================
// sgGeometry.pas
//=============================================================================
//
// Contains code to create points, vectors and matrices and operations for use
// between them (addition, multiplication). This unit is particularly useful
// for the sgPhysics unit with uses such operations for collision testing.
//
// Most of the code in this unit was in sgPhysics prior to version 3. See
// there for possible relevant change notes.
//
//=============================================================================
/// SwinGame's geometry code includes the features to create, draw, and manipulate
/// shapes.
///
/// @module Geometry
/// @static
unit sgGeometry;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//---------------------------------------------------------------------------
// Circle creation code
//---------------------------------------------------------------------------
/// Creates a Circle at the point pt with the given radius.
///
/// @lib
/// @sn circleAt:%s radius:%s
function CircleAt(const pt: Point2D; radius: Single): Circle; overload;
/// Creates a circle at the given x,y location with the indicated radius.
///
/// @lib CircleFromXY
/// @sn circleAtX:%s y:%s radius:%s
///
/// @doc_idx 0
function CircleAt(x, y: Single; radius: Single): Circle; overload;
/// Creates a Circle at the point pt with the given radius.
///
/// @lib
/// @sn createCircle:%s radius:%s
function CreateCircle(const pt: Point2D; radius: Single): Circle; overload;
/// Creates a circle at the given x,y location with the indicated radius.
///
/// @lib CreateCircleFromXY
/// @sn createCircleX:%s y:%s radius:%s
///
/// @doc_idx 0
function CreateCircle(x, y: Single; radius: Single): Circle; overload;
//---------------------------------------------------------------------------
// Circle code
//---------------------------------------------------------------------------
/// Return the center point of a circle.
///
/// @lib CircleCenterPoint
function CenterPoint(const c: Circle): Point2D; overload;
/// Returns the X value of the center point of a circle.
///
/// @lib
function CircleX(const c: Circle): Single;
/// Returns the Y value of the center point of a circle.
///
/// @lib
function CircleY(const c: Circle): Single;
/// Returns the radius of the passed in circle.
///
/// @lib
function CircleRadius(const c: Circle): Single;
/// Returns the point that lies on the circle's radius that is closest to the fromPt.
///
/// @lib
/// @sn closestPointFrom:%s onCircle:%s
///
/// @class Circle
/// @method ClosestPointTo
/// @self 2
function ClosestPointOnCircle(const fromPt: Point2D; const c: Circle): Point2D;
/// Returns the point at the opposite side of a circle from a given point ``pt``.
///
/// @lib
/// @sn distantPointFrom:%s onCircle:%s
///
/// @class Circle
/// @method DistantPointFrom
/// @self 2
/// @csn distantPointFrom:%s
function DistantPointOnCircle(const pt: Point2D; const c: Circle): Point2D;
/// Finds the opposite side of a circle from a given point ``pt`` when travelling along the
/// vector ``heading``. Returns False if the ray projected from point ``pt`` misses the circle.
///
/// @lib
/// @sn distantPointFrom:%s onCircle:%s heading:%s result:%s
///
/// @class Circle
/// @method DistantPointFrom
/// @self 2
/// @csn distantPointFrom:%s heading:%s result:%s
function DistantPointOnCircleHeading(const pt: Point2D; const c: Circle; const heading: Vector; out oppositePt: Point2D): Boolean;
/// Returns the two widest points on the circle that lie along the indicated vector.
///
/// @lib
/// @sn widestPointsOn:%s along:%s firstPt:%s secondPt:%s
///
/// @class Circle
/// @method WidestPoints
/// @csn widestPointsAlong:%s firstPt:%s secondPt:%s
procedure WidestPoints(const c: Circle; const along: Vector; out pt1, pt2: Point2D);
/// Returns the two tangent points on the circle given the indicated vector.
///
/// @lib
/// @sn tangentPointsFrom:%s on:%s firstPt:%s secondPt:%s
///
/// @class Circle
/// @method TangentPoints
/// @self 2
/// @csn tangentPointsFrom:%s firstPt:%s secondPt:%s
function TangentPoints(const fromPt: Point2D; const c: Circle; out p1, p2: Point2D): Boolean;
/// Returns the distance from the ray origin to the edge of the circle where the ray heads in the
/// direction indicated in the ray_heading parameter. This returns -1 where the ray does not hit
/// the circle.
///
/// @lib
/// @sn distanceRayAt:%s heading:%s hitCircle:%s
///
/// @class Point2D
/// @method RayCircleIntersectDistance
/// @self 1
/// @csn distanceRayHeading:%s toCircle:%s
function RayCircleIntersectDistance(const ray_origin: Point2D; const ray_heading:Vector; const c: Circle): Single;
//---------------------------------------------------------------------------
// Line code
//---------------------------------------------------------------------------
/// Returns true if the line segment intersects the circle.
///
/// @lib
/// @sn lineSegment:%s intersectsCircle:%s
function LineIntersectsCircle(const l: LineSegment; const c: Circle): Boolean;
//---------------------------------------------------------------------------
// Sprite <-> Rectangle Collision Detection
//---------------------------------------------------------------------------
/// Returns true if the two line segments intersect.
///
/// @lib
/// @sn lineSegment:%s intersectsLinesSegment:%s
function LineSegmentsIntersect(const line1, line2: LineSegment): Boolean;
/// Returns true if the triangle intersects with the rectangle.
///
/// @lib
/// @sn triangle:%s intersectsRectangle:%s
function TriangleRectangleIntersect(const tri: Triangle; const rect: Rectangle): Boolean;
/// Returns distance from the line, or if the intersecting point on the line nearest
/// the point tested is outside the endpoints of the line, the distance to the
/// nearest endpoint.
///
/// Returns -1 on zero-valued denominator conditions to return an illegal distance. (
/// modification of Brandon Crosby's VBA code)
///
/// @lib PointLineDistance
/// @sn point:%s distanceTo:%s
function PointLineDistance(const pt: Point2D; const line: LineSegment): Single; overload;
/// Returns the distance from the x,y point to the line segment.
///
/// @lib PointXYLineDistance
/// @sn pointX:%s y:%s distanceTo:%s
///
/// @doc_idx 0
function PointLineDistance(x, y: Single; const line: LineSegment): Single; overload;
/// Returns the closest point on the line from the x,y point.
///
/// @lib ClosestPointOnLineXY
/// @sn pointFromX:%s y:%s closestToLine:%s
///
/// @doc_idx 0
function ClosestPointOnLine(x, y: Single; const line: LineSegment): Point2D; overload;
/// Returns the point on the line that is closest to the indicated point.
///
/// @lib ClosestPointOnLine
/// @sn pointFrom:%s closestToLine:%s
function ClosestPointOnLine(const fromPt: Point2D; const line: LineSegment): Point2D; overload;
/// Returns the point on the rectangle that is closest to the circle.
///
/// @lib
/// @sn circle:%s closestPointOnRect:%s
function ClosestPointOnRectFromCircle(const c: Circle; const rect: Rectangle): Point2D;
/// Returns the point on the line that is closest to the circle.
///
/// @lib
/// @sn circle:%s closestPointOnLine:%s
function ClosestPointOnLineFromCircle(const c: Circle; const line: LineSegment): Point2D;
/// Create a Point2D that points at the X,Y location passed in.
///
/// @lib PointAt
/// @sn pointAtX:%s y:%s
///
/// @class Point2D
/// @constructor
/// @csn initAtX:%s y:%s
function PointAt(x, y: Single): Point2D; overload;
/// Create a Point2D that points at the X,Y location passed in.
///
/// @lib RandomScreenPoint
/// @sn randomScreenPoint
///
/// @class Point2D
/// @constructor
/// @csn init
function RandomScreenPoint(): Point2D;
/// Create a Point2D that points at the point from the startPoint at the end of the offset vector.
///
/// @lib PointAtStartWithOffset
/// @sn point:%s offset:%s
function PointAt(const startPoint: Point2D; const offset: Vector): Point2D; overload;
/// Get a text description of the point2D.
///
/// @lib
///
/// @class Point2D
/// @method ToString
/// @csn description
function PointToString(const pt: Point2D): String;
/// Get a text description of the Vector.
///
/// @lib
///
/// @class Vector
/// @method ToString
/// @csn description
function VectorToString(const v: Vector): String;
/// Get a text description of the line segment.
///
/// @lib
///
/// @class LineSegment
/// @method ToString
/// @csn description
function LineToString(const ln: LineSegment): String;
/// Get a text description of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @method ToString
/// @csn description
function RectangleToString(const rect:Rectangle): String;
/// Get a text description of the triangle.
///
/// @lib
///
/// @class Triangle
/// @method ToString
/// @csn description
function TriangleToString(const tri: Triangle): String;
/// Returns the center point of the rectangle.
///
/// @lib
function RectangleCenter(const rect: Rectangle): Point2D;
/// Returns a line segment from x1,y1 to x2,y2.
///
/// @lib
/// @sn lineFromX1:%s y1:%s toX2:%s y2:%s
///
/// @doc_idx 0
function LineFrom(x1, y1, x2, y2: Single): LineSegment; overload;
/// Returns a line from pt1 to pt2.
///
/// @lib LineFromPointToPoint
/// @sn lineFrom:%s to:%s
function LineFrom(const pt1, pt2: Point2D): LineSegment; overload;
/// Returns a line from a starting point to the point at the end of the
/// mv vector.
///
/// @lib LineFromVectorWithStartPoint
/// @sn lineFrom:%s toOffset:%s
function LineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
/// Returns a line from the x,y starting point to the point at the end of the
/// mv vector.
///
/// @lib LineFromVectorWithStartXY
/// @sn lineFromX:%s y:%s toOffset:%s
function LineFromVector(x, y: Single; const mv: Vector): LineSegment; overload;
/// Returns a line from the origin to the end of the mv vector.
///
/// @lib
///
/// @doc_idx 0
function LineFromVector(const mv: Vector): LineSegment; overload;
/// Returns a line segment from x1,y1 to x2,y2.
///
/// @lib
/// @sn createLineX1:%s y1:%s toX2:%s y2:%s
///
/// @doc_idx 0
function CreateLine(x1, y1, x2, y2: Single): LineSegment; overload;
/// Returns a line from pt1 to pt2.
///
/// @lib CreateLinePointToPoint
/// @sn createLine:%s to:%s
function CreateLine(const pt1, pt2: Point2D): LineSegment; overload;
/// Returns a line from a starting point to the point at the end of the
/// mv vector.
///
/// @lib CreateLineVectorWithStartPoint
/// @sn createLineFrom:%s toOffset:%s
function CreateLineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
/// Returns a line from the x,y starting point to the point at the end of the
/// mv vector.
///
/// @lib CreateLineVectorWithStartXY
/// @sn createLineFromX:%s y:%s toOffset:%s
function CreateLineFromVector(x, y: Single; const mv: Vector): LineSegment; overload;
/// Returns a line from the origin to the end of the mv vector.
///
/// @lib
///
/// @doc_idx 0
function CreateLineFromVector(const mv: Vector): LineSegment; overload;
/// Returns the mid point of the line segment.
///
/// @lib
function LineMidPoint(const line: LineSegment): Point2D;
/// Returns a quad for the passed in points.
///
/// @lib
/// @sn quadFromXTopLeft:%s yTopLeft:%s xTopRight:%s yTopRight:%s xBottomLeft:%s yBottomLeft:%s xBottomRight:%s yBottomRight:%s
function QuadFrom(xTopLeft, yTopLeft, xTopRight, yTopRight, xBottomLeft, yBottomLeft, xBottomRight, yBottomRight: Single ): Quad;
/// Returns a quad for the passed in points.
///
/// @lib QuadFromRect
/// @sn quadFromRect:%s
function QuadFrom(const rect: Rectangle ): Quad;
/// Use a matrix to transform all of the points in a quad.
///
/// @lib ApplyMatrixToQuad
/// @sn matrix:%s applyToQuad:%s
///
/// @class Matrix2D
/// @method ApplyTo
/// @updatesArrayParam 2
/// @csn applyToQuad:%s
procedure ApplyMatrix(const m: Matrix2D; var quad: Quad);
/// Change the location of a point on a Quad.
///
/// @lib
/// @sn quad:%s setPoint:%s to:%s
procedure SetQuadPoint(var q: Quad; idx: Longint; value: Point2d);
/// Returns a rectangle from a given x,y location with a given width
/// and height.
///
/// @lib
/// @sn rectangleFromX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
function RectangleFrom(x, y, w, h: Single): Rectangle; overload;
/// Returns a rectangle with pt1 and pt2 defining the two distant edge points.
///
/// @lib RectangleForPoints
/// @sn rectangleFrom:%s to:%s
function RectangleFrom(const pt1, pt2: Point2D): Rectangle; overload;
/// Returns a rectangle at a given point with a specified width and height.
///
/// @lib RectangleAtPoint
/// @sn rectangleFrom:%s width:%s height:%s
function RectangleFrom(const pt: Point2D; width, height: Single): Rectangle; overload;
/// Returns a rectangle that encloses the two points on the line segment.
///
/// @lib RectangleFromLine
function RectangleFrom(const line: LineSegment): Rectangle; overload;
/// Returns a rectangle that encloses a circle.
///
/// @lib RectangleFromCircle
function RectangleFrom(const c: Circle): Rectangle; overload;
/// Returns a rectangle that encloses the points in a triangle.
///
/// @lib RectangleFromTriangle
function RectangleFrom(const tri: Triangle): Rectangle; overload;
/// Returns a rectangle from a given x,y location with a given width
/// and height.
///
/// @lib
/// @sn createRectangleX:%s y:%s width:%s height:%s
///
/// @doc_idx 0
function CreateRectangle(x, y, w, h: Single): Rectangle; overload;
/// Returns a rectangle with pt1 and pt2 defining the two distant edge points.
///
/// @lib CreateRectangleForPoints
/// @sn createRectangle:%s to:%s
function CreateRectangle(const pt1, pt2: Point2D): Rectangle; overload;
/// Returns a rectangle at a given point with a specified width and height.
///
/// @lib CreateRectangleAtPoint
/// @sn createRectangle:%s width:%s height:%s
function CreateRectangle(const pt: Point2D; width, height: Single): Rectangle; overload;
/// Returns a rectangle that encloses the two points on the line segment.
///
/// @lib CreateRectangleLine
function CreateRectangle(const line: LineSegment): Rectangle; overload;
/// Returns a rectangle that encloses a circle.
///
/// @lib CreateRectangleCircle
function CreateRectangle(const c: Circle): Rectangle; overload;
/// Returns a rectangle that encloses th epoints in a triangle.
///
/// @lib CreateRectangleTriangle
function CreateRectangle(const tri: Triangle): Rectangle; overload;
/// Returns a rectangle that is inset from rect the amount specified.
///
/// @lib
/// @sn insetRectangle:%s pixels:%s
function InsetRectangle(const rect: Rectangle; insetAmount: Single): Rectangle;
/// Ensures that the passed in rectangle has a positive width and height.
///
/// @lib FixRectangle
procedure FixRectangle(var rect: Rectangle);
/// Ensures that the passed in rectangle has a positive width and height.
///
/// @lib FixRect
/// @sn fixRectangleX:%s y:%s width:%s height:%s
procedure FixRectangle(var x, y, width, height: Single);
//---------------------------------------------------------------------------
// Triangle creation code
//---------------------------------------------------------------------------
/// Returns a triangle from the points passed in.
///
/// @lib
/// @sn triangleFromAx:%s ay:%s bx:%s by:%s cx:%s cy:%s
///
/// @doc_idx 0
function TriangleFrom(ax, ay, bx, by, cx, cy: Single): Triangle; overload;
/// Returns a triangle made up of the three points passed in.
///
/// @lib TriangleFromPoints
/// @sn triangleFromPtA:%s ptB:%s ptC:%s
function TriangleFrom(const a, b, c: Point2D): Triangle; overload;
/// Returns a triangle from the points passed in.
///
/// @lib
/// @sn createTriangleAx:%s ay:%s bx:%s by:%s cx:%s cy:%s
///
/// @doc_idx 0
function CreateTriangle(ax, ay, bx, by, cx, cy: Single): Triangle; overload;
/// Returns a triangle made up of the three points passed in.
///
/// @lib CreateTrianglePoints
/// @sn createTrianglePtA:%s ptB:%s ptC:%s
function CreateTriangle(const a, b, c: Point2D): Triangle; overload;
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
/// Returns the barycenter point of the triangle.
///
/// @lib
///
/// @class Triangle
/// @method Barycenter
function TriangleBarycenter(const tri: Triangle): Point2D;
/// Returns the rectangle details after it moved the amount specified within
/// the vector.
///
/// @lib
/// @sn rectangle:%s rectangleAfterMove:%s
///
/// @class Rectangle
/// @method RectangleAfterMove
function RectangleAfterMove(const rect: Rectangle; const mv: Vector): Rectangle;
/// Returns the top (y) value of a rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter Top
function RectangleTop (const rect: Rectangle): Single;
/// Returns the bottom (y) value of a rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter Bottom
function RectangleBottom(const rect: Rectangle): Single;
/// Returns the left (x) value of a rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter Left
function RectangleLeft (const rect: Rectangle): Single;
/// Returns the right (x) value of a rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter Right
function RectangleRight (const rect: Rectangle): Single;
/// Returns the top left corner of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter TopLeft
function RectangleTopLeft(const rect: Rectangle): Point2D;
/// Returns the top right corner of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter TopRight
function RectangleTopRight(const rect: Rectangle): Point2D;
/// Returns the bottom left corner of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter BottomLeft
function RectangleBottomLeft(const rect: Rectangle): Point2D;
/// Returns the bottom right corner of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter BottomRight
function RectangleBottomRight(const rect: Rectangle): Point2D;
/// Returns the center of the top line of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter CenterTop
function RectangleCenterTop(const rect: Rectangle): Point2D;
/// Returns the center of the bottom line of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter CenterBottom
function RectangleCenterBottom(const rect: Rectangle): Point2D;
/// Returns the center of the left line of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter CenterLeft
function RectangleCenterLeft(const rect: Rectangle): Point2D;
/// Returns the center of the right line of the rectangle.
///
/// @lib
///
/// @class Rectangle
/// @getter CenterRight
function RectangleCenterRight(const rect: Rectangle): Point2D;
/// Returns a rectangle that is offset by the vector.
///
/// @lib
/// @sn rectangleOffset:%s by:%s
function RectangleOffset(const rect: Rectangle; const vec: Vector): Rectangle;
/// Returns true if the two rectangles intersect.
///
/// @lib
/// @sn rectangle:%s intersectsRectangle:%s
///
/// @class Rectangle
/// @method Intersects
function RectanglesIntersect(const rect1, rect2: Rectangle): Boolean;
/// Returns the intersection of two rectangles.
///
/// @lib
/// @sn rectangle:%s intersectionWithRectangle:%s
///
/// @class Rectangle
/// @method Intersection
function Intersection(const rect1, rect2: Rectangle): Rectangle;
/// Returns the intersection point of two lines.
///
/// @lib
/// @sn line:%s intersectionWith:%s result:%s
///
/// @class LineSegment
/// @method IntersectionPoint
/// @csn intersectionWith:%s result:%s
function LineIntersectionPoint(const line1, line2: LineSegment; out pt: Point2D) : Boolean;
/// Returns the intersection point of a ray with a line, returning true if the ray intesects with the line.
///
/// @lib
/// @sn rayFrom:%s heading:%s intersectsLine:%s result:%s
///
/// @class LineSegment
/// @self 3
/// @method RayIntersectionPoint
/// @csn rayFrom:%s heading:%s intersectsAt:%s
function RayIntersectionPoint(const fromPt: Point2D; const heading: Vector; const line: LineSegment; out pt: Point2D) : Boolean;
/// Returns true if the line intersects the rectangle.
///
/// @lib
/// @sn lineSegment:%s intersectsRectangle:%s
///
/// @class LineSegment
/// @method IntersectsRect
function LineIntersectsRect(const line: LineSegment; const rect: Rectangle): Boolean;
//---------------------------------------------------------------------------
// Point test operations
//---------------------------------------------------------------------------
/// Returns true if the point ``pt`` is in the Triangle ``tri``.
///
/// @lib
/// @sn point:%s inTriangle:%s
///
/// @class Point2D
/// @method InTriangle
function PointInTriangle(const pt: Point2D; const tri: Triangle): Boolean;
/// Returns true if the point is within the rectangle.
///
/// @lib PointInRectXY
/// @sn point:%s inRectX:%s y:%s width:%s height:%s
///
/// @class Point2D
/// @overload InRect InRectPtXYWH
/// @csn inRectX:%s y:%s width:%s height:%s
function PointInRect(const pt: Point2D; x, y, w, h: Single): Boolean; overload;
/// Returns True if point ``pt`` is in the Rectangle ``rect``.
///
/// @lib
/// @sn point:%s inRect:%s
///
/// @class Point2D
/// @method InRect
///
/// @doc_idx 0
function PointInRect(const pt: Point2D; const rect: Rectangle): Boolean; overload;
/// Returns true if the point (ptX, ptY) is within the rectangle.
///
/// @lib PointXYInRectXY
/// @sn pointX:%s ptY:%s inRectX:%s y:%s width:%s height:%s
function PointInRect(ptX, ptY, x, y, w, h: Single): Boolean; overload;
/// Returns true if the x,y point is within the rectangle.
///
/// @lib PointXYInRect
/// @sn pointX:%s ptY:%s inRect:%s
function PointInRect(x, y: Single; const rect: Rectangle): Boolean; overload;
/// Returns True if the point ``pt`` is in the circle.
///
/// @lib
/// @sn point:%s inCircle:%s
///
/// @class Point2D
/// @method InCircle
function PointInCircle(const pt: Point2D; const c: Circle): Boolean;
/// Returns True if the point ``pt`` is in the circle defined by x, y, radius.
///
/// @lib PointInCirclePt
/// @sn point:%s inCircleAtX:%s y:%s withRadius:%s
///
/// @class Point2D
/// @method InCircle
/// @csn inCircleAtX:%s y:%s withRadius:%s
function PointInCircle(const pt: Point2D; x, y, radius: Single): Boolean;
/// Returns True if the point ``ptX``, ``ptY`` is in the circle.
///
/// @lib PointXYInCircle
/// @sn pointX:%s y:%s inCircleX:%s y:%s radius:%s
function PointInCircle(ptX, ptY, cX, cY, radius: Single): Boolean;
/// Returns True if point ``pt`` is on the line segment ``line``.
///
/// @lib PointOnLine
/// @sn point:%s onLine:%s
///
/// @class Point2D
/// @method OnLine
function PointOnLine(const pt: Point2D; const line: LineSegment): Boolean;
/// Returns True if point ``pt`` is on the line segment ``line``.
///
/// @lib PointOnLineXYXY
/// @sn point:%s onLineAtX:%s Y:%s endX:%s endY:%s
///
/// @class Point2D
/// @method OnLine
/// @csn onLineAtX:%s Y:%s endX:%s endY:%s
function PointOnLine(const pt: Point2D; x, y, endX, endY: Single): Boolean;
/// Returns True of `pt1` is at the same point as `pt2`.
///
/// @lib
/// @sn point:%s atSamePointAs:%s
///
/// @class Point2D
/// @method OnPoint
function PointOnPoint(const pt1,pt2: Point2d): Boolean;
//---------------------------------------------------------------------------
// Vector Creation and Operations
//---------------------------------------------------------------------------
/// Returns a new `Vector` using the ``x`` and ``y`` values provided.
///
/// @lib VectorTo(x, y, False)
/// @uname VectorTo
///
/// @sn vectorToX:%s y:%s
function VectorTo(x, y: Single): Vector; overload;
/// Creates a new `Vector` with the ``x`` and ``y`` values provided, and will
/// invert the ``y`` value if the ``invertY`` parameter is True. The inversion
/// of the ``y`` value provides a convienient option for handling screen
/// related vectors.
///
/// @lib
/// @uname VectorToWithInvertY
///
/// @sn vectorToX:%s y:%s invertY:%s
function VectorTo(x, y: Single; invertY: Boolean): Vector; overload;
/// Adds the two parameter vectors (``v1`` and ``v2``) together and returns
/// the result as a new `Vector`.
///
/// @lib
///
/// @sn vector:%s addVector:%s
///
/// @class Vector
/// @method AddVector
/// @csn vectorByAdding:%s
function AddVectors(const v1, v2: Vector): Vector;
{$ifdef FPC}
/// Adds the two vectors together resulting in a new vector.
///
/// @class Vector
/// @calls AddVectors
operator + (const v1, v2: Vector) r : Vector;
{$endif}
/// Subtracts the second vector parameter (``v2``) from the first vector
/// (``v1``) and returns the result as new `Vector`.
///
/// @lib
/// @sn vector:%s subtractVector:%s
///
/// @class Vector
/// @method SubtractVector
function SubtractVectors(const v1, v2: Vector): Vector;
{$ifdef FPC}
/// @class Vector
/// @calls SubtractVectors
operator - (const v1, v2: Vector) r : Vector;
{$endif}
/// Multiplies each component (``x`` and ``y`` values) of the ``v1`` vector
/// by the ``s`` scalar value and returns the result as a new `Vector`.
///
/// @lib
/// @sn vector:%s multipliedBy:%s
///
/// @class Vector
/// @method Multiply
function VectorMultiply(const v: Vector; s: Single): Vector;
{$ifdef FPC}
/// @class Vector
/// @calls VectorMultiply
operator * (const v: Vector; s: Single) r : Vector;
{$endif}
/// Determines if two vectors are equal.
///
/// @lib
/// @sn vector:%s equals:%s
///
/// @class Vector
/// @method EqualsVector
function VectorsEqual(const v1, v2: Vector): Boolean;
{$ifdef FPC}
/// @class Vector
/// @calls VectorsEqual
operator = (const v1, v2: Vector) r : Boolean;
{$endif}
/// Determines if two vectors are not equal.
///
/// @lib
/// @sn vector:%s doesNotEqual:%s
///
/// @class Vector
/// @method DoesNotEqualVector
function VectorsNotEqual(const v1, v2: Vector): Boolean;
{$ifdef BLAH_BLAH_123}
// Never compile this... FPC doesn't allow <> operator
// but this is required by C#, so we need to pretend it exists...
/// @class Vector
/// @calls VectorsNotEqual
operator <> (const v1, v2: Vector) r : Boolean;
{$endif}
/// Calculates the dot product (scalar product) between the two vector
/// parameters rovided (``v1`` and ``v2``). It returns the result as a
/// scalar value.
///
/// If the result is 0.0 it means that the vectors are orthogonal (at right
/// angles to each other). If ``v1`` and ``v2`` are unit vectors (length of
/// 1.0) and the dot product is 1.0, it means that ``v1`` and ``v2`` vectors
/// are parallel.
///
/// @lib
/// @sn vector:%s dotProduct:%s
///
/// @class Vector
/// @method DotProduct
function DotProduct(const v1, v2: Vector): Single;
/// Returns a new `Vector` that is perpendicular ("normal") to the parameter
/// vector ``v`` provided. The concept of a "normal" vector is usually
/// extracted from (or associated with) a line. See `LineNormal`.
///
/// Note: when passed a zero or null vector (a vector with no
/// magnitude or direction) then this function returns a zero/null vector.
///
/// @lib
/// @sn vectorNormal:%s
///
/// @class Vector
/// @getter Normal
function VectorNormal(const v: Vector): Vector;
/// Returns a unit vector (length is 1.0) that is "normal" (prependicular) to
/// the ``line`` parameter. A normal vector is useful for calculating the
/// result of a collision such as sprites bouncing off walls (lines).
///
/// @lib
/// @sn lineNormal:%s
///
/// @class LineSegment
/// @getter Normal
function LineNormal(const line: LineSegment): Vector;
/// Returns a new Vector that is an inverted version of the parameter
/// vector (v). In other words, the -/+ sign of the x and y values are changed.
///
/// @lib
/// @sn vectorInvert:%s
///
/// @class Vector
/// @getter Inverted
function InvertVector(const v: Vector): Vector;
/// Returns a new `Vector` that is a based on the parameter ``v`` however
/// its magnitude (length) will be limited (truncated) if it exceeds the
/// specified limit value.
///
/// @lib
/// @sn vector:%s limitMagnitude:%s
///
/// @class Vector
/// @method LimitToMagnitude
function LimitVector(const v: Vector; limit: Single): Vector;
/// Returns the unit vector of the parameter vector (v). The unit vector has a
/// magnitude of 1, resulting in a vector that indicates the direction of
/// the original vector.
///
/// @lib
/// @sn vectorUnitVector:%s
///
/// @class Vector
/// @getter UnitVector
function UnitVector(const v: Vector): Vector;
/// Test to see if the ``x`` and ``y`` components of the provided vector
/// parameter ``v`` are zero.
///
/// @lib
///
/// @class Vector
/// @getter IsZero
function VectorIsZero(const v: Vector): Boolean;
/// Returns the magnitude (or "length") of the parameter vector (v) as a
/// scalar value.
///
/// @lib
///
/// @class Vector
/// @getter Magnitude
function VectorMagnitude(const v: Vector): Single;
/// Returns the squared magnitude (or "length") of the parameter vector (v) as a
/// scalar value.
///
/// @lib
///
/// @class Vector
/// @getter MagnitudeSq
function VectorMagnitudeSq(const v: Vector): Single;
/// Returns a new `Vector` created using the angle and magnitude (length).
/// The angle and magnitude are scalar values and the angle is in degrees.
///
/// @lib
/// @sn vectorFromAngle:%s magnitude:%s
function VectorFromAngle(angle, magnitude: Single): Vector;
/// Returns a new `Vector` using the x and y value of a Point2D parameter.
///
/// @lib
function VectorToPoint(const p1: Point2D): Vector;
/// Returns a `Vector` created from the difference from the ``p1`` to
/// the second ``p2`` points (`Point2D`).
///
/// @lib
/// @sn vectorFrom:%s to:%s
///
/// @class Point2D
/// @method ToPoint
function VectorFromPoints(const p1, p2: Point2D): Vector;
/// Returns a new `Vector` created from the start and end points of a
/// `LineSegment`. Useful for calculating angle vectors or extracting a
/// normal vector (see `LineNormal`) for the line.
///
/// @lib
///
/// @class LineSegment
/// @method AsVector
function LineAsVector(const line: LineSegment): Vector;
/// Return true if the vector (used as a point) is within the rectangle
///
/// @lib VectorInRectXY
/// @sn vector:%s inRectX:%s y:%s width:%s height:%s
///
/// @class Vector
/// @method InRect
/// @csn inRectX:%s y:%s width:%s height:%s
function VectorInRect(const v: Vector; x, y, w, h: Single): Boolean; overload;
/// Returns true if the vector ends within the rectangle when started at the origin.
///
/// @lib VectorInRect
/// @sn vector:%s inRectangle:%s
///
/// @class Vector
/// @overload InRect InRectangle
/// @csn inRect:%s
function VectorInRect(const v: Vector; const rect: Rectangle): Boolean; overload;
/// Returns a vector from the specified point to the specified rectangle.
///
/// @lib VectorFromPointToRect
/// @sn vectorFromX:%s y:%s toRectX:%s y:%s width:%s height:%s
function VectorFromPointToRect(x, y, rectX, rectY, rectWidth, rectHeight: Single): Vector; overload;
/// Returns a vector from the specified point to the specified rectangle.
///
/// @lib VectorFromPointToRectangle
/// @sn vectorFromX:%s y:%s toRect:%s
function VectorFromPointToRect(x, y: Single; const rect: Rectangle): Vector; overload;
/// Returns a vector from a point to the specified rectangle.
///
/// @lib VectorFromPointPtToRectangle
/// @sn vectorFromPt:%s to:%s
function VectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
/// Returns a new `Vector` created using the angle and magnitude (length).
/// The angle and magnitude are scalar values and the angle is in degrees.
///
/// @lib
/// @sn createvectorFromAngle:%s magnitude:%s
function CreateVectorFromAngle(angle, magnitude: Single): Vector;
/// Returns a new `Vector` using the x and y value of a Point2D parameter.
///
/// @lib
function CreateVectorToPoint(const p1: Point2D): Vector;
/// Returns a `Vector` created from the difference from the ``p1`` to
/// the second ``p2`` points (`Point2D`).
///
/// @lib
/// @sn createVectorFrom:%s to:%s
///
/// @class Point2D
/// @method CreateVectorToPoint
function CreateVectorFromPoints(const p1, p2: Point2D): Vector;
/// Returns a new `Vector` created from the start and end points of a
/// `LineSegment`. Useful for calculating angle vectors or extracting a
/// normal vector (see `LineNormal`) for the line.
///
/// @lib
///
/// @class LineSegment
/// @method CreateAsVector
function CreateLineAsVector(const line: LineSegment): Vector;
/// Returns a vector from the specified point to the specified rectangle.
///
/// @lib CreateVectorFromPointToRect
/// @sn createvectorFromX:%s y:%s toRectX:%s y:%s width:%s height:%s
function CreateVectorFromPointToRect(x, y, rectX, rectY, rectWidth, rectHeight: Single): Vector; overload;
/// Returns a vector from the specified point to the specified rectangle.
///
/// @lib CreateVectorFromPointToRectangle
/// @sn createvectorFromX:%s y:%s toRect:%s
function CreateVectorFromPointToRect(x, y: Single; const rect: Rectangle): Vector; overload;
/// Returns a vector from a point to the specified rectangle.
///
/// @lib CreateVectorFromPointPtToRectangle
/// @sn createvectorFromPt:%s to:%s
function CreateVectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
//---------------------------------------------------------------------------
// Functions to get a vector out of some bounded shape
//---------------------------------------------------------------------------
/// Determines the vector needed to move from point ``pt`` out of rectangle ``rect`` given the velocity specified
///
/// @lib
/// @sn vectorFromPt:%s outOfRect:%s givenHeading:%s
///
/// @class Point2D
/// @method VectorOutOfRect
/// @csn vectorOutOfRect:%s givenHeading:%s
function VectorOutOfRectFromPoint(const pt: Point2D; const rect: Rectangle; const velocity: Vector): Vector;
/// Returns the vector needed to move rectangle ``src`` out of rectangle``bounds`` given the velocity specified.
///
/// @lib
/// @sn vectorFromRect:%s outOfRect:%s givenHeading:%s
///
/// @class Rectangle
/// @method VectorOutOfRect
/// @csn vectorOutOfRect:%s givenHeading:%s
function VectorOutOfRectFromRect(const src, bounds: Rectangle; const velocity: Vector): Vector;
/// Returns the vector out of a circle from a given point.
///
/// @lib
/// @sn vectorFromPt:%s outOfCircle:%s givenHeading:%s
///
/// @class Point2D
/// @method VectorOutOfCircleFromPoint
/// @csn vectorOutOfCircle:%s givenHeading:%s
function VectorOutOfCircleFromPoint(const pt: Point2D; const c: Circle; const velocity: Vector): Vector;
/// Returns a vector out of a circle for a given circle.
///
/// @lib
/// @sn vectorFromCircle:%s outOfCircle:%s givenHeading:%s
///
/// @class Circle
/// @method VectorOutOfCircle
/// @csn vectorOutOfCircle:%s givenHeading:%s
function VectorOutOfCircleFromCircle(const src, bounds: Circle; const velocity: Vector): Vector;
/// Returns a vector that can be used to move a circle out of a rectangle.
///
/// @lib
/// @sn vectorFromCircle:%s outOfRect:%s givenHeading:%s
///
/// @class Circle
/// @method VectorOutOfRect
/// @csn vectorOutOfRect:%s givenHeading:%s
function VectorOutOfRectFromCircle(const c: Circle; const rect: Rectangle; const velocity: Vector): Vector;
//---------------------------------------------------------------------------
// Angle Calculation
//---------------------------------------------------------------------------
/// Calculates the angle from x1,y1 to x2,y2.
///
/// @lib
/// @sn calculateAngleFromX1:%s y1:%s toX2:%s y:%s
function CalculateAngle(x1, y1, x2, y2: Single): Single; overload;
/// Calculates the angle between two sprites.
///
/// @lib CalculateAngleBetweenSprites
/// @sn sprite:%s angleToSprite:%s
///
/// @class Sprite
/// @method AngleTo
function CalculateAngle(s1, s2: Sprite): Single; overload;
/// Calculates the angle from one vector to another.
///
/// @lib CalculateAngleBetweenVectors
/// @sn vector:%s angleTo:%s
///
/// @class Vector
/// @method AngleTo
///
/// @doc_idx 0
function CalculateAngle(const v1, v2: Vector): Single; overload;
/// Calculates the angle between two points.
///
/// @lib
/// @sn point:%s angleTo:%s
///
/// @class Point2D
/// @method AngleTo
function CalculateAngleBetween(const pt1, pt2: Point2D): Single;
/// Calculates the angle of a vector.
///
/// @lib
///
/// @class Vector
/// @getter Angle
function VectorAngle(const v: Vector): Single;
//---------------------------------------------------------------------------
// Distance / Magnitude Calculation
//---------------------------------------------------------------------------
/// Returns the squared magnitude of the line from the points given.
///
/// @lib
/// @sn lineMagnitudeSqX1:%s y1:%s x2:%s y2:%s
function LineMagnitudeSq(x1, y1, x2, y2: single): Single; overload;
/// Returns the squared line magnitude.
///
/// @lib LineMagnitudeSqFromLine
/// @sn lineMagnitudeSq:%s
///
/// @class LineSegment
/// @getter MagnitudeSq
function LineMagnitudeSq(const line: LineSegment): Single; overload;
/// Returns the distance from point to point.
///
/// @lib
/// @sn point:%s distanceToPoint:%s
///
/// @class Point2D
/// @method DistanceTo
function PointPointDistance(const pt1, pt2: Point2D): Single;
//---------------------------------------------------------------------------
// Point2D Operations
//---------------------------------------------------------------------------
/// Returns the sum of pt1 and pt2
///
/// @lib
/// @sn point:%s plusPoint:%s
///
/// @class Point2D
/// @method Add
function PointAdd(const pt1, pt2: Point2D): Point2D;
//---------------------------------------------------------------------------
// Matrix2D Creation and Operations
//---------------------------------------------------------------------------
/// Returns the identity matrix. When a Matrix2D or Vector is multiplied by
/// the identity matrix the result is the original matrix or vector.
///
/// @lib
///
/// @class Matrix2D
/// @static
/// @method IdentityMatrix
function IdentityMatrix(): Matrix2D;
/// Returns a matrix that can be used to translate 2d points. Moving them
/// by dx and dy.
///
/// @lib
/// @sn translationMatrixDx:%s dy:%s
///
/// @class Matrix2D
/// @static
/// @method TranslationMatrix
/// @csn translationMatrixDx:%s dy:%s
///
/// @doc_idx 0
function TranslationMatrix(dx, dy: Single): Matrix2D; overload;
/// Returns a translation matric used to translate 2d points by the
/// distance in the Point2D.
///
/// @lib TranslationMatrixPt
/// @sn translationMatrix:%s
///
/// @class Matrix2D
/// @static
/// @overload TranslationMatrix TranslationMatrixWithPoint
/// @csn translationMatrix:%s
function TranslationMatrix(const pt: Point2D): Matrix2D; overload;
/// Returns a matrix that can be used to scale 2d points (both x and y).
///
/// @lib
/// @sn scaleMatrix:%s
///
/// @class Matrix2D
/// @static
/// @method ScaleMatrix
///
/// @doc_idx 0
function ScaleMatrix(scale: Single): Matrix2D; overload;
/// Create a scale matrix that scales x and y to
/// different degrees.
///
/// @lib ScaleMatrixByPoint
/// @sn scaleMatricByPoint:%s
///
/// @class Matrix2D
/// @static
/// @overload ScaleMatrix ScaleMatrixWithPoint
/// @csn scaleMatrixByPoint:%s
function ScaleMatrix(const scale: Point2D): Matrix2D; overload;
/// Returns a rotation matrix that rotates 2d points by the angle.
///
/// @lib
///
/// @class Matrix2D
/// @static
/// @method RotationMatrix
function RotationMatrix(deg: Single): Matrix2D;
/// Create a matrix that can scale, rotate then translate geometry points.
///
/// @lib
/// @sn matrixToScale:%s rotate:%s translate:%s
///
/// @class Matrix2D
/// @static
/// @method ScaleRotateTranslateMatrix
/// @csn matrixToScale:%s rotate:%s translate:%s
function ScaleRotateTranslateMatrix(const scale: Point2D; deg: Single; const translate: Point2D): Matrix2D;
/// Multiplies the two `Matrix2D` parameters, ``m1`` by ``m2``, and returns
/// the result as a new `Matrix2D`. Use this to combine the effects to two
/// matrix transformations.
///
/// @lib
/// @sn matrix:%s multiplyByMatrix:%s
///
/// @class Matrix2D
/// @method Multiply
/// @csn multiplyByMatrix:%s
function MatrixMultiply(const m1, m2: Matrix2D): Matrix2D; overload;
/// Multiplies the `Vector` parameter ``v`` with the `Matrix2D` ``m`` and
/// returns the result as a `Vector`. Use this to transform the vector with
/// the matrix (to apply scaling, rotation or translation effects).
///
/// @lib MatrixMultiplyVector
/// @sn matrix:%s multiplyByVector:%s
///
/// @class Matrix2D
/// @overload Multiply MultiplyVector
/// @csn multiplyByVector:%s
function MatrixMultiply(const m: Matrix2D; const v: Vector): Vector; overload;
/// Calculate the inverse of a matrix.
///
/// @lib
///
/// @class Matrix2D
/// @method Inverse
function MatrixInverse(const m: Matrix2D): Matrix2D;
/// Use a matrix to transform all of the points in a triangle.
///
/// @lib
/// @sn matrix:%s applyToTriangle:%s
///
/// @class Matrix2D
/// @method ApplyTo
/// @updatesArrayParam 2
/// @csn applyToTriangle:%s
procedure ApplyMatrix(const m: Matrix2D; var tri: Triangle);
{$ifdef FPC}
/// Multiply matrix by the vector.
///
/// @class Matrix2D
/// @calls MatrixMultiplyVector
operator * (const m: Matrix2D; const v: Vector) r : Vector;
{$endif}
{$ifdef FPC}
/// Multiply the two matricies together.
///
/// @class Matrix2D
/// @calls MatrixMultiply
operator * (const m1, m2: Matrix2D) r : Matrix2D;
{$endif}
/// This function returns a string representation of a Matrix.
///
/// @lib
///
/// @class Matrix2D
/// @method ToString
/// @csn description
function MatrixToString(const m: Matrix2D) : String;
//----------------------------------------------------------------------------
// Cosine/Sin/Tan accepting degrees
//----------------------------------------------------------------------------
/// Returns the cosine of the passed in angle (in degrees).
///
/// @lib
function Cosine(angle: Single): Single;
/// Returns the sine of the passed in angle (in degrees).
///
/// @lib
function Sine(angle: Single): Single;
/// Returns the tangent of the passed in angle (in degrees).
///
/// @lib
function Tangent(angle: Single): Single;
//=============================================================================
implementation
//=============================================================================
uses
Classes, SysUtils, Math, sgBackendTypes, GeometryHelper, // system
sgCamera, sgGraphics, sgSprites, sgPhysics, sgShared, sgTrace, sgUtils, sgWindowManager; // SwinGame
const
DEG_TO_RAD = 0.0174532925199432957692369076848861271344287188854172545609;
function PointsFrom(const rect: Rectangle): Point2DArray; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointsFrom(const rect: Rectangle): Point2DArray', '');
{$ENDIF}
SetLength(result, 4);
result[0] := PointAt(rect.x, rect.y);
result[1] := PointAt(rect.x + rect.width, rect.y);
result[2] := PointAt(rect.x, rect.y + rect.height);
result[3] := PointAt(rect.x + rect.width, rect.y + rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointsFrom(const rect: Rectangle): Point2DArray', '');
{$ENDIF}
end;
function PointsFrom(const line: LineSegment): Point2DArray; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointsFrom(line): Point2DArray', '');
{$ENDIF}
SetLength(result, 2);
result[0] := line.startPoint;
result[1] := line.endPoint;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointsFrom(line): Point2DArray', '');
{$ENDIF}
end;
//
// This internal function is used to calculate the vector and determine if a hit has occurred...
//
// pts contains the array of points to search from. These represent the widest points of the shape being tested
// against the lines.
//
// lines These are the lines being tested for collision.
//
// velocity The direction/distance of the movement of the points (used to find impact point)
//
// maxIds The index of the line that is the furthest colliding line back from the points.
//
function VectorOverLinesFromLines(const srcLines, boundLines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector;
var
ray, vOut: Vector;
i, j, k: Longint;
maxDist: Single;
lnPoints, boundLnPoints: Point2DArray;
bothDidHit: Boolean;
// Search from the startPt for the ray
function _RayFromPtHitLine(startPt: Point2D; const toLine: LineSegment; myRay: Vector): Boolean;
var
ptOnLine: Point2D;
dist: Single;
begin
//DrawCircle(ColorWhite, pts[j], 2);
result := False;
// Cast myRay back from startPt to find line pts... out on ptOnLine
// ptOnLine is then the point that the ray intersects with the line
if RayIntersectionPoint(startPt, myRay, toLine, ptOnLine) then
begin
if not PointOnLine(ptOnLine, toLine) then exit; //this points ray misses the line
result := True;
// FillCircle(ColorRed, startPt, 2);
// DrawCircle(ColorRed, ptOnLine, 2);
// DrawLine(ColorRed, startPt, ptOnLine);
// Calculate the distance from the point on the line to the point being tested
dist := PointPointDistance(ptOnLine, startPt);
// Check if the distance is the new max distance
if (dist > maxDist) or (maxIdx = -1) then
begin
maxDist := dist;
maxIdx := i; // We hit with the current line
if VectorsEqual(myRay, ray) then // if we are searching back...
vOut := VectorFromPoints(startPt, ptOnLine)
else // if we are searching forward (using velocity)
vOut := VectorFromPoints(ptOnLine, startPt);
vOut := VectorMultiply(UnitVector(vOut), VectorMagnitude(vOut) + 1) //TODO: check this further
end;
end;
end;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOverLinesFromLines(const pts: Point2DArray', '');
{$ENDIF}
// Cast ray searching back from pts... looking for the impact point
ray := InvertVector(velocity); // the ray
vOut := VectorTo(0,0); // the vector out (from the point to over the line, i.e. moving the point along this vector moves it back over the line)
// Indicate no find so far....
maxIdx := -1;
maxDist := -1;
//
// Search all lines for hit points - cast ray back from line ends and find where these intersect with the bound lines
//
for i := 0 to High(boundLines) do
begin
//WriteLn('Testing bound line: ', LineToString(boundLines[i]));
boundLnPoints := PointsFrom(boundLines[i]);
// for all source lines...
for j := 0 to High(srcLines) do
begin
//WriteLn('Testing src line: ', LineToString(srcLines[j]));
// Get the points from the srcLine
lnPoints := PointsFrom(srcLines[j]);
bothDidHit := True;
for k := 0 to High(lnPoints) do
begin
//WriteLn('Point ', k, ' in line is at ', PointToString(lnPoints[k]));
bothDidHit := _RayFromPtHitLine(lnPoints[k], boundLines[i], ray) and bothDidHit;
end;
if bothDidHit then continue;
// Search from the bound line to the source
for k := 0 to High(boundLnPoints) do
begin
_RayFromPtHitLine(boundLnPoints[k], srcLines[j], velocity);
end;
end;
end;
result.x := Ceiling(vOut.x);
result.y := Ceiling(vOut.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOverLinesFromLines(const pts: Point2DArray', '');
{$ENDIF}
end;
//
// This internal function is used to calculate the vector and determine if a hit has occurred...
//
// pts contains the array of points to search from. These represent the widest points of the shape being tested
// against the lines.
//
// lines These are the lines being tested for collision.
//
// velocity The direction/distance of the movement of the points (used to find impact point)
//
// maxIds The index of the line that is the furthest colliding line back from the points.
//
function _VectorOverLinesFromPoints(const pts: Point2DArray; const lines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector;
var
ptOnLine: Point2D;
ray, vOut: Vector;
i, j: Longint;
dist, maxDist: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', '_VectorOverLinesFromPoints(const pts: Point2DArray', '');
{$ENDIF}
// Cast ray searching back from pts... looking for the impact point
ray := InvertVector(velocity); // the ray
vOut := VectorTo(0,0); // the vector out (from the point to over the line, i.e. moving the point along this vector moves it back over the line)
// Indicate no find so far....
maxIdx := -1;
maxDist := -1;
//Search all lines for hit points
for i := 0 to High(lines) do
begin
// for all points...
for j := 0 to High(pts) do
begin
//DrawCircle(ColorWhite, pts[j], 2);
// Cast a ray back from this point to find line pts... out on ptOnLine
// ptOnLine is then the point that the ray intersects with the line
if RayIntersectionPoint(pts[j], ray, lines[i], ptOnLine) then
begin
//DrawCircle(ColorRed, ptOnLine, 1);
//DrawLine(ColorRed, pts[j], ptOnLine);
if not PointOnLine(ptOnLine, lines[i]) then continue; //this points ray misses the line
// Calculate the distance from the point on the line to the point being tested
dist := PointPointDistance(ptOnLine, pts[j]);
// Check if the distance is the new max distance
if (dist > maxDist) or (maxIdx = -1) then
begin
maxDist := dist;
maxIdx := i;
vOut := VectorFromPoints(pts[j], ptOnLine);
vOut := VectorMultiply(UnitVector(vOut), VectorMagnitude(vOut) + 1)
end;
end;
end;
end;
result.x := Ceiling(vOut.x);
result.y := Ceiling(vOut.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', '_VectorOverLinesFromPoints(const pts: Point2DArray', '');
{$ENDIF}
end;
//
// This internal function is used to calculate the vector and determine if a hit has occurred...
//
function _VectorOverLinesFromPoint(const pt: Point2D; const lines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector;
var
pts: Point2DArray;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', '_VectorOverLinesFromPoint(const pt: Point2D', '');
{$ENDIF}
SetLength(pts, 1);
pts[0] := pt;
result := _VectorOverLinesFromPoints(pts, lines, velocity, maxIdx);
{$IFDEF TRACE}
TraceExit('sgGeometry', '_VectorOverLinesFromPoint(const pt: Point2D', '');
{$ENDIF}
end;
//---------------------------------------------------------------------------
// Vector operations on Vectors (usally returning vectors)
//---------------------------------------------------------------------------
function VectorTo(x, y: Single; invertY: Boolean): Vector; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorTo(x, y: Single', '');
{$ENDIF}
if invertY then y := y * -1;
result.x := x;
result.y := y;
//result.w := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorTo(x, y: Single', '');
{$ENDIF}
end;
function VectorTo(x, y: Single): Vector; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorTo(x, y: Single): Vector', '');
{$ENDIF}
result := VectorTo(x, y, false);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorTo(x, y: Single): Vector', '');
{$ENDIF}
end;
function VectorToPoint(const p1: Point2D): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorToPoint(const p1: Point2D): Vector', '');
{$ENDIF}
result := VectorTo(p1.x, p1.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorToPoint(const p1: Point2D): Vector', '');
{$ENDIF}
end;
function VectorFromPoints(const p1, p2: Point2D): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorFromPoints(const p1, p2: Point2D): Vector', '');
{$ENDIF}
result := VectorTo(p2.x - p1.x, p2.y - p1.y, false);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorFromPoints(const p1, p2: Point2D): Vector', '');
{$ENDIF}
end;
function AddVectors(const v1, v2: Vector): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'AddVectors(const v1, v2: Vector): Vector', '');
{$ENDIF}
result.x := v1.x + v2.x;
result.y := v1.y + v2.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'AddVectors(const v1, v2: Vector): Vector', '');
{$ENDIF}
end;
{$ifdef FPC}
operator + (const v1, v2: Vector) r : Vector;
begin
r := AddVectors(v1, v2);
end;
{$endif}
function SubtractVectors(const v1, v2: Vector): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'SubtractVectors(const v1, v2: Vector): Vector', '');
{$ENDIF}
result.x := v1.x - v2.x;
result.y := v1.y - v2.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'SubtractVectors(const v1, v2: Vector): Vector', '');
{$ENDIF}
end;
{$ifdef FPC}
operator - (const v1, v2: Vector) r : Vector;
begin
r := SubtractVectors(v1, v2);
end;
{$endif}
function VectorMultiply(const v: Vector; s: Single): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorMultiply(const v: Vector', '');
{$ENDIF}
result.x := v.x * s;
result.y := v.y * s;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorMultiply(const v: Vector', '');
{$ENDIF}
end;
{$ifdef FPC}
operator * (const v: Vector; s: Single) r : Vector;
begin
r := VectorMultiply(v, s);
end;
{$endif}
function VectorsEqual(const v1, v2: Vector): Boolean;
begin
result := (v1.x = v2.x) and (v1.y = v2.y);
end;
{$ifdef FPC}
operator = (const v1, v2: Vector) r : Boolean;
begin
r := VectorsEqual(v1, v2);
end;
{$endif}
function VectorsNotEqual(const v1, v2: Vector): Boolean;
begin
result := (v1.x <> v2.x) or (v1.y <> v2.y);
end;
function InvertVector(const v: Vector): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'InvertVector(const v: Vector): Vector', '');
{$ENDIF}
result.x := v.x * -1;
result.y := v.y * -1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'InvertVector(const v: Vector): Vector', '');
{$ENDIF}
end;
function LimitVector(const v: Vector; limit: Single): Vector;
var
mag: Single;
tmp: Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LimitVector(const v: Vector', '');
{$ENDIF}
mag := VectorMagnitude(v);
if mag > limit then
begin
tmp := UnitVector(v);
result.x := tmp.x * limit;
result.y := tmp.y * limit;
end
else
result := v;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LimitVector(const v: Vector', '');
{$ENDIF}
end;
function UnitVector(const v: Vector): Vector;
var
mag, tmp: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'UnitVector(const v: Vector): Vector', '');
{$ENDIF}
mag := VectorMagnitude(v);
if mag = 0 then
tmp := 0
else
tmp := 1 / mag;
result.x := tmp * v.x;
result.y := tmp * v.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'UnitVector(const v: Vector): Vector', '');
{$ENDIF}
end;
function VectorIsZero(const v: Vector): Boolean;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorIsZero(const v: Vector): Boolean', '');
{$ENDIF}
result := (v.x = 0) and (v.y = 0);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorIsZero(const v: Vector): Boolean', '');
{$ENDIF}
end;
function VectorMagnitude(const v: Vector): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorMagnitude(const v: Vector): Single', '');
{$ENDIF}
result := Sqrt(VectorMagnitudeSq(v));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorMagnitude(const v: Vector): Single', '');
{$ENDIF}
end;
function VectorMagnitudeSq(const v: Vector): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorMagnitudeSq(const v: Vector): Single', '');
{$ENDIF}
result := (v.x * v.x) + (v.y * v.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorMagnitudeSq(const v: Vector): Single', '');
{$ENDIF}
end;
function DotProduct(const v1, v2: Vector): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'DotProduct(const v1, v2: Vector): Single', '');
{$ENDIF}
result := (v1.x * v2.x) + (v1.y * v2.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'DotProduct(const v1, v2: Vector): Single', '');
{$ENDIF}
end;
function VectorFromAngle(angle, magnitude: Single): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorFromAngle(angle, magnitude: Single): Vector', '');
{$ENDIF}
result := VectorTo(magnitude * sgGeometry.Cosine(angle), magnitude * sgGeometry.Sine(angle));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorFromAngle(angle, magnitude: Single): Vector', '');
{$ENDIF}
end;
function LineAsVector(const line: LineSegment): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineAsVector(const line: LineSegment): Vector', '');
{$ENDIF}
result.x := line.endPoint.x - line.startPoint.x;
result.y := line.endPoint.y - line.startPoint.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineAsVector(const line: LineSegment): Vector', '');
{$ENDIF}
end;
function VectorNormal(const v: Vector): Vector;
var
magnitude: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorNormal(const v: Vector): Vector', '');
{$ENDIF}
// magnitude calculated in place to
magnitude := VectorMagnitude( v );
if magnitude > 0 then
begin
result.x := -v.y / magnitude;
result.y := v.x / magnitude;
end
else
begin
// Return the zero/null vector
RaiseWarning('Attempting to get normal of zero/null vector. This is usually an error.');
result := v;
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorNormal(const v: Vector): Vector', '');
{$ENDIF}
end;
function LineNormal(const line: LineSegment): Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineNormal(const line: LineSegment): Vector', '');
{$ENDIF}
result := VectorNormal(LineAsVector(line));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineNormal(const line: LineSegment): Vector', '');
{$ENDIF}
end;
function CreateVectorFromAngle(angle, magnitude: Single): Vector;
begin
result := VectorFromAngle(angle,magnitude);
end;
function CreateVectorToPoint(const p1: Point2D): Vector;
begin
result := VectorToPoint(p1);
end;
function CreateVectorFromPoints(const p1, p2: Point2D): Vector;
begin
result := VectorFromPoints(p1,p2);
end;
function CreateLineAsVector(const line: LineSegment): Vector;
begin
result := LineAsVector(line);
end;
function CreateVectorFromPointToRect(x, y, rectX, rectY, rectWidth, rectHeight: Single): Vector; overload;
begin
result := VectorFromPointToRect(x,y,rectX,rectY,rectWidth,rectHeight);
end;
function CreateVectorFromPointToRect(x, y: Single; const rect: Rectangle): Vector; overload;
begin
result := VectorFromPointToRect(x,y,rect);
end;
function CreateVectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
begin
result := VectorFromPointToRect(pt,rect);
end;
//---------------------------------------------------------------------------
// Angle Calculation
//---------------------------------------------------------------------------
function VectorAngle(const v: Vector): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorAngle(const v: Vector): Single', '');
{$ENDIF}
if v.x = 0 then
begin
if v.y < 0 then result := -90
else result := 90; //Default to down screen if x and y are both 0
end
else if v.y = 0 then
begin
if v.x < 0 then result := 180
else result := 0;
end
else
begin
result := RadToDeg(arctan(v.y / v.x));
if v.x < 0 then
begin
if v.y < 0 then result := result - 180
else result := result + 180;
end;
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorAngle(const v: Vector): Single', '');
{$ENDIF}
end;
function CalculateAngle(x1, y1, x2, y2: Single): Single; overload;
var
o, a, oa, rads: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CalculateAngle(x1, y1, x2, y2: Single): Single', '');
{$ENDIF}
if (x1 = x2) and (y2 < y1) then result := -90
else if (x1 = x2) and (y2 >= y1) then result := 90
else if (y1 = y2) and (x2 < x1) then result := 180
else if (y1 = y2) and (x2 >= x1) then result := 0
else
begin
o := (y2 - y1);
a := (x2 - x1);
oa := o / a;
rads := arctan(oa);
result := RadToDeg(rads);
if x2 < x1 then
begin
if (y2 < y1) then result := result - 180
else result := result + 180;
end;
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CalculateAngle(x1, y1, x2, y2: Single): Single', '');
{$ENDIF}
end;
function CalculateAngle(s1, s2: Sprite): Single; overload;
var
cx1, cy1, cx2, cy2: Single;
sp1, sp2: SpritePtr;
begin
sp1 := ToSpritePtr(s1);
sp2 := ToSpritePtr(s2);
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CalculateAngle(s1, s2: Sprite): Single', '');
{$ENDIF}
if (not Assigned(s1)) or (not Assigned(s2)) then
begin
result := 0;
exit;
end;
cx1 := sp1^.position.x + SpriteWidth(s1) / 2;
cy1 := sp1^.position.y + SpriteHeight(s1) / 2;
cx2 := sp2^.position.x + SpriteWidth(s2) / 2;
cy2 := sp2^.position.y + SpriteHeight(s2) / 2;
result := CalculateAngle(cx1, cy1, cx2, cy2);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CalculateAngle(s1, s2: Sprite): Single', '');
{$ENDIF}
end;
function CalculateAngle(const v1, v2: Vector): Single; overload;
var
t1, t2: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CalculateAngle(const v1, v2: Vector): Single', '');
{$ENDIF}
t1 := CalculateAngle(0, 0, v1.x, v1.y);
t2 := CalculateAngle(0, 0, v2.x, v2.y);
result := t2 - t1;
if result > 180 then result := result - 360
else if result <= -180 then result := result + 360;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CalculateAngle(const v1, v2: Vector): Single', '');
{$ENDIF}
end;
function CalculateAngleBetween(const pt1, pt2: Point2D): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CalculateAngleBetween(const pt1, pt2: Point2D): Single', '');
{$ENDIF}
result := CalculateAngle(pt1.x, pt1.y, pt2.x, pt2.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CalculateAngleBetween(const pt1, pt2: Point2D): Single', '');
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Distance / Magnitude Calculations
//----------------------------------------------------------------------------
//
// Returns the square of the magnitude of the line
// to cut down on unnecessary Sqrt when in many cases
// DistancePointLine() squares the result
//
function LineMagnitudeSq(const line: LineSegment): Single; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineMagnitudeSq(const line: LineSegment): Single', '');
{$ENDIF}
result := (line.endPoint.x - line.startPoint.x) * (line.endPoint.x - line.startPoint.x) +
(line.endPoint.y - line.startPoint.y) * (line.endPoint.y - line.startPoint.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineMagnitudeSq(const line: LineSegment): Single', '');
{$ENDIF}
end;
function LineMagnitudeSq(x1, y1, x2, y2: single): single; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineMagnitudeSq(x1, y1, x2, y2: single): single', '');
{$ENDIF}
result := (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineMagnitudeSq(x1, y1, x2, y2: single): single', '');
{$ENDIF}
end;
function PointPointDistance(const pt1, pt2: Point2D): Single;
var
temp: Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointPointDistance(const pt1, pt2: Point2D): Single', '');
{$ENDIF}
temp := VectorTo(pt2.x - pt1.x, pt2.y - pt1.y);
result := VectorMagnitude(temp);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointPointDistance(const pt1, pt2: Point2D): Single', '');
{$ENDIF}
end;
//----------------------------------------------------------------------------
// Matrix2D Creation and Operation / Translation of Point/Vector Types
//----------------------------------------------------------------------------
function RotationMatrix(deg: Single): Matrix2D;
var
rads: Extended;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RotationMatrix(deg: Single): Matrix2D', '');
{$ENDIF}
rads := -deg * DEG_TO_RAD;
result.elements[0, 0] := System.Cos(rads);
result.elements[0, 1] := System.Sin(rads);
result.elements[0, 2] := 0;
result.elements[1, 0] := -System.Sin(rads);
result.elements[1, 1] := System.Cos(rads);
result.elements[1, 2] := 0;
result.elements[2, 0] := 0;
result.elements[2, 1] := 0;
result.elements[2, 2] := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RotationMatrix(deg: Single): Matrix2D', '');
{$ENDIF}
end;
function ScaleMatrix(const scale: Point2D): Matrix2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ScaleMatrix(const scale: Point2D): Matrix2D', '');
{$ENDIF}
result.elements[0, 0] := scale.x;
result.elements[0, 1] := 0;
result.elements[0, 2] := 0;
result.elements[1, 0] := 0;
result.elements[1, 1] := scale.y;
result.elements[1, 2] := 0;
result.elements[2, 0] := 0;
result.elements[2, 1] := 0;
result.elements[2, 2] := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ScaleMatrix(const scale: Point2D): Matrix2D', '');
{$ENDIF}
end;
function ScaleMatrix(scale: Single): Matrix2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ScaleMatrix(scale: Single): Matrix2D', '');
{$ENDIF}
result.elements[0, 0] := scale;
result.elements[0, 1] := 0;
result.elements[0, 2] := 0;
result.elements[1, 0] := 0;
result.elements[1, 1] := scale;
result.elements[1, 2] := 0;
result.elements[2, 0] := 0;
result.elements[2, 1] := 0;
result.elements[2, 2] := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ScaleMatrix(scale: Single): Matrix2D', '');
{$ENDIF}
end;
function IdentityMatrix(): Matrix2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'IdentityMatrix(): Matrix2D', '');
{$ENDIF}
result.elements[0, 0] := 1;
result.elements[0, 1] := 0;
result.elements[0, 2] := 0;
result.elements[1, 0] := 0;
result.elements[1, 1] := 1;
result.elements[1, 2] := 0;
result.elements[2, 0] := 0;
result.elements[2, 1] := 0;
result.elements[2, 2] := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'IdentityMatrix(): Matrix2D', '');
{$ENDIF}
end;
function TranslationMatrix(const pt: Point2D): Matrix2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TranslationMatrix(const pt: Point2D): Matrix2D', '');
{$ENDIF}
result := TranslationMatrix(pt.x, pt.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TranslationMatrix(const pt: Point2D): Matrix2D', '');
{$ENDIF}
end;
function TranslationMatrix(dx, dy: Single): Matrix2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TranslationMatrix(dx, dy: Single): Matrix2D', '');
{$ENDIF}
result := IdentityMatrix();
result.elements[0, 2] := dx;
result.elements[1, 2] := dy;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TranslationMatrix(dx, dy: Single): Matrix2D', '');
{$ENDIF}
end;
function ScaleRotateTranslateMatrix(const scale: Point2D; deg: Single; const translate: Point2D): Matrix2D;
var
rads: Extended;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ScaleRotateTranslateMatrix(const scale: Point2D', '');
{$ENDIF}
rads := -deg * DEG_TO_RAD;
result.elements[0, 0] := System.Cos(rads) * scale.x;
result.elements[0, 1] := System.Sin(rads);
result.elements[0, 2] := translate.x;
result.elements[1, 0] := -System.Sin(rads);
result.elements[1, 1] := System.Cos(rads) * scale.y;
result.elements[1, 2] := translate.y;
result.elements[2, 0] := 0;
result.elements[2, 1] := 0;
result.elements[2, 2] := 1;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ScaleRotateTranslateMatrix(const scale: Point2D', '');
{$ENDIF}
end;
function MatrixInverse(const m: Matrix2D): Matrix2D;
var
det, invdet: Single;
begin
det := m.elements[0, 0] * (m.elements[1, 1] * m.elements[2, 2] - m.elements[2, 1] * m.elements[1, 2]) -
m.elements[0, 1] * (m.elements[1, 0] * m.elements[2, 2] - m.elements[1, 2] * m.elements[2, 0]) +
m.elements[0, 2] * (m.elements[1, 0] * m.elements[2, 1] - m.elements[1, 1] * m.elements[2, 0]);
if det = 0 then //cant actually compute inverse!
begin
invdet := 3.4E38;
WriteLn('HERE');
end
else
invdet := 1 / det;
result.elements[0, 0] := (m.elements[1, 1] * m.elements[2, 2] - m.elements[2, 1] * m.elements[1, 2]) * invdet;
result.elements[0, 1] := (m.elements[0, 2] * m.elements[2, 1] - m.elements[0, 1] * m.elements[2, 2]) * invdet;
result.elements[0, 2] := (m.elements[0, 1] * m.elements[1, 2] - m.elements[0, 2] * m.elements[1, 1]) * invdet;
result.elements[1, 0] := (m.elements[1, 2] * m.elements[2, 0] - m.elements[1, 0] * m.elements[2, 2]) * invdet;
result.elements[1, 1] := (m.elements[0, 0] * m.elements[2, 2] - m.elements[0, 2] * m.elements[2, 0]) * invdet;
result.elements[1, 2] := (m.elements[1, 0] * m.elements[0, 2] - m.elements[0, 0] * m.elements[1, 2]) * invdet;
result.elements[2, 0] := (m.elements[1, 0] * m.elements[2, 1] - m.elements[2, 0] * m.elements[1, 1]) * invdet;
result.elements[2, 1] := (m.elements[2, 0] * m.elements[0, 1] - m.elements[0, 0] * m.elements[2, 1]) * invdet;
result.elements[2, 2] := (m.elements[0, 0] * m.elements[1, 1] - m.elements[1, 0] * m.elements[0, 1]) * invdet;
end;
function MatrixMultiply(const m1, m2: Matrix2D): Matrix2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'MatrixMultiply(const m1, m2: Matrix2D): Matrix2D', '');
{$ENDIF}
//unwound for performance optimisation
result.elements[0, 0] := m1.elements[0, 0] * m2.elements[0, 0] +
m1.elements[0, 1] * m2.elements[1, 0] +
m1.elements[0, 2] * m2.elements[2, 0];
result.elements[0, 1] := m1.elements[0, 0] * m2.elements[0, 1] +
m1.elements[0, 1] * m2.elements[1, 1] +
m1.elements[0, 2] * m2.elements[2, 1];
result.elements[0, 2] := m1.elements[0, 0] * m2.elements[0, 2] +
m1.elements[0, 1] * m2.elements[1, 2] +
m1.elements[0, 2] * m2.elements[2, 2];
result.elements[1, 0] := m1.elements[1, 0] * m2.elements[0, 0] +
m1.elements[1, 1] * m2.elements[1, 0] +
m1.elements[1, 2] * m2.elements[2, 0];
result.elements[1, 1] := m1.elements[1, 0] * m2.elements[0, 1] +
m1.elements[1, 1] * m2.elements[1, 1] +
m1.elements[1, 2] * m2.elements[2, 1];
result.elements[1, 2] := m1.elements[1, 0] * m2.elements[0, 2] +
m1.elements[1, 1] * m2.elements[1, 2] +
m1.elements[1, 2] * m2.elements[2, 2];
result.elements[2, 0] := m1.elements[2, 0] * m2.elements[0, 0] +
m1.elements[2, 1] * m2.elements[1, 0] +
m1.elements[2, 2] * m2.elements[2, 0];
result.elements[2, 1] := m1.elements[2, 0] * m2.elements[0, 1] +
m1.elements[2, 1] * m2.elements[1, 1] +
m1.elements[2, 2] * m2.elements[2, 1];
result.elements[2, 2] := m1.elements[2, 0] * m2.elements[0, 2] +
m1.elements[2, 1] * m2.elements[1, 2] +
m1.elements[2, 2] * m2.elements[2, 2];
{$IFDEF TRACE}
TraceExit('sgGeometry', 'MatrixMultiply(const m1, m2: Matrix2D): Matrix2D', '');
{$ENDIF}
end;
function MatrixToString(const m: Matrix2D) : String;
var
i, j: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'MatrixToString(const m: Matrix2D) : String', '');
{$ENDIF}
result := '-------------------------------' + LineEnding;
for i := 0 to 2 do
begin
result := result + '|';
for j := 0 to 2 do
begin
result := result + ' ' + FormatFloat('###0.00', m.elements[i,j]) + ' ';
end;
result := result + '|' + LineEnding;
end;
result := result + '-------------------------------';
{$IFDEF TRACE}
TraceExit('sgGeometry', 'MatrixToString(const m: Matrix2D) : String', '');
{$ENDIF}
end;
function MatrixMultiply(const m: Matrix2D; const v: Vector): Vector; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'MatrixMultiply(const m: Matrix2D', '');
{$ENDIF}
result.x := v.x * m.elements[0,0] + v.y * m.elements[0,1] + m.elements[0,2];
result.y := v.x * m.elements[1,0] + v.y * m.elements[1,1] + m.elements[1,2];
{$IFDEF TRACE}
TraceExit('sgGeometry', 'MatrixMultiply(const m: Matrix2D', '');
{$ENDIF}
end;
procedure ApplyMatrix(const m: Matrix2D; var tri: Triangle);
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ApplyMatrix(const m: Matrix2D', '');
{$ENDIF}
tri.points[0] := MatrixMultiply(m, tri.points[0]);
tri.points[1] := MatrixMultiply(m, tri.points[1]);
tri.points[2] := MatrixMultiply(m, tri.points[2]);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ApplyMatrix(const m: Matrix2D', '');
{$ENDIF}
end;
procedure ApplyMatrix(const m: Matrix2D; var pts: Point2DArray);
var
i: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ApplyMatrix(const m: Matrix2D', '');
{$ENDIF}
for i := 0 to High(pts) do
begin
pts[i] := MatrixMultiply(m, pts[i]);
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ApplyMatrix(const m: Matrix2D', '');
{$ENDIF}
end;
{$ifdef FPC}
operator * (const m: Matrix2D; const v: Vector) r : Vector;
begin
r := MatrixMultiply(m, v);
end;
{$endif}
{$ifdef FPC}
operator * (const m1, m2: Matrix2D) r : Matrix2D;
begin
r := MatrixMultiply(m2, m1);
end;
{$endif}
//----------------------------------------------------------------------------
// Cosine/Sin/Tan accepting degrees
//----------------------------------------------------------------------------
function Cosine(angle: Single): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'Cosine(angle: Single): Single', '');
{$ENDIF}
result := System.Cos(DegToRad(angle));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'Cosine(angle: Single): Single', '');
{$ENDIF}
end;
function Sine(angle: Single): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'Sine(angle: Single): Single', '');
{$ENDIF}
result := System.Sin(DegToRad(angle));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'Sine(angle: Single): Single', '');
{$ENDIF}
end;
function Tangent(angle: Single): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'Tangent(angle: Single): Single', '');
{$ENDIF}
result := Math.Tan(DegToRad(angle));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'Tangent(angle: Single): Single', '');
{$ENDIF}
end;
const
EPS = 0.01; // smallest positive value: less than that to be considered zero
EPSEPS = EPS * EPS; // and its square
function PointLineDistance(x, y: Single; const line: LineSegment): Single; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointLineDistance(x, y: Single', '');
{$ENDIF}
result := PointLineDistance(PointAt(x, y), line);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointLineDistance(x, y: Single', '');
{$ENDIF}
end;
function PointLineDistance(const pt: Point2D; const line: LineSegment): Single; overload;
var
sqLineMag, u: Single;
intersect: Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointLineDistance(const pt: Point2D', '');
{$ENDIF}
// see Paul Bourke's original article(s)
// square of line's magnitude (see note in function LineMagnitude)
sqLineMag := LineMagnitudeSq(line);
if SqLineMag < EPSEPS then
begin
RaiseException('Cannot determine intersection point on line, line is too short');
exit;
end;
//squared unit vector
u := ( (pt.x - line.startPoint.x) * (line.endPoint.x - line.startPoint.x) +
(pt.y - line.startPoint.y) * (line.endPoint.y - line.startPoint.y) ) / sqLineMag;
if (u < EPS) or (u > 1) then
begin
// Closest point does not fall within the line segment,
// take the shorter distance to an endpoint
intersect.x := LineMagnitudeSq(pt.x, pt.y, line.startPoint.x, line.startPoint.y);
intersect.y := LineMagnitudeSq(pt.x, pt.y, line.endPoint.x, line.endPoint.y);
result := min(intersect.x, intersect.y);
end // if (u < EPS) or (u > 1)
else
begin
// Intersecting point is on the line, use the formula
intersect.x := line.startPoint.x + u * (line.endPoint.x - line.startPoint.x);
intersect.y := line.startPoint.y + u * (line.endPoint.y - line.startPoint.y);
result := LineMagnitudeSq(pt.x, pt.y, intersect.x, intersect.y);
end; // else NOT (u < EPS) or (u > 1)
// finally convert to actual distance not its square
result := sqrt(result);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointLineDistance(const pt: Point2D', '');
{$ENDIF}
end;
function ClosestPointOnCircle(const fromPt: Point2D; const c: Circle): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnCircle(const fromPt: Point2D', '');
{$ENDIF}
result := AddVectors(VectorMultiply(UnitVector(VectorFromPoints(c.center, fromPt)), c.radius), c.center);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnCircle(const fromPt: Point2D', '');
{$ENDIF}
end;
function ClosestPointOnLine(x, y: Single; const line: LineSegment): Point2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnLine(x, y: Single', '');
{$ENDIF}
result := ClosestPointOnLine(PointAt(x, y), line);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnLine(x, y: Single', '');
{$ENDIF}
end;
function ClosestPointOnLine(const fromPt: Point2D; const line: LineSegment): Point2D; overload;
var
sqLineMag, u: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnLine(const fromPt: Point2D', '');
{$ENDIF}
// see Paul Bourke's original article(s)
// square of line's magnitude (see note in function LineMagnitude)
sqLineMag := LineMagnitudeSq(line);
if SqLineMag < EPSEPS then begin RaiseWarning('Cannot determine intersection point on line, line is too short'); exit; end;
u := ( (fromPt.x - line.startPoint.x)*(line.endPoint.x - line.startPoint.x) + (fromPt.y - line.startPoint.y) * (line.endPoint.y - line.startPoint.y) ) / sqLineMag;
if (u < EPS) or (u > 1) then
begin
// Closest point does not fall within the line segment,
// take the shorter distance to an endpoint
if LineMagnitudeSq(fromPt.x, fromPt.y, line.startPoint.x, line.startPoint.y) < LineMagnitudeSq(fromPt.x, fromPt.y, line.endPoint.x, line.endPoint.y) then
result := line.startPoint
else
result := line.endPoint;
end // if (u < EPS) or (u > 1)
else
begin
// Intersecting point is on the line, use the formula
result.x := line.startPoint.x + u * (line.endPoint.x - line.startPoint.x);
result.y := line.startPoint.y + u * (line.endPoint.y - line.startPoint.y);
end; // else NOT (u < EPS) or (u > 1)
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnLine(const fromPt: Point2D', '');
{$ENDIF}
end;
function ClosestPointOnLineFromCircle(const c: Circle; const line: LineSegment): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnLineFromCircle(const c: Circle', '');
{$ENDIF}
result := ClosestPointOnLine(c.center, line);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnLineFromCircle(const c: Circle', '');
{$ENDIF}
end;
function ClosestPointOnLinesFromCircle(const c: Circle; const lines: LinesArray): Point2D;
var
i: Longint;
dst, minDist: Single;
pt: Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnLinesFromCircle(const c: Circle', '');
{$ENDIF}
minDist := -1;
for i := Low(lines) to High(lines) do
begin
pt := ClosestPointOnLineFromCircle(c, lines[i]);
dst := PointPointDistance(pt, c.center);
if (minDist > dst) or (minDist < 0) then
begin
minDist := dst;
result := pt;
end;
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnLinesFromCircle(const c: Circle', '');
{$ENDIF}
end;
function ClosestPointOnRectFromCircle(const c: Circle; const rect: Rectangle): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'ClosestPointOnRectFromCircle(const c: Circle', '');
{$ENDIF}
result := ClosestPointOnLinesFromCircle(c, LinesFrom(rect));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'ClosestPointOnRectFromCircle(const c: Circle', '');
{$ENDIF}
end;
function InsetRectangle(const rect: Rectangle; insetAmount: Single): Rectangle;
var
dblAmt: Single;
begin
dblAmt := 2 * insetAmount;
if (rect.width <= dblAmt) or (rect.height <= dblAmt) then begin result := rect; exit; end;
result := RectangleFrom(rect.x + insetAmount, rect.y + insetAmount, rect.width - dblAmt, rect.height - dblAmt)
end;
function RectangleFrom(const c: Circle): Rectangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const c: Circle): Rectangle', '');
{$ENDIF}
result.x := c.center.x - c.radius;
result.y := c.center.y - c.radius;
result.width := Ceiling(2 * c.radius);
result.height := result.width;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const c: Circle): Rectangle', '');
{$ENDIF}
end;
function RectangleFrom(const pt1, pt2: Point2D): Rectangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const pt1, pt2: Point2D): Rectangle', '');
{$ENDIF}
result.x := pt1.x;
result.y := pt1.y;
result.width := Ceiling(pt2.x - pt1.x);
result.height := Ceiling(pt2.y - pt1.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const pt1, pt2: Point2D): Rectangle', '');
{$ENDIF}
end;
function RectangleFrom(const tri: Triangle): Rectangle; overload;
var
minX, minY, maxX, maxY: Single;
i: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const tri: Triangle): Rectangle', '');
{$ENDIF}
minX := tri.points[0].x; maxX := tri.points[0].x;
minY := tri.points[0].y; maxY := tri.points[0].y;
for i := 1 to 2 do
begin
if tri.points[i].x < minX then minX := tri.points[i].x
else if tri.points[i].x > maxX then maxX := tri.points[i].x;
if tri.points[i].y < minY then minY := tri.points[i].y
else if tri.points[i].y > maxY then maxY := tri.points[i].y;
end;
result.x := minX;
result.y := minY;
result.width := Ceiling(maxX - minX);
result.height := Ceiling(maxY - minY);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const tri: Triangle): Rectangle', '');
{$ENDIF}
end;
function RectangleFrom(const lines: LinesArray): Rectangle; overload;
var
minX, minY, maxX, maxY: Single;
i: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const lines: LinesArray): Rectangle', '');
{$ENDIF}
if Length(lines) = 0 then exit;
minX := lines[0].startPoint.x; maxX := lines[0].startPoint.x;
minY := lines[0].startPoint.y; maxY := lines[0].startPoint.y;
for i := 0 to High(lines) do
begin
if lines[i].startPoint.x < minX then minX := lines[i].startPoint.x
else if lines[i].startPoint.x > maxX then maxX := lines[i].startPoint.x;
if lines[i].startPoint.y < minY then minY := lines[i].startPoint.y
else if lines[i].startPoint.y > maxY then maxY := lines[i].startPoint.y;
if lines[i].endPoint.x < minX then minX := lines[i].endPoint.x
else if lines[i].endPoint.x > maxX then maxX := lines[i].endPoint.x;
if lines[i].endPoint.y < minY then minY := lines[i].endPoint.y
else if lines[i].endPoint.y > maxY then maxY := lines[i].endPoint.y;
end;
result.x := minX;
result.y := minY;
result.width := Ceiling(maxX - minX);
result.height := Ceiling(maxY - minY);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const lines: LinesArray): Rectangle', '');
{$ENDIF}
end;
function RectangleFrom(const line: LineSegment): Rectangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const line: LineSegment): Rectangle', '');
{$ENDIF}
result.x := Min(line.startPoint.x, line.endPoint.x);
result.y := Min(line.startPoint.y, line.endPoint.y);
result.width := Ceiling(Max(line.startPoint.x, line.endPoint.x) - result.x);
result.height := Ceiling(Max(line.startPoint.y, line.endPoint.y) - result.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const line: LineSegment): Rectangle', '');
{$ENDIF}
end;
function CreateRectangle(x, y, w, h: Single): Rectangle; overload;
begin
result := RectangleFrom(x,y,w,h);
end;
function CreateRectangle(const pt1, pt2: Point2D): Rectangle; overload;
begin
result := RectangleFrom(pt1,pt2);
end;
function CreateRectangle(const pt: Point2D; width, height: Single): Rectangle; overload;
begin
result := RectangleFrom(pt,width,height);
end;
function CreateRectangle(const line: LineSegment): Rectangle; overload;
begin
result := RectangleFrom(line);
end;
function CreateRectangle(const c: Circle): Rectangle; overload;
begin
result := RectangleFrom(c);
end;
function CreateRectangle(const tri: Triangle): Rectangle; overload;
begin
result := RectangleFrom(tri);
end;
function CreateRectangle(const lines: LinesArray): Rectangle; overload;
begin
result := RectangleFrom(lines);
end;
function PointOnLine(const pt: Point2D; const line: LineSegment): Boolean;
const SMALL = 0.9;
function SimpleComparisonXSame(): Boolean;
var
minY, maxY: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointOnLine(const pt: Point2D', '');
{$ENDIF}
minY := Min(line.startPoint.y, line.endPoint.Y);
maxY := Max(line.startPoint.y, line.endPoint.Y);
result :=
(pt.x >= line.startPoint.x - SMALL) and (pt.x <= line.startPoint.x + SMALL) and
(pt.y >= minY) and (pt.y <= maxY);
end;
function SimpleComparisonYSame(): Boolean;
var
minX, maxX: Single;
begin
minX := Min(line.startPoint.x, line.endPoint.x);
maxX := Max(line.startPoint.x, line.endPoint.x);
result :=
(pt.y >= line.startPoint.y - SMALL) and (pt.y <= line.startPoint.y + SMALL) and
(pt.x >= minX) and (pt.x <= maxX);
end;
var
sqLineMag, lx, ly, m, c : Single;
begin
//Lines Magnitude must be at least 0.0001
sqLineMag := LineMagnitudeSq(line);
if SqLineMag < EPSEPS then
begin
RaiseException('Cannot determine if point is on line, line is too short'); exit;
end;
//Obtain the other variables for the Line Algorithm
if line.endPoint.x = line.startPoint.x then
begin
result := SimpleComparisonXSame();
exit;
end;
if line.endPoint.y = line.startPoint.y then
begin
result := SimpleComparisonYSame();
exit;
end;
m := (line.endPoint.y - line.startPoint.y) / (line.endPoint.x - line.startPoint.x);
c := line.startPoint.y - (m * line.startPoint.x);
ly := (m * pt.x) + c;
lx := (pt.y - c) / m;
result := (lx >= pt.x - SMALL) and
(lx <= pt.x + SMALL) and
(ly >= pt.y - SMALL) and
(ly <= pt.y + SMALL) and
PointInRect(pt, RectangleFrom(line));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointOnLine(const pt: Point2D', '');
{$ENDIF}
end;
function PointOnLine(const pt: Point2D; x, y, endX, endY: Single): Boolean;
begin
result := PointOnLine(pt, LineFrom(x, y, endX, endY));
end;
function PointOnPoint(const pt1,pt2:Point2d):Boolean;
begin
if ((pt1.X = pt2.X) AND (pt1.Y = pt2.Y)) then
begin
result:=True;
end
else
begin
result:=False;
end
end;
function LineFrom(const pt1, pt2: Point2D): LineSegment; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineFrom(const pt1, pt2: Point2D): LineSegment', '');
{$ENDIF}
result := LineFrom(pt1.x, pt1.y, pt2.x, pt2.y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineFrom(const pt1, pt2: Point2D): LineSegment', '');
{$ENDIF}
end;
function LineFrom(x1, y1, x2, y2: Single): LineSegment; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineFrom(x1, y1, x2, y2: Single): LineSegment', '');
{$ENDIF}
result.startPoint.x := x1;
result.startPoint.y := y1;
result.endPoint.x := x2;
result.endPoint.y := y2;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineFrom(x1, y1, x2, y2: Single): LineSegment', '');
{$ENDIF}
end;
function CreateLine(x1, y1, x2, y2: Single): LineSegment; overload;
begin
result := LineFrom(x1,y1,x2,y2);
end;
function CreateLine(const pt1, pt2: Point2D): LineSegment; overload;
begin
result := LineFrom(pt1,pt2);
end;
function RectangleCenter(const rect: Rectangle): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleCenter(const rect: Rectangle): Point2D', '');
{$ENDIF}
result.x := rect.x + (rect.width / 2);
result.y := rect.y + (rect.height / 2);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleCenter(const rect: Rectangle): Point2D', '');
{$ENDIF}
end;
function PointAt(x, y: Single): Point2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointAt(x, y: Single): Point2D', '');
{$ENDIF}
result.x := x;
result.y := y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointAt(x, y: Single): Point2D', '');
{$ENDIF}
end;
function RandomScreenPoint(): Point2D;
begin
result := PointAt(Rnd() * ScreenWidth(), Rnd() * ScreenHeight());
end;
function PointToString(const pt: Point2D): String;
begin
result := 'Pt @' + FloatToStr(pt.x) + ':' + FloatToStr(pt.y);
end;
function VectorToString(const v: Vector): String;
begin
result := 'Vec -> ' + FloatToStr(v.x) + ':' + FloatToStr(v.y);
end;
function TriangleToString(const tri: Triangle): String;
begin
result := 'Triangle @' + PointToString(tri.points[0]) + ' - ' + PointToString(tri.points[1]) + ' - ' + PointToString(tri.points[2]);
end;
function RectangleToString(const rect:Rectangle): String;
begin
result := 'Rect @' + FloatToStr(rect.x) + ':' + FloatToStr(rect.y) + ' ' + FloatToStr(rect.width) + 'x' + FloatToStr(rect.height);
end;
function LineToString(const ln: LineSegment): String;
begin
result := 'From ' + PointToString(ln.startPoint) + ' to ' + PointToString(ln.endPoint);
end;
function PointAt(const startPoint: Point2D; const offset: Vector): Point2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointAt(const startPoint: Point2D', '');
{$ENDIF}
result.x := startPoint.x + offset.x;
result.y := startPoint.y + offset.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointAt(const startPoint: Point2D', '');
{$ENDIF}
end;
function LineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineFromVector(const pt: Point2D', '');
{$ENDIF}
result := LineFromVector(pt.x, pt.Y, mv);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineFromVector(const pt: Point2D', '');
{$ENDIF}
end;
function LineFromVector(x, y: Single; const mv: Vector): LineSegment; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineFromVector(x, y: Single', '');
{$ENDIF}
result.startPoint.x := x;
result.startPoint.y := y;
result.endPoint.x := x + mv.x;
result.endPoint.y := y + mv.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineFromVector(x, y: Single', '');
{$ENDIF}
end;
function LineFromVector(const mv: Vector): LineSegment; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineFromVector(const mv: Vector): LineSegment', '');
{$ENDIF}
result := LineFromVector(0, 0, mv);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineFromVector(const mv: Vector): LineSegment', '');
{$ENDIF}
end;
function CreateLineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
begin
result := LineFromVector(pt,mv);
end;
function CreateLineFromVector(x, y: Single; const mv: Vector): LineSegment; overload;
begin
result := LineFromVector(x,y,mv);
end;
function CreateLineFromVector(const mv: Vector): LineSegment; overload;
begin
result := LineFromVector(mv);
end;
function RectangleAfterMove(const rect: Rectangle; const mv: Vector): Rectangle;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleAfterMove(const rect: Rectangle', '');
{$ENDIF}
result := rect;
result.x := result.x + mv.x;
result.y := result.y + mv.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleAfterMove(const rect: Rectangle', '');
{$ENDIF}
end;
function RectangleTop(const rect: Rectangle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleTop(const rect: Rectangle): Single', '');
{$ENDIF}
if rect.height > 0 then result := rect.y
else result := rect.y + rect.height; //add negative height
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleTop(const rect: Rectangle): Single', '');
{$ENDIF}
end;
function RectangleBottom(const rect: Rectangle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleBottom(const rect: Rectangle): Single', '');
{$ENDIF}
if rect.height > 0 then result := rect.y + rect.height
else result := rect.y; //y is bottom most
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleBottom(const rect: Rectangle): Single', '');
{$ENDIF}
end;
function RectangleLeft(const rect: Rectangle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleLeft(const rect: Rectangle): Single', '');
{$ENDIF}
if rect.width > 0 then result := rect.x
else result := rect.x + rect.width; //add negative width
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleLeft(const rect: Rectangle): Single', '');
{$ENDIF}
end;
function RectangleRight(const rect: Rectangle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleRight(const rect: Rectangle): Single', '');
{$ENDIF}
if rect.width > 0 then result := rect.x + rect.width
else result := rect.x; //x is right most
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleRight(const rect: Rectangle): Single', '');
{$ENDIF}
end;
function RectangleTopLeft(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleLeft(rect), RectangleTop(rect));
end;
function RectangleTopRight(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleRight(rect), RectangleTop(rect));
end;
function RectangleBottomLeft(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleLeft(rect), RectangleBottom(rect));
end;
function RectangleBottomRight(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleRight(rect), RectangleBottom(rect));
end;
function RectangleCenterTop(const rect: Rectangle): Point2D;
begin
result := PointAt((RectangleLeft(rect) + RectangleRight(rect)) / 2, RectangleTop(rect));
end;
function RectangleCenterBottom(const rect: Rectangle): Point2D;
begin
result := PointAt((RectangleLeft(rect) + RectangleRight(rect)) / 2, RectangleBottom(rect));
end;
function RectangleCenterLeft(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleLeft(rect), (RectangleTop(rect) + RectangleBottom(rect)) / 2);
end;
function RectangleCenterRight(const rect: Rectangle): Point2D;
begin
result := PointAt(RectangleRight(rect), (RectangleTop(rect) + RectangleBottom(rect)) / 2);
end;
function RectangleOffset(const rect: Rectangle; const vec: Vector): Rectangle;
begin
result := RectangleFrom(PointAdd(vec, RectangleTopLeft(rect)), rect.width, rect.height);
end;
function RectangleFrom(x, y, w, h: Single): Rectangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(x, y: Single', '');
{$ENDIF}
result.x := x;
result.y := y;
result.width := w;
result.height := h;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(x, y: Single', '');
{$ENDIF}
end;
function RectangleFrom(const pt: Point2D; width, height: Single): Rectangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectangleFrom(const pt: Point2D', '');
{$ENDIF}
result := RectangleFrom(pt.x, pt.y, width, height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectangleFrom(const pt: Point2D', '');
{$ENDIF}
end;
function TriangleFrom(ax, ay, bx, by, cx, cy: Single): Triangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TriangleFrom(ax, ay, bx, by, cx, cy: Single): Triangle', '');
{$ENDIF}
result := TriangleFrom(PointAt(ax, ay), PointAt(bx, by), PointAt(cx, cy));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TriangleFrom(ax, ay, bx, by, cx, cy: Single): Triangle', '');
{$ENDIF}
end;
function TriangleFrom(const a, b, c: Point2D): Triangle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TriangleFrom(const a, b, c: Point2D): Triangle', '');
{$ENDIF}
result.points[0] := a;
result.points[1] := b;
result.points[2] := c;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TriangleFrom(const a, b, c: Point2D): Triangle', '');
{$ENDIF}
end;
function CreateTriangle(const a, b, c: Point2D): Triangle; overload;
begin
result := TriangleFrom(a,b,c);
end;
function CreateTriangle(ax, ay, bx, by, cx, cy: Single): Triangle; overload;
begin
result := TriangleFrom(ax, ay, bx, by, cx, cy);
end;
function PointInTriangle(const pt : Point2D; const tri : Triangle): Boolean;
var
v0, v1, v2 : Vector;
a, b, c, p: Vector;
dot00, dot01, dot02, dot11, dot12 : Single;
invDenom, u, v: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInTriangle(const pt : Point2D', '');
{$ENDIF}
//Convert Points to vectors
p := VectorToPoint(pt);
a := VectorToPoint(tri.points[0]);
b := VectorToPoint(tri.points[1]);
c := VectorToPoint(tri.points[2]);
// Compute vectors
v0 := SubtractVectors(c, a);
v1 := SubtractVectors(b, a);
v2 := SubtractVectors(p, a);
// Compute dot products
dot00 := DotProduct(v0, v0);
dot01 := DotProduct(v0, v1);
dot02 := DotProduct(v0, v2);
dot11 := DotProduct(v1, v1);
dot12 := DotProduct(v1, v2);
// Compute barycentric coordinates
if dot00 * dot11 - dot01 * dot01 = 0 then
begin
result := false;
exit;
end;
invDenom := 1 / (dot00 * dot11 - dot01 * dot01);
u := (dot11 * dot02 - dot01 * dot12) * invDenom;
v := (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
result := ((u > 0) and (v > 0) and (u + v < 1));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInTriangle(const pt : Point2D', '');
{$ENDIF}
end;
function PointInCircle(const pt: Point2D; const c: Circle): Boolean;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInCircle(const pt: Point2D', '');
{$ENDIF}
result := PointPointDistance(pt, c.center) <= c.radius;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInCircle(const pt: Point2D', '');
{$ENDIF}
end;
function PointInCircle(ptX, ptY, cX, cY, radius: Single): Boolean;
begin
result := PointInCircle(PointAt(ptX, ptY), CircleAt(cX, cY, radius));
end;
function PointInCircle(const pt: Point2D; x, y, radius: Single): Boolean;
begin
result := PointInCircle(pt.x, pt.y, x, y, radius);
end;
function TriangleBarycenter(const tri: Triangle): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TriangleBarycenter(const tri: Triangle): Point2D', '');
{$ENDIF}
result.x := (tri.points[0].x + tri.points[1].x + tri.points[2].x) / 3;
result.y := (tri.points[0].y + tri.points[1].y + tri.points[2].y) / 3;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TriangleBarycenter(const tri: Triangle): Point2D', '');
{$ENDIF}
end;
function LineMidPoint(const line: LineSegment): Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineMidPoint(const line: LineSegment): Point2D', '');
{$ENDIF}
result.x := line.startPoint.x + (line.endPoint.x - line.startPoint.x) / 2;
result.y := line.startPoint.y + (line.endPoint.y - line.startPoint.y) / 2;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineMidPoint(const line: LineSegment): Point2D', '');
{$ENDIF}
end;
function TriangleAABB(const tri: Triangle): Rectangle;
var
minPt, maxPt: Point2D;
i: Longint;
begin
minPt := tri.points[0];
maxPt := tri.points[0];
for i := 1 to 2 do
begin
if minPt.x > tri.points[i].x then minPt.x := tri.points[i].x
else if maxPt.x < tri.points[i].x then maxPt.x := tri.points[i].x;
if minPt.y > tri.points[i].y then minPt.y := tri.points[i].y
else if maxPt.y < tri.points[i].y then maxPt.y := tri.points[i].y;
end;
result := RectangleFrom(minPt, maxPt);
end;
function TrianglesRectangleIntersect(const tri: TriangleArray; const rect: Rectangle): Boolean;
var
i: Longint;
begin
for i := Low(tri) to High(tri) do
begin
if TriangleRectangleIntersect(tri[i], rect) then
begin
result := true;
exit;
end;
end;
// none intersect
result := false;
end;
function TriangleRectangleIntersect(const tri: Triangle; const rect: Rectangle): Boolean;
var
r, l, t, b: Single;
function _TriLineRectangleTest(const pt1, pt2: Point2D): Boolean;
var
m,c: Single;
top_intersection, bottom_intersection: Single;
toptrianglepoint, bottomtrianglepoint: Single;
topoverlap, botoverlap: Single;
begin
if (pt2.x - pt1.x = 0) then m := 0
else
m := (pt2.y - pt1.y) / (pt2.x - pt1.x);
c := pt1.y - (m * pt1.x);
// if the line is going up from right to left then the top intersect point is on the left
if m > 0 then
begin
top_intersection := m * l + c;
bottom_intersection := m * r + c;
end
// otherwise it's on the right
else
begin
top_intersection := m * l + c;
bottom_intersection := m * l + c;
end;
// work out the top and bottom extents for the triangle
if pt1.y < pt2.y then
begin
toptrianglepoint := pt1.y;
bottomtrianglepoint := pt2.y;
end
else
begin
toptrianglepoint := pt2.y;
bottomtrianglepoint := pt1.y;
end;
// and calculate the overlap between those two bounds
topoverlap := iif(top_intersection>toptrianglepoint, top_intersection, toptrianglepoint);
botoverlap := iif(bottom_intersection<bottomtrianglepoint, bottom_intersection, bottomtrianglepoint);
// (topoverlap<botoverlap) :
// if the intersection isn't the right way up then we have no overlap
// (!((botoverlap<t) || (topoverlap>b)) :
// If the bottom overlap is higher than the top of the rectangle or the top overlap is
// lower than the bottom of the rectangle we don't have intersection. So return the negative
// of that. Much faster than checking each of the points is within the bounds of the rectangle.
result := (topoverlap<botoverlap) and (not((botoverlap<t) or (topoverlap>b)));
end;
begin
result := false;
// Perform bounding box check
if not RectanglesIntersect(rect, TriangleAABB(tri)) then exit;
r := RectangleRight(rect);
l := RectangleLeft(rect);
t := RectangleTop(rect);
b := RectangleBottom(rect);
// Check line intersects see http://sebleedelisle.com/2009/05/super-fast-trianglerectangle-intersection-test/
result := _TriLineRectangleTest(tri.points[0],tri.points[1])
or _TriLineRectangleTest(tri.points[1],tri.points[2])
or _TriLineRectangleTest(tri.points[2],tri.points[0]);
if not result then
begin
//check rect points in triangle
result := PointInTriangle(PointAt(l, t), tri) or
PointInTriangle(PointAt(l, b), tri) or
PointInTriangle(PointAt(r, t), tri) or
PointInTriangle(PointAt(r, b), tri);
end;
end;
function RectanglesIntersect(const rect1, rect2: Rectangle): Boolean;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RectanglesIntersect(const rect1, rect2: Rectangle): Boolean', '');
{$ENDIF}
if RectangleBottom(rect1) < RectangleTop(rect2) then result := false
else if RectangleTop(rect1) > RectangleBottom(rect2) then result := false
else if RectangleRight(rect1) < RectangleLeft(rect2) then result := false
else if RectangleLeft(rect1) > RectangleRight(rect2) then result := false
else result := true;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RectanglesIntersect(const rect1, rect2: Rectangle): Boolean', '');
{$ENDIF}
end;
function LinesIntersect(const lines, lines1: LinesArray): Boolean;
var
i: Longint;
begin
result := false;
if (Length(lines) = 0) or (Length(lines1) = 0) then exit;
for i := 0 to High(lines) do
begin
if LineIntersectsLines(lines[i], lines1) then
begin
result := True;
exit;
end;
end;
end;
function LinesRectIntersect(const lines: LinesArray; const r: Rectangle): Boolean;
begin
result := LinesIntersect(lines, LinesFrom(r));
end;
function Intersection(const rect1, rect2: Rectangle): Rectangle;
var
r, l, b, t: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'Intersection(const rect1, rect2: Rectangle): Rectangle', '');
{$ENDIF}
if RectangleBottom(rect1) > RectangleBottom(rect2) then b := RectangleBottom(rect2)
else b := RectangleBottom(rect1);
if RectangleTop(rect1) < RectangleTop(rect2) then t := RectangleTop(rect2)
else t := RectangleTop(rect1);
if RectangleRight(rect1) > RectangleRight(rect2) then r := RectangleRight(rect2)
else r := RectangleRight(rect1);
if RectangleLeft(rect1) < RectangleLeft(rect2) then l := RectangleLeft(rect2)
else l := RectangleLeft(rect1);
if (r < l) or (b < t) then
begin
result := RectangleFrom(0, 0, 0, 0);
exit;
end;
result := RectangleFrom(l, t, Ceiling(r - l), Ceiling(b - t));
// WriteLn();
// WriteLn('b ', b);
// WriteLn('t ', t);
// WriteLn(RectangleToString(rect1));
// WriteLn(RectangleToString(rect2));
// WriteLn(RectangleToString(result));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'Intersection(const rect1, rect2: Rectangle): Rectangle', '');
{$ENDIF}
end;
function RayCircleIntersectDistance(const ray_origin: Point2D; const ray_heading:Vector; const c: Circle): Single;
var
to_circle, unit_heading: Vector;
length, v, d: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RayCircleIntersectDistance(const ray_origin: Point2D', '');
{$ENDIF}
unit_heading := UnitVector(ray_heading);
to_circle := VectorFromPoints(ray_origin, c.center);
length := VectorMagnitude(to_circle);
v := DotProduct(to_circle, unit_heading);
d := c.radius*c.radius - (length*length - v*v);
// if there was no intersection, return -1
if d < 0.0 then
result := -1.0
// return the distance to the (first) intersection point
else
result := (v - sqrt(d));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RayCircleIntersectDistance(const ray_origin: Point2D', '');
{$ENDIF}
end;
procedure WidestPoints(const c: Circle; const along: Vector; out pt1, pt2: Point2D);
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'WidestPoints(const c: Circle', '');
{$ENDIF}
pt1 := AddVectors(c.center, VectorMultiply(UnitVector(along), c.radius));
pt2 := AddVectors(c.center, VectorMultiply(UnitVector(along), -c.radius));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'WidestPoints(const c: Circle', '');
{$ENDIF}
end;
{
''' Given a point P and a circle of radius R centered at C, determine the
two points T1, T2 on the circle that intersect with the tangents from P
to the circle. Returns False if P is within the circle '''
}
function TangentPoints(const fromPt: Point2D; const c: Circle; out p1, p2: Point2D): Boolean;
var
pmC: Vector;
sqr_len, r_sqr, inv_sqr_len, root: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'TangentPoints(const fromPt: Point2D', '');
{$ENDIF}
pmC := VectorFromPoints(fromPt, c.center);
sqr_len := VectorMagnitudeSq(PmC);
r_sqr := c.radius*c.radius;
// Quick check for P inside the circle, return False if so
if sqr_len <= r_sqr then
begin
result := False; // tangent objects are not returned.
exit;
end;
// time to work out the real tangent points then
inv_sqr_len := 1.0 / sqr_len;
root := sqrt(abs(sqr_len - r_sqr));
p1.x := c.center.x + c.radius*(c.radius*pmC.x - pmC.y*root)*inv_sqr_len;
p1.y := c.center.y + c.radius*(c.radius*pmC.y + pmC.x*root)*inv_sqr_len;
p2.x := c.center.x + c.radius*(c.radius*pmC.x + pmC.y*root)*inv_sqr_len;
p2.y := c.center.y + c.radius*(c.radius*pmC.y - pmC.x*root)*inv_sqr_len;
result := True;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'TangentPoints(const fromPt: Point2D', '');
{$ENDIF}
end;
function RayIntersectionPoint(const fromPt: Point2D; const heading: Vector; const line: LineSegment; out pt: Point2D) : Boolean;
var
rayLine: LineSegment;
combMag: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'RayIntersectionPoint(const fromPt: Point2D', '');
{$ENDIF}
result := False;
rayLine := LineFromVector(fromPt, heading);
// Get where the line intersect
if not LineIntersectionPoint(rayLine, line, pt) then exit;
//DrawLine(ColorWhite, fromPt, pt);
combMag := VectorMagnitude(AddVectors(UnitVector(VectorFromPoints(fromPt, pt)), UnitVector(heading)));
// WriteLn(combMag:4:2);
// Test that pt is forward of fromPt (given heading)
if combMag < 1 then exit; //behind point
result := True;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'RayIntersectionPoint(const fromPt: Point2D', '');
{$ENDIF}
end;
function LineIntersectionPoint(const line1, line2: LineSegment; out pt: Point2D) : Boolean;
var
// convert lines to the eqn
// c = ax + by
a1, b1, c1: Single;
a2, b2, c2: Single;
det: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineIntersectionPoint(const line1, line2: LineSegment', '');
{$ENDIF}
pt.x := 0;
pt.y := 0;
//Convert lines to eqn c = ax + by
a1 := line1.endPoint.y - line1.startPoint.y; //y12 - y11;
b1 := line1.startPoint.x - line1.endPoint.x; //x11 - x12;
c1 := a1 * line1.startPoint.x + b1 * line1.startPoint.y; //a1 * x11 + b1 * y11;
a2 := line2.endPoint.y - line2.startPoint.y; //y22 - y21;
b2 := line2.startPoint.x - line2.endPoint.x; //x21 - x22;
c2 := a2 * line2.startPoint.x + b2 * line2.startPoint.y; //a2 * x21 + b2 * y21;
det := (a1 * b2) - (a2 * b1);
if det = 0 then
result := false
else
begin
pt.x := (b2*c1 - b1*c2) / det;
pt.y := (a1*c2 - a2*c1) / det;
result := true;
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineIntersectionPoint(const line1, line2: LineSegment', '');
{$ENDIF}
end;
function LineSegmentsIntersect(const line1, line2: LineSegment): Boolean;
var
pt: Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineSegmentsIntersect(const line1, line2: LineSegment): Boolean', '');
{$ENDIF}
result := LineIntersectionPoint(line1, line2, pt) and PointOnLine(pt, line2) and PointOnLine(pt, line1);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineSegmentsIntersect(const line1, line2: LineSegment): Boolean', '');
{$ENDIF}
end;
function LineIntersectsRect(const line: LineSegment; const rect: Rectangle): Boolean;
var
lines: LinesArray;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineIntersectsRect(const line: LineSegment', '');
{$ENDIF}
lines := LinesFrom(rect);
result := LineIntersectsLines(line, lines);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineIntersectsRect(const line: LineSegment', '');
{$ENDIF}
end;
function PointInRect(const pt: Point2D; x, y, w, h: Single): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInRect(const pt: Point2D', '');
{$ENDIF}
if pt.x < x then result := false
else if pt.x > x + w then result := false
else if pt.y < y then result := false
else if pt.y > y + h then result := false
else result := true;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInRect(const pt: Point2D', '');
{$ENDIF}
end;
function PointInRect(const pt: Point2D; const rect: Rectangle): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInRect(const pt: Point2D', '');
{$ENDIF}
result := PointInRect(pt, rect.x, rect.y, rect.width, rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInRect(const pt: Point2D', '');
{$ENDIF}
end;
function PointInRect(ptX, ptY, x, y, w, h: Single): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInRect(ptX, ptY, x, y, w, h: Single): Boolean', '');
{$ENDIF}
if ptX < x then result := false
else if ptX > x + w then result := false
else if ptY < y then result := false
else if ptY > y + h then result := false
else result := true;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInRect(ptX, ptY, x, y, w, h: Single): Boolean', '');
{$ENDIF}
end;
function PointInRect(x, y: Single; const rect: Rectangle): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'PointInRect(x, y: Single', '');
{$ENDIF}
result := PointInRect(x, y, rect.x, rect.y, rect.width, rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'PointInRect(x, y: Single', '');
{$ENDIF}
end;
function VectorFromPointToRect(x, y, rectX, rectY, rectWidth, rectHeight: Single): Vector; overload;
var
px, py: Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorFromPointToRect(x, y, rectX, rectY: Single', '');
{$ENDIF}
if x < rectX then px := rectX
else if x > (rectX + rectWidth) then px := rectX + rectWidth
else px := x;
if y < rectY then py := rectY
else if y > (rectY + rectHeight) then py := rectY + rectHeight
else py := y;
result := VectorTo(px - x, py - y);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorFromPointToRect(x, y, rectX, rectY: Single', '');
{$ENDIF}
end;
function VectorFromPointToRect(x, y: Single; const rect: Rectangle): Vector; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorFromPointToRect(x, y: Single', '');
{$ENDIF}
result := VectorFromPointToRect(x, y, rect.x, rect.y, rect.width, rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorFromPointToRect(x, y: Single', '');
{$ENDIF}
end;
function VectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorFromPointToRect(const pt: Point2D', '');
{$ENDIF}
result := VectorFromPointToRect(pt.x, pt.y, rect.x, rect.y, rect.width, rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorFromPointToRect(const pt: Point2D', '');
{$ENDIF}
end;
function VectorOutOfRectFromPoint(const pt: Point2D; const rect: Rectangle; const velocity: Vector): Vector;
var
maxIdx: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOutOfRectFromPoint(const pt: Point2D', '');
{$ENDIF}
result := _VectorOverLinesFromPoint(pt, LinesFrom(rect), velocity, maxIdx);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOutOfRectFromPoint(const pt: Point2D', '');
{$ENDIF}
end;
function VectorOutOfCircleFromPoint(const pt: Point2D; const c: Circle; const velocity: Vector): Vector;
var
dx, dy, cx, cy: Single;
a, b, c1, det, t, mvOut: single;
ipt2: Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOutOfCircleFromPoint(const pt: Point2D', '');
{$ENDIF}
// If the point is not in the radius of the circle, return a zero vector
if PointPointDistance(pt, CenterPoint(c)) > c.radius then
begin
result := VectorTo(0, 0);
exit;
end;
// Calculate the determinant (and components) from the center circle and
// the point+velocity details
cx := c.center.x;
cy := c.center.y;
dx := velocity.x;
dy := velocity.y;
a := dx * dx + dy * dy;
b := 2 * (dx * (pt.x - cx) + dy * (pt.y - cy));
c1 := (pt.x - cx) * (pt.x - cx) + (pt.y - cy) * (pt.y - cy) - c.radius * c.radius;
det := b * b - 4 * a * c1;
// If the determinate is very small, return a zero vector
if (det <= 0) or (a = 0) then
result := VectorTo(0, 0)
else
begin
// Calculate the vector required to "push" the vector out of the circle
t := (-b - Sqrt(det)) / (2 * a);
ipt2.x := pt.x + t * dx;
ipt2.y := pt.y + t * dy;
mvOut := PointPointDistance(pt, ipt2) + 1.42; // sqrt 2
result := VectorMultiply(UnitVector(InvertVector(velocity)), mvOut);
end;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOutOfCircleFromPoint(const pt: Point2D', '');
{$ENDIF}
end;
function VectorOutOfCircleFromCircle(const src, bounds: Circle; const velocity: Vector): Vector;
var
c: Circle;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOutOfCircleFromCircle(const src, bounds: Circle', '');
{$ENDIF}
c := CircleAt(CenterPoint(bounds), bounds.radius + src.radius);
result := VectorOutOfCircleFromPoint(CenterPoint(Src), c, velocity);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOutOfCircleFromCircle(const src, bounds: Circle', '');
{$ENDIF}
end;
function VectorOutOfRectFromRect(const src, bounds: Rectangle; const velocity: Vector): Vector;
var
maxIDx: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOutOfRectFromRect(const src, bounds: Rectangle', '');
{$ENDIF}
result := VectorOverLinesFromLines(LinesFrom(src), LinesFrom(bounds), velocity, maxIdx);
//result := _VectorOverLinesFromPoints(PointsFrom(src), LinesFrom(bounds), velocity, maxIdx);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOutOfRectFromRect(const src, bounds: Rectangle', '');
{$ENDIF}
end;
function VectorInRect(const v: Vector; x, y, w, h: Single): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorInRect(const v: Vector', '');
{$ENDIF}
if v.x < x then result := false
else if v.x > x + w then result := false
else if v.y < y then result := false
else if v.y > y + h then result := false
else result := true;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorInRect(const v: Vector', '');
{$ENDIF}
end;
function VectorInRect(const v: Vector; const rect: Rectangle): Boolean; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorInRect(const v: Vector', '');
{$ENDIF}
result := VectorInRect(v, rect.x, rect.y, rect.width, rect.height);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorInRect(const v: Vector', '');
{$ENDIF}
end;
// function LineCircleHit(const c: Circle; const velocity: Vector; const lines: LinesArray; out found: LineSegment): Boolean;
// var
// hitIdx: Longint;
// begin
// {$IFDEF TRACE}
// TraceEnter('sgGeometry', 'LineCircleHit(const c: Circle', '');
// {$ENDIF}
// _VectorOverLinesFromCircle(c, lines, velocity, hitIdx);
// if hitIdx >= 0 then
// begin
// found := lines[hitIdx];
// result := True;
// end
// else result := False;
// {$IFDEF TRACE}
// TraceExit('sgGeometry', 'LineCircleHit(const c: Circle', '');
// {$ENDIF}
// end;
function DistantPointOnCircle(const pt: Point2D; const c: Circle): Point2D;
var
ptOnCircle: Point2D;
toCircle: Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'DistantPointOnCircle(const pt: Point2D', '');
{$ENDIF}
//Get the closest point
ptOnCircle := ClosestPointOnCircle(pt, c);
// Get other side... follow toCircle vector 2 * radius
toCircle := VectorFromPoints(pt, ptOnCircle);
result := AddVectors(ptOnCircle, VectorMultiply(UnitVector(toCircle), c.radius * 2));
{$IFDEF TRACE}
TraceExit('sgGeometry', 'DistantPointOnCircle(const pt: Point2D', '');
{$ENDIF}
end;
function DistantPointOnCircleHeading(const pt: Point2D; const c: Circle; const heading: Vector; out oppositePt: Point2D): Boolean;
var
dist, dotProd: Single;
ptOnCircle, chkPt: Point2D;
toCenter: Vector;
head: Vector;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'DistantPointOnCircleHeading(const pt: Point2D', '');
{$ENDIF}
result := False;
head := UnitVector(heading);
//Move pt back 2 * radius to ensure it is outside of the circle...
// but still on same alignment
chkPt := AddVectors(pt, VectorMultiply(InvertVector(head), 2 * c.radius));
//DrawCircle(ColorBlue, chkPt, 1);
dist := RayCircleIntersectDistance(chkPt, head, c);
if dist < 0 then exit;
// Get point on circle by moving from chkPt dist distance in heading direction
ptOnCircle := AddVectors(chkPt, VectorMultiply(head, dist));
//DrawLine(ColorMagenta, chkPt, ptOnCircle);
//DrawCircle(ColorMagenta, ptOnCircle, 2);
//Project the ray to the other side of the circle
toCenter := VectorFromPoints(ptOnCircle, c.center);
dotProd := DotProduct(toCenter, head);
//WriteLn(dotProd:4:2);
result := True;
oppositePt := AddVectors(ptOnCircle, VectorMultiply(head, 2 * dotProd));
//FillCircle(ColorRed, oppositePt, 2);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'DistantPointOnCircleHeading(const pt: Point2D', '');
{$ENDIF}
end;
function VectorOutOfRectFromCircle(const c: Circle; const rect: Rectangle; const velocity: Vector): Vector;
var
maxIdx: Longint;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'VectorOutOfRectFromCircle(const c: Circle', '');
{$ENDIF}
result := VectorOverLinesFromCircle(c, LinesFrom(rect), velocity, maxIdx);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'VectorOutOfRectFromCircle(const c: Circle', '');
{$ENDIF}
end;
// function VectorOverLinesFromCircle(const c: Circle; const lines: LinesArray; const velocity: Vector; out maxIdx: Longint): Vector;
// begin
// {$IFDEF TRACE}
// TraceEnter('sgGeometry', 'VectorOverLinesFromCircle(const c: Circle', '');
// {$ENDIF}
// result := _VectorOverLinesFromCircle(c, lines, velocity, maxIDx);
// {$IFDEF TRACE}
// TraceExit('sgGeometry', 'VectorOverLinesFromCircle(const c: Circle', '');
// {$ENDIF}
// end;
// function VectorInLinesFromCircle(const c: Circle; lines: LinesArray; velocity: Vector; out maxIdx: Longint): Vector;
// begin
// result := _VectorOverLinesFromCircle(c, lines, velocity, False, maxIDx);
// end;
//---------------------------------------------------------------------------
// Points functions and procedures
//---------------------------------------------------------------------------
function CenterPoint(const c: Circle): Point2D; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CenterPoint(const c: Circle): Point2D', '');
{$ENDIF}
result := c.center;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CenterPoint(const c: Circle): Point2D', '');
{$ENDIF}
end;
function CircleAt(const pt: Point2D; radius: Single): Circle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CircleAt(const pt: Point2D', '');
{$ENDIF}
result.center := pt;
result.radius := Abs(radius);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CircleAt(const pt: Point2D', '');
{$ENDIF}
end;
function CircleAt(x, y: Single; radius: Single): Circle; overload;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CircleAt(x, y: Single', '');
{$ENDIF}
result.center := PointAt(x, y);
result.radius := Abs(radius);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CircleAt(x, y: Single', '');
{$ENDIF}
end;
function CreateCircle(const pt: Point2D; radius: Single): Circle; overload;
begin
result := CircleAt(pt,radius);
end;
function CreateCircle(x, y: Single; radius: Single): Circle; overload;
begin
result := CircleAt(x,y,radius);
end;
function CircleX(const c: Circle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CircleX(const c: Circle): Single', '');
{$ENDIF}
result := c.center.x;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CircleX(const c: Circle): Single', '');
{$ENDIF}
end;
function CircleY(const c: Circle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CircleY(const c: Circle): Single', '');
{$ENDIF}
result := c.center.y;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CircleY(const c: Circle): Single', '');
{$ENDIF}
end;
function CircleRadius(const c: Circle): Single;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'CircleRadius(const c: Circle): Single', '');
{$ENDIF}
result := c.radius;
{$IFDEF TRACE}
TraceExit('sgGeometry', 'CircleRadius(const c: Circle): Single', '');
{$ENDIF}
end;
function LineIntersectsCircle(const l: LineSegment; const c: Circle): Boolean;
var
pt: Point2D;
begin
{$IFDEF TRACE}
TraceEnter('sgGeometry', 'LineIntersectsCircle(const l: LineSegment', '');
{$ENDIF}
pt := ClosestPointOnLineFromCircle(c, l);
result := PointInCircle(pt, c);
{$IFDEF TRACE}
TraceExit('sgGeometry', 'LineIntersectsCircle(const l: LineSegment', '');
{$ENDIF}
end;
procedure FixRectangle(var rect: Rectangle);
begin
FixRectangle(rect.x, rect.y, rect.width, rect.height);
end;
procedure FixRectangle(var x, y, width, height: Single);
begin
if width < 0 then
begin
x := x + width;
width := -width;
end;
if height < 0 then
begin
y := y + height;
height := -height;
end;
end;
function PointAdd(const pt1, pt2: Point2D): Point2D;
begin
result.X := pt1.X + pt2.X;
result.Y := pt1.Y + pt2.Y;
end;
function QuadFrom(xTopLeft, yTopLeft, xTopRight, yTopRight, xBottomLeft, yBottomLeft, xBottomRight, yBottomRight: Single ): Quad;
begin
result.points[0].x := xTopLeft;
result.points[0].y := yTopLeft;
result.points[1].x := xTopRight;
result.points[1].y := yTopRight;
result.points[2].x := xBottomLeft;
result.points[2].y := yBottomLeft;
result.points[3].x := xBottomRight;
result.points[3].y := yBottomRight;
end;
/// Returns a quad for the passed in points.
///
/// @lib
/// @sn quadFromRect:%s
function QuadFrom(const rect: Rectangle ): Quad;
begin
result := QuadFrom(
RectangleLeft(rect), RectangleTop(rect),
RectangleRight(rect), RectangleTop(rect),
RectangleLeft(rect), RectangleBottom(rect),
RectangleRight(rect), RectangleBottom(rect) )
end;
/// Use a matrix to transform all of the points in a quad.
///
/// @lib
/// @sn matrix:%s applyToQuad:%s
///
/// @class Matrix2D
/// @method ApplyTo
/// @updatesArrayParam 2
/// @csn applyToQuad:%s
procedure ApplyMatrix(const m: Matrix2D; var quad: Quad);
var
i: Integer;
begin
for i := 0 to 3 do
begin
quad.points[i] := MatrixMultiply(m, quad.points[i]);
end;
end;
/// Change the location of a point on a Quad.
///
/// @lib
/// @sn quad:%s setPoint:%s to:%s
procedure SetQuadPoint(var q: Quad; idx: Longint; value: Point2d);
begin
if (idx < 0) or (idx > 3) then exit;
q.points[idx] := value;
end;
end.
|
unit ufTarefa2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.Samples.Spin, Vcl.Samples.Gauges;
type
TThreadExecutar = Class
public
class var FspMiliSegundos: Integer;
class var FpbThread: TProgressBar;
class procedure Executar;
end;
TEdit = Class(Vcl.StdCtrls.TEdit)
private
function GetValor: Integer;
public
procedure DoEnter; override;
procedure DoExit; override;
procedure AfterConstruction; override;
procedure KeyPress(var Key: Char); override;
published
property Valor : Integer read GetValor;
end;
TfTarefa2 = class(TForm)
btnThread: TButton;
grbThread1: TGroupBox;
edtThread1: TEdit;
pgbThread1: TProgressBar;
grbThread2: TGroupBox;
edtThread2: TEdit;
pgbThread2: TProgressBar;
btnFechar: TButton;
procedure btnThreadClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnFecharClick(Sender: TObject);
private
public
procedure ExecutarThread1;
procedure ExecutarThread2;
end;
implementation
uses
ufPrincipal, Controller.Factory;
{$R *.dfm}
function TextoParaNumero(Valor: String): Integer;
var
nIndex: Integer;
sAux : String;
begin
sAux := '0';
for nIndex := 1 to Length(Valor) do
if CharInSet(Valor[nIndex], ['0'..'9']) then
sAux := sAux + Valor[nIndex];
Result := StrToInt(sAux);
end;
class procedure TThreadExecutar.Executar;
begin
TControllerFactory.Novo.ThreadController.ExecutarLaco(FspMiliSegundos, FpbThread);
end;
procedure TfTarefa2.btnThreadClick(Sender: TObject);
begin
ExecutarThread1;
ExecutarThread2;
end;
procedure TfTarefa2.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TfTarefa2.ExecutarThread1;
begin
TThreadExecutar.FspMiliSegundos := edtThread1.Valor;
TThreadExecutar.FpbThread := pgbThread1;
TThreadExecutar.Executar;
end;
procedure TfTarefa2.ExecutarThread2;
begin
TThreadExecutar.FspMiliSegundos := edtThread2.Valor;
TThreadExecutar.FpbThread := pgbThread2;
TThreadExecutar.Executar;
end;
procedure TfTarefa2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TfPrincipal(Owner).VariableClear(Self);
Action := caFree;
end;
{ TEdit }
procedure TEdit.AfterConstruction;
begin
inherited;
Alignment := taRightJustify;
end;
procedure TEdit.DoEnter;
begin
inherited;
Text := IntToStr(Valor);
end;
procedure TEdit.DoExit;
begin
inherited;
if Valor <= 0 then
begin
ShowMessage('Valor deve ser maior que 1');
Text := '1';
end;
Text := FormatFloat(',0', Valor);
end;
function TEdit.GetValor: Integer;
begin
Result := TextoParaNumero(Text);
end;
procedure TEdit.KeyPress(var Key: Char);
begin
inherited;
if not (CharInSet(Key, ['0'..'9', #8, #9, #13])) then
Key := #0;
end;
end.
|
{
Lua4Lazarus
sample:TLuaMyUtilsObject
License: New BSD
Copyright(c)2010- Malcome@Japan All rights reserved.
}
unit l4l_myutils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs, lua54, l4l_object;
type
{ TLuaMyUtilsObject }
TLuaMyUtilsObject = class(TLuaObject)
private
function GetNow: string;
protected
public
constructor Create(L : Plua_State); override;
destructor Destroy; override;
published
function l4l_Sleep: integer;
function l4l_ShowMessage: integer;
function l4l_Utf8ToWide: integer;
function l4l_WideToUtf8: integer;
function l4l_Utf8ToAnsi: integer;
function l4l_AnsiToUtf8: integer;
property l4l_Now: string read GetNow;
end;
function CreateMyUtilsObject(L : Plua_State) : Integer; cdecl;
implementation
{ TLuaMyUtilsObject }
constructor TLuaMyUtilsObject.Create(L: Plua_State);
begin
inherited Create(L);
end;
destructor TLuaMyUtilsObject.Destroy;
begin
inherited Destroy;
end;
function TLuaMyUtilsObject.l4l_Sleep: integer;
begin
SysUtils.sleep(lua_tointeger(LS, 1));
Result := 0;
end;
function TLuaMyUtilsObject.l4l_ShowMessage: integer;
begin
Dialogs.ShowMessage(lua_tostring(LS, 1));
Result := 0;
end;
function TLuaMyUtilsObject.l4l_Utf8ToWide: integer;
var
ws: WideString;
begin
ws := UTF8Decode(lua_tostring(LS, 1));
lua_pushlstring(LS, PChar(ws), Length(ws) shl 1);
Result := 1;
end;
function TLuaMyUtilsObject.l4l_WideToUtf8: integer;
var
l: integer;
ws: WideString;
p: PChar;
begin
p := lua_tolstring(LS, 1, @l);
SetLength(ws, l shr 1);
Strlcopy(PChar(ws), p, l);
lua_pushstring(LS, PChar(UTF8Encode(ws)));
Result := 1;
end;
function TLuaMyUtilsObject.l4l_Utf8ToAnsi: integer;
begin
lua_pushstring(LS, PChar(System.Utf8ToAnsi(lua_tostring(LS, 1))));
Result := 1;
end;
function TLuaMyUtilsObject.l4l_AnsiToUtf8: integer;
begin
lua_pushstring(LS, PChar(System.AnsiToUtf8(lua_tostring(LS, 1))));
Result := 1;
end;
function TLuaMyUtilsObject.GetNow: string;
begin
Result:= DatetimeToStr(SysUtils.Now, DefaultFormatSettings);
end;
function CreateMyUtilsObject(L : Plua_State) : Integer; cdecl;
begin
l4l_PushLuaObject(TLuaMyUtilsObject.Create(L));
Result := 1;
end;
end.
|
unit UnitConsts;
interface
Uses Messages;
resourcestring
IDS_InfoFilesPath = '.\Info\';
IDS_ScriptFilesPath = '.\Scripts\';
IDS_UsersPath = '.\Users\';
IDS_StoreFilename = 'Store.ini';
IDS_DefaultMapFileName = 'Map.ini';
RS_UpDateTime = '2019.06.03';
IDS_MainHotKeyInfo = 'MainHotKeyInfo';
IDS_WinInfoHotKeyInfo = 'WinInfoHotKeyInfo';
IDS_VirtualKey = 'VirtualKey';
IDS_Modifiers = 'Modifiers';
IDS_ShowText = 'ShowText';
IDS_FormTopStr = 'Top';
IDS_FormLeftStr = 'Left';
IDS_MainFormName = 'Main';
IDS_ImageFormName = 'Image';
IDS_GeneralSetFormName = 'Settings';
IDS_StuffsFormName = 'Inventory';
IDS_PetsFormName = 'Pets';
IDS_UniverseStoveFormName = 'Wuxing Oven';
IDS_WorkTransactionsFormName = 'Script';
IDS_WGsFormName = 'Create Kungfu';
IDS_WGAttrFormName = 'Basic Settings';
IDS_WG_Name = 'Name';
IDS_WG_NameDef = 'DivinePalm';
IDS_WG_XiShu = 'Destructive Index';
IDS_WG_NeiLi = 'Mana Consumed';
IDS_WG_ZiShi = 'Starting Posture';
IDS_WG_GuiJi = 'Flying Track';
IDS_WG_BaoZha = 'Explosion Type';
const
// AddrHumanBase = $006C21FC;
// AddrBattleState = $006C51DC;
CustomMouseMsg = WM_USER + 1;
CustomIID = 100;
// 定义的动作代码,用在Work.ini里面
ActUnknown = -1; // 未知指令---------------------------------------
ActLeftClick = 0; // 左键单击
ActRightClick = 1; // 右键单击
ActMoveToPos = 10; // 移动位置:移动到地图内的某个坐标
ActGoToMap = 20; // 来到地图:移动到指定地图
ActInBattle = 30; // 正在战斗
ActBuyStuff = 40; // 购买物品
ActDoForge = 50; // 进行锻造
ActQuitShop = 60; // 离开商店
ActPressButton = 70; // 点击按钮
ActCallNPC = 80; // 呼叫 NPC
ActTerminate = 90; // 停止工作
ActHaveStuff = 100; // 拥有物品:等待满足此物品,达到指定数量级
ActStuffNum = 110; // 物品数目:等待满足此物品,等于指定数量级
ActJumpToTransN = 120; // 跳至步骤 N
ActHavePet = 130; // 拥有宠物:等待满足此宠物,达到指定数量级
ActPetNum = 140; // 宠物数目:等待满足此宠物,等于指定数量级
ActCancelNPCDialog = 150; // 取消对话
ActWinLeftClick = 160; // 窗口单击
ActWinLeftDblClick = 170; // 窗口双击
ActDelay = 180; // 等待延时
ActActiveBattle = 190; // 进入战斗
ActSetCapture = 200; // 捉宠设置
ActLocateWindow = 210; // 定位窗口
ActWinRightClick = 220; // 窗口右键
ActWaitWindow = 230; // 等待窗口
ActCreateWG = 240; // 自创武功
ActUseItem = 250; // 使用物品
ActOpenItemWindow = 260; // 开物品栏
ActCloseItemWindow = 270; // 关物品栏
ActSetWGAttr = 280; // 武功参数
ActSetWGDisp = 290; // 武功外观
ActDeleteWGs = 300; // 删除武功
ActSetHeal = 310; // Set heal settings
ActDropItem = 320; // Drop an item
ActSetAttr = 330; // Set user Attributes
// UserIDAddr = $006c2200; // Old HL_Base_Address
HL_EXE_Name = 'HL_Client.exe';
//UserNameAddress = $006c2244; CN
//UserNickAddress = $006c2254;
//UserSpouseAddress = $006c2264;
UserNameAddress = $006BB974;
UserNickAddress = $006BB984;
UserSpouseAddress = $006BB994;
UserNameSize = 16;
UserIdAddress = $006BB930;
//UserMoneyAddress = $6c2214;
UserMoneyAddress = $6BB944;
// Level, cultivation(?)
//UserLevelAddr = $006c2206; // WORD CN
//UserBaseXiuAddr = $006C3478; // DWORD
UserLevelAddr = $6BB936; // WORD
UserBaseXiuAddr = $6BCBA8; // DWORD
// User rank: master=5
// UserRankAddr = $006c2208; // WORD CN
UserRankAddr = $6BB938; // WORD
// 人物仙魔地址:仙=1,魔=2, 凡人/散仙=0
//UserXianmo_1Xian_2Mo = $006C346C; // WORD CN
UserXianmo_1Xian_2Mo = $6BCB9C; // WORD
UserAttrXian = 1; // 仙
UserAttrMo = 2; // 魔
// 人物五转职业:
//User5TurnCareer = $006C3470; // WORD
User5TurnCareer = $6BCBA0; // WORD
// Life current/max
//UserLifeCurrAddr = $006c220A; // WORD CN
//UserLifeMAXAddr = $006c220c; //WORD
UserLifeCurrAddr = $6BB93A; // WORD
UserLifeMAXAddr = $6BB93C; //WORD
// Mana current/max
//UserNeiliCurrAddr = $006c220e; // WORD CN
//UserNeiliMAXAddr = $006c2210; // WORD
UserNeiliCurrAddr = $6BB93E; // WORD
UserNeiliMAXAddr = $6BB940; // WORD
// 5 attributes
//UserAttribTiliAddr = $006c2230; // WORD CN
//UserAttribNeigongAddr = $006c2238; // WORD
//UserAttribGongjiAddr = $006c2234; // WORD
//UserAttribFangyuAddr = $006c2232; // WORD
//UserAttribQinggongAddr = $006c2236; // WORD
UserAttribTiliAddr = $6BB960; // WORD hp
UserAttribNeigongAddr = $6BB968; // WORD mp
UserAttribGongjiAddr = $6BB964; // WORD atk
UserAttribFangyuAddr = $6BB962; // WORD def
UserAttribQinggongAddr = $6BB966; // WORD dex
UserAttribRemainingAddr = $6BCCF4; // WORD unused attributes
// User coordinates on map
//UserPosXAdress = $006c22a8; CN
//UserPosYAdress = $006c22ac;
UserPosXAdress = $006BB9D8;
UserPosYAdress = $006BB9DC;
UserRealXAddress = $006BB9E8;
UserRealYAddress = $006BB9EC;
// 用户所在的地图的ID、名称的地址
//UserCurMapAddress = $006c4630; // DWORD
//UserCurMapNameAddress = $006c45A0; // 16 Bytes
UserCurMapAddress = $006BDD60; // DWORD
UserCurMapNameAddress = $006BDCD0; // 16 Bytes
// 用户所处环境状态地址;状态:3f1-战斗,3f2-平时,3f3-与NPC对话
UserEnvironmentAdress = $0066C0B8; // WORD
UserEnvSwitchMap = $3f0;
UserEnvBattle = $3f1;
UserEnvNormal = $3f2;
UserEnvDialog = $3f3;
UserEnvSomeAboutDealingPostClickMessage = $3f4;
// 用户身上武器、衣服、鞋子、身饰、头饰的偏移
//UserWuqiOnBodyAddress = $006c39a4;
//UserHujiaOnBodyAddress = $006c39a8;
//UserXieziOnBodyAddress = $006c39ac;
//UserShenshiOnBodyAddress = $006c39b0;
//UserToushiOnBodyAddress = $006c39b4;
UserWuqiOnBodyAddress = $6BD0D4;
UserHujiaOnBodyAddress = $6BD0D8;
UserXieziOnBodyAddress = $6BD0DC;
UserShenshiOnBodyAddress = $6BD0E0;
UserToushiOnBodyAddress = $6BD0E4;
// 与对话指针的指针
//NPCDialogAddressAddress = $6c6f60;
NPCDialogAddressAddress = $6C06C0;
// 对话数据的长度
NPCDialogLength = $200;
// $006c39a0($006c39c0) 是一个指针的指针的base地址
// 用户物品栏里面物品数目的地址
//UserItemCountAddress = $006c39ec;
UserItemCountAddress = $6BD11C;
// 用户物品指针的指针
//UserFirstItemAddressAddress = $006c39c4;
UserFirstItemAddressAddress = $006BD0F4;
// 宠物指针的指针
//UserFirstPetAddressAddress = $006C3A0C;
UserFirstPetAddressAddress = $6BD13C;
// 宠物数据的大小
UserPetSize = $B4;
// 宠物数目的地址
//UserPetCountAddress = $006c3a34;
UserPetCountAddress = $6BD164;
// 物品信息数据大小
UserItemInfoSize=$60;
// 以下是物品类型
ItemJian = 0; // 剑
ItemDao = 1; // 刀
ItemChui = 2; // 锤
ItemTui = 3; // 腿
ItemHuan = 4; // 环
ItemShan = 5; // 扇
ItemZhang = 6; // 杖
ItemCha = 7; // 叉
ItemGou = 8; // 钩
ItemHujia = 100; // 护甲
ItemXiezi = 200; // 鞋子
ItemShenshi = 300; // 身饰
ItemToushi = 400; // 头饰
ItemAnqi = 500; // 暗器
ItemDuyao = 600; // 毒药
ItemLiaoshangyao = 700; // 疗伤药,注:内药和血药
ItemUnknown = 800; // 不知道是什么,估计是任务用品
// 老虎机 投币 位置
TigerMachinePutCoinX = '263';
TigerMachinePutCoinY = '84';
// 老虎机 "3" 位置
TigerMachineCheckX = '426';
TigerMachineCheckY = '151';
// 游戏主窗口
PlayLeftJust = 29;
PlayRightJust = -31;
PlayTopJust = 58;
PlayBottomJust = -132;
// 主面板窗口
PnlMainTitle = 'pnlMain';
// 物品/装备窗口
ItemWindowTitle = 'Item/Equipment';
// “装备” 按钮
ItemButtonX = 630;
ItemButtonY = 450;
// 以下是物品栏内15个位置
Item1X = 395;
Item1Y = 75;
Item2X = 440;
Item2Y = 75;
Item3X = 485;
Item3Y = 75;
Item4X = 535;
Item4Y = 75;
Item5X = 395;
Item5Y = 120;
Item6X = 440;
Item6Y = 120;
Item7X = 485;
Item7Y = 120;
Item8X = 530;
Item8Y = 120;
Item9X = 395;
Item9Y = 170;
Item10X = 440;
Item10Y = 170;
Item11X = 490;
Item11Y = 170;
Item12X = 530;
Item12Y = 170;
Item13X = 395;
Item13Y = 215;
Item14X = 440;
Item14Y = 215;
Item15X = 485;
Item15Y = 210;
// 用户招的数目地址
//UserWGCountAddress = $006c3a7c;
UserWGCountAddress = $6BD1AC;
// 用户招式指针的指针
//UserFirstWGAddressAddress = $006c3a54;
UserFirstWGAddressAddress = $6BD184;
// 招式数据
// 名称[16];创招人[16];[4];武功ID[4];起手[4];轨迹[4];爆炸[4];等级[4];内力[4];显示系数*100[4];[12];实际系数与显示系数的比值[4];[16];[8];经验[4];...
// 招式数据长度
UserWGDataLength = $6c;
// 创招 招式名称
CreateWG_MC_LeftJust = 112;
CreateWG_MC_RightJust = -50;
CreateWG_MC_TopJust = 54;
CreateWG_MC_BottomJust = -343;
// 创招 杀伤系数
CreateWG_XS_LeftJust = 112;
CreateWG_XS_RightJust = -50;
CreateWG_XS_TopJust = 78;
CreateWG_XS_BottomJust = -319;
// 创招 使用内力
CreateWG_NL_LeftJust = 112;
CreateWG_NL_RightJust = -50;
CreateWG_NL_TopJust = 102;
CreateWG_NL_BottomJust = -295;
// 创招 起手姿势
CreateWG_QS_LeftJust = 112;
CreateWG_QS_RightJust = -50;
CreateWG_QS_TopJust = 239;
CreateWG_QS_BottomJust = -158;
// 创招 飞行轨迹
CreateWG_GJ_LeftJust = 112;
CreateWG_GJ_RightJust = -50;
CreateWG_GJ_TopJust = 265;
CreateWG_GJ_BottomJust = -132;
// 创招 爆炸方式
CreateWG_BZ_LeftJust = 112;
CreateWG_BZ_RightJust = -50;
CreateWG_BZ_TopJust = 291;
CreateWG_BZ_BottomJust = -106;
// 炼化菜单
IDM_UniverseStove = 20;
// 创招菜单ID
IDM_CreateWG = 22;
// 人物属性菜单ID
IDM_HumanAttr = 73;
// 战斗菜单ID
IDM_Battle = 88;
// 物品菜单ID
IDM_Item = 74;
// 战斗状态的地址
// BattleStateAddr = $006c51dc;
BattleStateAddr = $6BE90C;
// 战斗指令的地址
// BattleOrderAddr = $006c6018;
BattleOrderAddr = $6BF748;
// 战斗指令数据的大小
BattleOrderSize = $1c;
// 战斗指令状态[4], 人物动作[4],人物动作对象[4],[4],宠物动作[4],宠物动作对象[4],[4]
//Combat command status [4], character action [4], character action object [4], [4], pet action [4], pet action object [4], [4]
// Autofight 0-no 1-yes
// BattleIsAutoFightAddr = $006c6260;
BattleIsAutoFightAddr = $6BF990;
// 是否快速战斗 0-不是,1-是
// BattleIsFastFightAddr = $006c6478;
BattleIsFastFightAddr = $6BFBA8;
// 战斗时生物的数据大小
CreatureInfoSize = $70;
// 战斗怪物数(不大于5)地址
// 6c627c
// 战斗死掉的怪物数地址
// DeadMonsterCountAddr = $6c626c;
DeadMonsterCountAddr = $6BF99C;
// 战斗时生物的数目(包括自己和宠)的地址
// BattleCreatureCountAddress = $006c5144;
BattleCreatureCountAddress = $6BE874;
// 战斗时生物指针的指针
// BattleFirstCreatureAddressAddress = $006c511c;
BattleFirstCreatureAddressAddress = $6BE84C;
// 战斗时的动作
BattleAttack = 0;
BattleMagic = 1; // 这个时候,BattleBufferRemain1就是要练的拳
BattleDefence = 2;
BattleCapture = 6;
BattleEscape = 5;
BattleIdle = 3;
BattleEat = 9; // 这个时候,BattleBufferRemain1就是要吃的药的ID
DelWGRemainEasyWG = -1;
DelWGNoIndicator = -2;
// 用户炼化经验地址
//UserLianhuaExpAddr = $006c2220;
UserLianhuaExpAddr = $6BB950;
// Oven item type
StoveRoomVide = $4D2;
StoveRoomPet = $4D4;
StoveRoomItem = $4D6;
//DialogControlAddr = $6c6d40;
DialogControlAddr = $6c04a0; // 控制是否是对话框状态的地址
//6c6f60 > 6C06C0
// 从Exported Entry可得到
// 幻灵FormMain
// HL_FormMainAddrAddrAddr = $006ab338;
// 幻灵UniverseStoveForm
//HL_UniverseStoveFormAddressAddress = $006abb08;
HL_UniverseStoveFormAddressAddress = $006A8568;
HL_HeroStatsFormAddressAddress = $006a4ec8;
AttrOffset_Rem = $4bc;
AttrOffset_Life = $4d4;
AttrOffset_Mana = $4d8;
AttrOffset_Attack = $4dc;
AttrOffset_Defense = $4e0;
AttrOffset_Dexterity = $4e4;
implementation
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooINIConfig;
interface
uses
INIFiles,
ooINI.DataInput, ooINI.DataOutput,
ooConfig.Intf;
type
TINIConfig = class sealed(TInterfacedObject, IConfig)
strict private
_IniFile: TIniFile;
public
function LoadSection(const ConfigSection: IConfigSection): Boolean;
function SaveSection(const ConfigSection: IConfigSection): Boolean;
constructor Create(const FileName: String);
destructor Destroy; override;
class function New(const FileName: String): IConfig;
end;
implementation
function TINIConfig.LoadSection(const ConfigSection: IConfigSection): Boolean;
begin
ConfigSection.Unmarshal(TINIDataInput.New(_IniFile, ConfigSection.Name));
Result := True;
end;
function TINIConfig.SaveSection(const ConfigSection: IConfigSection): Boolean;
begin
ConfigSection.Marshal(TINIDataOutput.New(_IniFile, ConfigSection.Name));
Result := True;
end;
constructor TINIConfig.Create(const FileName: String);
begin
_IniFile := TIniFile.Create(FileName);
end;
destructor TINIConfig.Destroy;
begin
_IniFile.Destroy;
inherited;
end;
class function TINIConfig.New(const FileName: String): IConfig;
begin
Result := TINIConfig.Create(FileName);
end;
end.
|
unit libautocomplete;
interface
procedure autocomplete( var commandline: string; var cursorindex: integer );
implementation
uses classes, libosutils, libenv, crt, sysutils, process, strutils, libutils;
function parse_args_raw_mode ( commandline: string ): tstrarray; forward;
function argument_is_quoted ( argument : string ): byte; forward;
function argument_trim_quotes ( argument : string ): string; forward;
function autocomplete_get_starting_sequence( t: tstrarray; user_input: string ) : tstrarray; forward;
// basically we call the "auto.php" "$argumentIndex" "$firstArgText" "$subString"
function call_autocomplete (
argumentIndex: integer;
firstArgumentText: string;
subString: string ): tstrarray; forward;
procedure show_completion_list( list: tstrarray; leftArg: string ); forward;
function str_join( src: tstrarray ): string;
var out: string = '';
i: integer;
begin
for i := 0 to length( src ) - 1 do begin
out := concat( out, src[i] );
end;
str_join := out;
end;
function str_needs_escaping( s: string ): boolean;
begin
if pos( ' ', s ) > 0 then exit( true ) else exit( false );
end;
function is_pipe_argument( s: string ): boolean;
begin
if trim( s ) = '|' then exit( true )
else exit( false );
end;
procedure autocomplete( var commandline: string; var cursorindex: integer );
var args : tstrarray; // array of string (dynamic array, 0-based index)
i : integer = 0; // counter variable
processed_chars : integer = 0; // processed characters
detected_arg_index : integer = -1; // on which argument of the command line the cursor is positioned?
relative_cursor_pos: integer = 0; // relative cursor position to detected argument index
ignore_first_chars : string = ''; // ignore first space characters from current argument
current_arg_text : string = ''; // current argument string contents
moved_cursor_once : boolean = false; // weather the autocomplete engine moved the cursor to the first char of detected argument
arg_is_quoted : byte = 0; // weather the argument is escaped byte, enum (0, 1)
arg_unquoted_form : string = ''; // the argument with trimmed quotes
arg_left_text : string = ''; // the left part before the cursor of the argument that will be evaluated for autocompletion
first_script_arg : string = ''; // we need the first script argument of the command
completionList : tstrarray;
cursor_increment : integer = 0;
new_argument : string = '';
relative_arg_index : integer = 0;
last_pipe_position : integer = -1;
begin
if ( length( commandline ) = 0 ) then
exit;
args := parse_args_raw_mode( commandline );
for i := 0 to length( args ) - 1 do
begin
if ( processed_chars + length( args[i] ) ) >= cursorindex then
begin
detected_arg_index := i;
break; // exit loop
end;
processed_chars += length( args[i] );
if is_pipe_argument( args[i] ) then begin
relative_arg_index := -1;
last_pipe_position := i;
end else
begin
inc(relative_arg_index);
end;
end;
if relative_arg_index < 0 then relative_arg_index := 0;
// detected argument index is 0-based
if detected_arg_index = -1 then
detected_arg_index := length( args ) - 1;
// relative cursor position to current "raw" argument is 0-based
relative_cursor_pos := cursorindex - processed_chars;
// current argument text contents
current_arg_text := args[ detected_arg_index ];
// jump to first non white space in current argument.
while ( ( current_arg_text <> '' ) and ( current_arg_text[1] = ' ' ) ) do
begin
ignore_first_chars := concat( ignore_first_chars, ' ' );
relative_cursor_pos := relative_cursor_pos - 1;
delete( current_arg_text, 1, 1 );
//jump cursor to first character letter if needed
if relative_cursor_pos < 0 then
begin
relative_cursor_pos += 1;
cursorindex += 1;
moved_cursor_once := true;
end;
end;
// if we jump to the first argument character, we don't do auto complete
// this time, but wait for the user to press the tab key another time
if moved_cursor_once then exit;
arg_is_quoted := argument_is_quoted( current_arg_text );
arg_unquoted_form := argument_trim_quotes( current_arg_text );
if ( arg_is_quoted = 1 ) and ( relative_cursor_pos > 0 ) then
relative_cursor_pos -= 1;
if ( arg_is_quoted = 1 ) and ( relative_cursor_pos = length( current_arg_text ) ) then
relative_cursor_pos -= 1;
arg_left_text := copy( arg_unquoted_form, 1, relative_cursor_pos );
if ( arg_left_text <> '' ) and ( ( arg_left_text[1] = '"' ) or ( arg_left_text[1] = '''' ) ) then
arg_left_text := copy( arg_left_text, 2, length( arg_left_text ) - 1 );
//writeln( arg_left_text );
first_script_arg := argument_trim_quotes( trim( args[last_pipe_position + 1] ) );
completionList := autocomplete_get_starting_sequence(
call_autocomplete( relative_arg_index, first_script_arg, arg_left_text ),
arg_left_text
);
if length( completionList ) > 1 then begin
show_completion_list( completionList, arg_left_text );
exit;
end;
if length( completionList ) = 0 then exit;
// repack argument
cursor_increment := length( completionList[0] ) - length( arg_left_text );
//writeln( cursor_increment );
new_argument := arg_left_text + copy( completionList[0], length( arg_left_text ) + 1, cursor_increment );
if str_needs_escaping( new_argument ) = false then begin
args[ detected_arg_index ] := ignore_first_chars + new_argument;
end else
begin
args[ detected_arg_index ] := ignore_first_chars + escapeshellarg( new_argument );
end;
commandLine := str_join( args );
if detected_arg_index = length( args ) - 1 then
cursorindex := length( commandLine )
else begin
cursorindex := 0;
for i := 0 to detected_arg_index do
cursorindex += length( args[i] );
end;
end;
function argument_is_quoted( argument: string ): byte;
begin
if ( ( length( argument ) > 2 ) and
( argument[1] = argument[ length(argument) ] ) and
( ( argument[1] = '"' ) or ( argument[1] = '''' ) )
) then exit(1)
else exit(0);
end;
function argument_trim_quotes( argument: string ): string;
begin
if ( argument_is_quoted( argument ) = 1 ) then
argument_trim_quotes := copy( argument, 2, length( argument ) - 2 )
else
argument_trim_quotes := argument;
end;
function str_read( var s: string ): char;
begin
if length( s ) = 0 then
exit( #0 )
else begin
str_read := s[1];
delete( s, 1, 1 );
end;
end;
function str_get( var s: string ): char;
begin
if length( s ) = 0 then
exit( #0 )
else
exit( s[1] );
end;
procedure array_push( var items: tstrarray; value: string );
begin
setlength( items, length( items ) + 1 );
items[ length( items ) - 1 ] := value;
end;
function parse_args_raw_mode( commandline: string ): tstrarray;
var items : tstrarray;
cmd : string;
seqend : integer;
chr : char;
chr1 : char;
arg : string;
begin
seqend := 0;
cmd := commandline;
arg := '';
setlength( items, 0 );
if cmd = '' then
exit(items);
while true do
begin
// initialize sequence end type
seqend := 0;
repeat
chr := str_read( cmd );
case chr of
#0: begin
// string consumed. return
if arg <> '' then
array_push( items, arg );
exit( items ); //exit function
end;
' ': begin
arg := concat( arg, chr );
// good, continue next
end;
else begin
arg := concat( arg, chr );
break; // break current repeat loop
end;
end;
until ( false );
case chr of
'"': begin
seqend := 1; // seqend 1 eq "
end;
'''': begin
seqend := 2; // seqend 2 eq '
end
else begin
seqend := 0; // seqend 0 eq non-space char
end;
end; //case
repeat
chr := str_read( cmd );
case chr of
#0: begin
if arg <> '' then
array_push( items, arg );
exit( items ); // exit function
end;
' ': begin
// encountered space.
// if we're expecting a space, then restart loop
// otherwise treat the space as a normal char
if seqend = 0 then
begin
array_push( items, arg );
arg := ' ';
break; // exit repeat loop
end else
begin
// add the space to current arg
arg := concat( arg, ' ' );
// and continue repeat loop
end;
end;
'"': begin
// encountered double quotes
// if we're expecting a double quote, then restart the loop
// otherwise treat the double quote as a normal char
chr1 := str_get( cmd );
if ( seqend = 1 ) and ( ( chr1 = ' ' ) or ( chr1 = #0 ) ) then
begin
// add current double quote to the current item
arg := concat( arg, '"' );
// increment args, and exit this repeat loop
array_push( items, arg );
arg := '';
break; // exit repeat loop;
end else
begin
// add the double quote to the current arg
arg := concat( arg, '"' );
// and continue repeat loop
end;
end;
'''': begin
// encountered mono quote
// if we're expecting a mono quote, then restart the loop
// otherwise treat the mono quote as a normal char
chr1 := str_get( cmd );
if ( seqend = 2 ) and ( ( chr1 = ' ' ) or ( chr1 = #0 ) ) then
begin
// add current mono quote to the current item
arg := concat( arg, '''' );
// increment args, and exit this repeat loop
array_push( items, arg );
arg := '';
break;
end else
begin
// add the mono quote to the current arg
arg := concat( arg, '''' );
// and continue repeat loop
end;
end else
begin
// encountered a non white-space character.
arg := concat( arg, chr );
// continue this repeat loop...
end;
end; //case
until ( false );
end;
end;
// basically we call the "auto.php" "$argumentIndex" "$firstArgText" "$subString"
function call_autocomplete (
argumentIndex: integer;
firstArgumentText: string;
subString: string ): tstrarray;
var testFile : String;
outputLines : TStringList;
memStream : TMemoryStream;
ourProcess : TProcess;
numBytes : Longint;
bytesRead : Longint;
out : tstrarray;
i : integer;
begin
testFile := base_dir() + '/../plugins/auto.php';
setlength( out, 0 );
if not fileExists( testFile ) then
begin
textcolor( red );
writeln( '* autocomplete: file "plugins/auto.php" was not found. function disabled' );
textcolor( lightgray );
exit( out );
end;
outputLines := TStringList.create;
memStream := TMemoryStream.create;
bytesRead := 0;
ourProcess := TProcess.create( nil );
ourProcess.executable := which( 'php' );
ourProcess.parameters.add( testFile );
ourProcess.parameters.add( '-ENV=site:' + term_get_env( 'site' ) );
ourProcess.parameters.add( '-ENV=path:' + term_get_env( 'path' ) );
ourProcess.parameters.add( '-ENV=user:' + term_get_env( 'user' ) );
ourProcess.parameters.add( '-ENV=password:' + term_get_env( 'password' ) );
ourProcess.parameters.add( IntToStr( argumentIndex ) );
if argumentIndex > 0 then
begin
ourProcess.parameters.add( firstArgumentText );
end else
begin
// add empty argument. it seems that empty arguments rise a problem into the
// tprocess class, so we found a workaround for this.
ourProcess.parameters.add( '---empty---argument---fpc---tprocess---bug---' );
end;
if subString = '' then
ourProcess.parameters.add( '---empty---argument---fpc---tprocess---bug---' )
else
ourProcess.parameters.add( subString );
ourProcess.Options := [ poUsePipes ];
ourProcess.Execute;
while true do begin
memStream.setSize( bytesRead + 2048 );
numBytes := ourProcess.output.read( ( memStream.memory + bytesRead )^, 2048 );
if numBytes > 0 then
inc( bytesRead, numBytes )
else
break;
end;
memStream.SetSize( bytesRead );
outputLines.loadFromStream( memStream );
ourProcess.free;
memStream.free;
// populate the out array with the entries
for i:=0 to outputLines.count - 1 do begin
if outputLines[i] <> '' then
array_push( out, outputLines[i] )
else
break;
end;
exit( out );
end;
procedure show_completion_list( list: tstrarray; leftArg: string );
var longestItem : integer = 0;
i: integer;
maxCols: integer;
begin
for i:=0 to length( list ) - 1 do begin
if longestItem < length( list[i] ) then
longestItem := length( list[i] );
end;
// determine on how many columns to display output
maxCols := trunc( screenWidth / longestItem );
if maxCols < 1 then maxCols := 1;
writeln();
for i := 0 to length( list ) - 1 do begin
clreol();
textcolor( lightgray );
write( leftArg );
textColor( cyan );
write( copy( list[i], length( leftArg ) + 1, length( list[i] ) - length( leftArg ) ) );
write( padLeft( ' ', longestItem - length( list[i] ) + 2 ) );
end;
writeln();
textcolor( white );
end;
function autocomplete_get_starting_sequence( t: tstrarray; user_input: string ) : tstrarray;
var out: tstrarray;
i: integer;
ret: string;
retlen: integer;
loops: integer;
good: boolean;
c: char;
index: integer;
begin
ret := user_input;
loops := 0;
if length( t ) < 2 then exit( t );
while true do
begin
retlen := length( ret );
index := retlen + 1;
good := true;
for i:=0 to length( t ) - 1 do begin
if length( t[i] ) < retlen then
begin
good := false;
break;
end;
if i = 0 then
c := t[i][ index ]
else begin
if c <> t[i][index] then
begin
good := false;
break;
end;
end;
end;
if good = true then
begin
loops := loops + 1;
ret := ret + c;
end else
begin
break;
end;
end;
if loops > 0 then
begin
setlength( out, 1 );
out[0] := ret;
exit( out );
end else
begin
exit( t );
end;
end;
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
DesignTime registration code for the Physics Managers
}
unit GLPhysicsRegister;
interface
uses
System.Classes,
GLODEManager,
GLNGDManager,
GLPhysics;
procedure Register;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
procedure Register;
begin
RegisterClasses([TGLODEManager, TGLODEJointList, TODEJoints, TODEElements,
TGLNGDManager, TGLNGDDynamic, TGLNGDStatic]);
RegisterComponents('GLScene',[TGLODEManager,TGLODEJointList,
TGLNGDManager, TGLPhysicsManager]);
end;
end.
|
unit Config;
interface
uses
SysUtils, Forms;
var
BinFolder: string;
ConfigFolder: string;
HomeFolder: string;
LibSourceFolder: string;
RefFolder: string;
TpLibDocsFolder: string;
implementation
const
cHomeSuffix = '..\';
cConfigSuffix = 'config\';
cDocsSuffix = 'docs\TurboPhpLib\';
cLibSuffix = 'libs\';
cRefSuffix = 'ref\default\';
procedure InitGlobals;
begin
BinFolder := ExtractFilePath(Application.ExeName);
HomeFolder := ExpandFileName(BinFolder + cHomeSuffix);
ConfigFolder := HomeFolder + cConfigSuffix;
LibSourceFolder := HomeFolder + cLibSuffix;
RefFolder := HomeFolder + cRefSuffix;
TpLibDocsFolder := HomeFolder + cDocsSuffix;
end;
initialization
InitGlobals;
end.
|
unit uFinLancamentoCalc;
interface
const
FIN_LANCAMENTO_SINGLE = 0;
FIN_LANCAMENTO_PARENT = 1;
FIN_LANCAMENTO_CHILD = 2;
//############ Disbursiment ###############
//Recalcula o Total do Disbursement Parent
function UpdateTotalDisbursement(sIDLancamentoParent:String):Boolean;
//Atualiza as Alteracao do Disbursement Parent e dos Filhos
procedure UpdateDisbursementFields(sIDLancamento, sIDLancamentoParent:String);
//Atualiza os disbursements filhos
procedure UpdateDisbursementsChildren(sIDLancamentoParent:String);
//Atualiza o status dos filho only
procedure UpdateStatusChildren(sIDLancamentoParent:String);
//Atualiza o status do Pai e Filhos
procedure UpdateStatusParent(sIDLancamento, sIDLancamentoParent:String);
//retorn a list de IDLancamentos para alteracao
function GetIDLancamentos(sIDLancamento, sIDLancamentoParent:String):String;
//verifica se o Parent tem disbursemente
function HasDisbursement(IDLancParent:integer):Boolean;
//############ Temp Table AQuitar ###############
procedure DeleteAQuitar(IDLancamento: integer); //Deleta as records na Temp Tbl Aquitar
procedure InsereAQuitar(IDLancamento: integer; bHasParent:Boolean); //Insere Lancamentos na Temp Tbl Aquitar
procedure CreateAQuitar; //Create a TmpTable AQuitar
//############ Payment ###############
function OnBeforePay:Boolean;
function OnAfterPay:Boolean;
function GetTotalQuitado(IDLanc:Integer):Currency;
implementation
uses uDM, Sysutils;
function GetIDLancamentos(sIDLancamento, sIDLancamentoParent:String):String;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('Select IDLancamento');
SQL.Add('From Fin_Lancamento');
SQL.Add('Where IDLancamentoParent = '+ sIDLancamentoParent);
SQL.Add('and IDLancamento <> ' + sIDLancamento);
Open;
if IsEmpty then
Result := sIDLancamentoParent
else
begin
First;
Result := sIDLancamentoParent + ', ';
While not EOF do
begin
Result := Result + FieldByName('IDLancamento').AsString;
Next;
If not EOF then
Result := Result + ', ';
end;
end;
Close;
end;
end;
procedure UpdateStatusParent(sIDLancamento, sIDLancamentoParent:String);
var
sIDLancamentos : String;
begin
if (sIDLancamento = '') or (sIDLancamentoParent = '') then
Exit;
sIDLancamentos := GetIDLancamentos(sIDLancamento,sIDLancamentoParent);
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('UPDATE L');
SQL.Add('SET L.Desativado = LO.Desativado,');
SQL.Add('L.Hidden = LO.Hidden');
SQL.Add('FROM Fin_Lancamento L, Fin_Lancamento LO');
SQL.Add('WHERE L.IDLancamento In ('+sIDLancamentos+')');
SQL.Add('AND LO.IDLancamento = ' + sIDLancamento);
ExecSQL;
end;
end;
procedure UpdateStatusChildren(sIDLancamentoParent:String);
begin
if sIDLancamentoParent = '' then
Exit;
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('UPDATE L');
SQL.Add('SET L.Desativado = LO.Desativado,');
SQL.Add('L.Hidden = LO.Hidden');
SQL.Add('FROM Fin_Lancamento L, Fin_Lancamento LO');
SQL.Add('WHERE L.IDLancamentoParent = '+sIDLancamentoParent+'');
SQL.Add('AND LO.IDLancamento = ' + sIDLancamentoParent);
ExecSQL;
end;
end;
procedure UpdateDisbursementsChildren(sIDLancamentoParent : String);
begin
if sIDLancamentoParent = '' then
Exit;
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('UPDATE L');
SQL.Add('SET L.IDEmpresa = LO.IDEmpresa,');
SQL.Add('L.IDCentroCusto = LO.IDCentroCusto,');
SQL.Add('L.IDPessoaTipo = LO.IDPessoaTipo,');
SQL.Add('L.IDPessoa = LO.IDPessoa,');
SQL.Add('L.IDDocumentoTipo = LO.IDDocumentoTipo,');
SQL.Add('L.IDDesdobramentoTipo = LO.IDDesdobramentoTipo,');
SQL.Add('L.IDQuitacaoMeioPrevisto = LO.IDQuitacaoMeioPrevisto,');
SQl.Add('L.IDContaCorrentePrevista = LO.IDContaCorrentePrevista,');
SQL.Add('L.DataEmissao = LO.DataEmissao,');
SQL.Add('L.DataVencimento = LO.DataVencimento,');
SQL.Add('L.NumDesdobramento = LO.NumDesdobramento,');
SQL.Add('L.NumDocumento = LO.NumDocumento,');
SQL.Add('L.NumMeioQuitPrevisto = LO.NumMeioQuitPrevisto,');
SQL.Add('L.FavorecidoPrevisto = LO.FavorecidoPrevisto,');
SQL.Add('L.Desativado = LO.Desativado,');
SQL.Add('L.Hidden = LO.Hidden');
SQL.Add('FROM Fin_Lancamento L, Fin_Lancamento LO');
SQL.Add('WHERE L.IDLancamentoParent = '+sIDLancamentoParent+'');
SQL.Add('AND LO.IDLancamento = ' + sIDLancamentoParent);
ExecSQL;
end;
end;
procedure UpdateDisbursementFields(sIDLancamento, sIDLancamentoParent:String);
var
sIDLancamentos : String;
begin
if (sIDLancamento = '') or (sIDLancamentoParent = '') then
Exit;
sIDLancamentos := GetIDLancamentos(sIDLancamento,sIDLancamentoParent);
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('UPDATE L');
SQL.Add('SET L.IDEmpresa = LO.IDEmpresa,');
SQL.Add('L.IDCentroCusto = LO.IDCentroCusto,');
SQL.Add('L.IDPessoaTipo = LO.IDPessoaTipo,');
SQL.Add('L.IDPessoa = LO.IDPessoa,');
SQL.Add('L.IDDocumentoTipo = LO.IDDocumentoTipo,');
SQL.Add('L.IDDesdobramentoTipo = LO.IDDesdobramentoTipo,');
SQL.Add('L.IDQuitacaoMeioPrevisto = LO.IDQuitacaoMeioPrevisto,');
SQl.Add('L.IDContaCorrentePrevista = LO.IDContaCorrentePrevista,');
SQL.Add('L.DataEmissao = LO.DataEmissao,');
SQL.Add('L.DataVencimento = LO.DataVencimento,');
SQL.Add('L.NumDesdobramento = LO.NumDesdobramento,');
SQL.Add('L.NumDocumento = LO.NumDocumento,');
SQL.Add('L.NumMeioQuitPrevisto = LO.NumMeioQuitPrevisto,');
SQL.Add('L.FavorecidoPrevisto = LO.FavorecidoPrevisto,');
SQL.Add('L.Desativado = LO.Desativado,');
SQL.Add('L.Hidden = LO.Hidden');
SQL.Add('FROM Fin_Lancamento L, Fin_Lancamento LO');
SQL.Add('WHERE L.IDLancamento In ('+sIDLancamentos+')');
SQL.Add('AND LO.IDLancamento = ' + sIDLancamento);
ExecSQL;
end;
end;
function UpdateTotalDisbursement(sIDLancamentoParent:String):Boolean;
begin
if sIDLancamentoParent = '' then
Exit;
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('Update Fin_Lancamento');
SQL.Add('Set ValorNominal = IsNull((Select Sum(IsNull(ValorNominal,0))');
SQL.Add('From Fin_Lancamento Where IDLancamentoParent = '+sIDLancamentoParent+'),0)');
SQl.Add('Where IDLancamento = ' + sIDLancamentoParent);
ExecSQL;
end;
end;
procedure DeleteAQuitar(IDLancamento: integer);
begin
with DM.quFreeSQL do
begin
if Active then
Close;
if IDLancamento < 0 then
SQL.Text := 'DELETE #AQuitar'
else
SQL.Text := 'DELETE #AQuitar WHERE IDLancamento = ' + IntToStr(IDLancamento);
ExecSQL;
end;
end;
procedure InsereAQuitar(IDLancamento: integer; bHasParent:Boolean);
var
sSQL : String;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
sSQL := 'Insert #AQuitar (IDLancamento, ValorAQuitar, IDContaCorrente, Favorecido, ' +
' IDQuitacaoMeio, NumeroMeioQuit, ValorDiscount) ' +
'SELECT L.IDLancamento, ' +
' (L.ValorNominal - L.TotalQuitado), ' +
' IsNull(L.IDContaCorrentePrevista, -1), ' +
' IsNull(L.FavorecidoPrevisto,P.Pessoa) as FavorecidoPrevisto, ' +
' IsNull(L.IDQuitacaoMeioPrevisto, -1), L.NumMeioQuitPrevisto, ' +
' CASE IsNull(L.TotalQuitado,0) ' +
' WHEN 0 ' +
' THEN IsNull( -1 * (L.ValorNominal - (L.ValorNominal * (1-(LAT.Discount/100)))),0) ' +
' ELSE 0 ' +
' END ' +
'FROM Fin_Lancamento L (NOLOCK) ' +
'LEFT OUTER JOIN dbo.vw_Fin_LancamentoActiveTerm LAT ' +
' ON (L.IDLancamento = LAT.IDLancamento) ' +
'LEFT OUTER JOIN Pessoa P ' +
' ON (L.IDPessoa = P.IDPessoa) ';
if bHasParent then
sSQl := sSQL + ' WHERE L.IDLancamentoParent = ' + IntToStr(IDLancamento)
else
sSQl := sSQL + ' WHERE L.IDLancamento = ' + IntToStr(IDLancamento);
SQL.Text := sSQl;
ExecSQL;
end;
end;
procedure CreateAQuitar;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'CREATE TABLE #AQuitar ( IDLancamento int NOT NULL, ' +
'ValorAQuitar Money NULL, ' +
'IDContaCorrente int NULL, ' +
'Favorecido VarChar(60) NULL, ' +
'IDQuitacaoMeio int NULL, ' +
'NumeroMeioQuit VarChar(60) NULL, ' +
'ValorDiscount Money NULL )';
ExecSQL;
end;
end;
function OnBeforePay:Boolean;
begin
Result := True;
end;
function OnAfterPay:Boolean;
begin
Result := True;
end;
function GetTotalQuitado(IDLanc:Integer):Currency;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT SUM(IsNull(ValorQuitado,0)) FROM Fin_LancQuit Q ' +
'WHERE Q.IDLancamento = ' + intToStr(IDLanc);
Open;
Result := Fields[0].AsCurrency;
Close;
end;
end;
function HasDisbursement(IDLancParent:integer):Boolean;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT L.IDLancamento FROM Fin_Lancamento L ' +
'WHERE L.IDLancamentoParent = ' + intToStr(IDLancParent);
Open;
Result := not IsEmpty;
Close;
end;
end;
end.
|
unit uFrameObjectReestr;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, uFrameOKOF, ExtCtrls, cxClasses, uFrameObjects, cxSplitter, cxPC,
StdCtrls, uFrameUserData, uAccess, ActnList, Menus,
cxLookAndFeelPainters, cxDropDownEdit, cxCalendar, cxTextEdit,
cxCurrencyEdit, cxDBEdit, cxMaskEdit, cxButtonEdit, cxContainer, cxEdit,
cxGroupBox, cxButtons, uFrameObjectsByProps, uFrameObjectFilter, dxBar,
dxNavBar, dxNavBarCollns, dxNavBarBase;
type
TFrameObjectReestr = class(TFrame)
NavBar: TdxNavBar;
grSelf: TdxNavBarGroup;
grOKOF: TdxNavBarGroup;
grSelfControl: TdxNavBarGroupControl;
grOKOFControl: TdxNavBarGroupControl;
FrameOKOF: TFrameOKOF;
FrameOjects: TFrameOjects;
pnlFrame: TPanel;
cxSplitter: TcxSplitter;
pnlData: TPanel;
pcAllData1: TcxPageControl;
Button1: TButton;
tsData1: TcxTabSheet;
grProps: TdxNavBarGroup;
grPropsControl: TdxNavBarGroupControl;
Label4: TLabel;
Label5: TLabel;
Label8: TLabel;
Label9: TLabel;
pcAllData2: TcxPageControl;
tsData2: TcxTabSheet;
pcAllData3: TcxPageControl;
tsData3: TcxTabSheet;
FrameObjectFilter: TFrameObjectFilter;
DockControl: TdxBarDockControl;
ReestrBarManager: TdxBarManager;
ReestrBarManagerBar1: TdxBar;
procedure Button1Click(Sender: TObject);
procedure NavBarActiveGroupChanged(Sender: TObject);
procedure FrameOjectscolNamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
TabSheetNameCounter: integer;
FCreatedBook1: TAccessBook;
FFrameByProps: TFrameObjectsByProps;
protected
procedure SetVisiblePageControl(Index: byte);
procedure btn4ApplyFilterClick(Sender: TObject); virtual;
public
property CreatedBook1: TAccessBook read FCreatedBook1;
property FrameByProps: TFrameObjectsByProps read FFrameByProps;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses uMain, uDlgTypesSelect, uSel_ObjectType, uUserBook,
uBASE_ObjectPropsForm, uFrmOKOF, uParams, uCommonUtils;
{$R *.dfm}
{ TFrameObjectReestr }
constructor TFrameObjectReestr.Create(AOwner: TComponent);
begin
inherited;
TabSheetNameCounter:=1;
FCreatedBook1:=nil;
FFrameByProps:=nil;
pcAllData1.Align:=alClient;
pcAllData2.Align:=alClient;
pcAllData3.Align:=alClient;
NavBarActiveGroupChanged(nil);
self.FrameObjectFilter.bbApplyFilter.OnClick:=btn4ApplyFilterClick;
SetVisiblePageControl(NavBar.ActiveGroupIndex);
end;
procedure TFrameObjectReestr.Button1Click(Sender: TObject);
var
dlg: TdlgTypesSelect;
begin
dlg:=TdlgTypesSelect.Create(nil);
try
if dlg.ShowModal<>mrOK then exit;
finally
dlg.Free;
end;
end;
destructor TFrameObjectReestr.Destroy;
begin
if Assigned(FCreatedBook1) then
CreatedBook1.Free;
inherited;
end;
procedure TFrameObjectReestr.SetVisiblePageControl(Index: byte);
begin
pcAllData1.Visible:=Index=1;
pcAllData2.Visible:=Index=2;
pcAllData3.Visible:=Index=0;
end;
procedure TFrameObjectReestr.NavBarActiveGroupChanged(Sender: TObject);
begin
SetVisiblePageControl(NavBar.ActiveGroupIndex);
end;
procedure TFrameObjectReestr.btn4ApplyFilterClick(Sender: TObject);
var
p: TParamCollection;
begin
if Assigned(FrameByProps) then
FrameByProps.Free;
FFrameByProps:=TFrameObjectsByProps.Create(nil);
FrameByProps.actInsert.Visible:=true;
FrameByProps.Parent:=tsData3;
FrameByProps.Align:=alClient;
p:=FrameObjectFilter.CreateFilterParams;
try
FrameByProps.ApplyFilterParams(p);
FrameByProps.RestoryGrid(163);
finally
p.Free;
end;
end;
procedure TFrameObjectReestr.FrameOjectscolNamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
if Assigned(CreatedBook1) then
CreatedBook1.Free;
FCreatedBook1:=TAccessBook.Create;
CreatedBook1.ObjectID:=self.FrameOjects.ObjectID;
CreatedBook1.PropsFormClass:=TBASE_ObjectPropsForm;
CreatedBook1.ShowOnControl(tsData1);
end;
end.
|
unit uStrings;
{$I ..\Include\IntXLib.inc}
interface
resourcestring
AlphabetRepeatingChars = 'Alphabet characters must be unique.';
AlphabetTooSmall = 'Alphabet is too small to represent numbers in base %u.';
CantBeNull = 'Operand(s) can''t be null.';
CantBeNullCmp = 'Can''t use null in comparison operations.';
CantBeNullOne = 'Operand can''t be null.';
DigitBytesLengthInvalid = 'Digit bytes array length is invalid.';
FhtMultiplicationError =
'FHT multiplication returned invalid results for TIntX objects with lengths %u and %u.';
IntegerTooBig = 'One of the operated big integers is too big.';
ParseBaseInvalid = 'Base is invalid.';
ParseInvalidChar = 'Invalid character in input.';
ParseNoDigits = 'No digits in string.';
ParseTooBigDigit = 'Digit is too big for this base.';
ToStringSmallBase = 'Base must be between 2 and 65536.';
DivideByZero = 'Attempted to divide by Zero.';
DivisionUndefined = 'Division undefined (0/0)';
NegativeFactorial = 'Can''t calculate factorial for negative number %s.';
BezoutNegativeNotAllowed = 'Negative value not allowed for Bézouts identity.';
BezoutNegativeCantComputeZero = 'One or more parameters are Zero.';
NegativeSquareRoot = 'Cannot compute squareroot of Negative number.';
LogCantComputeZero = 'One or more parameters are Zero.';
LogNegativeNotAllowed = 'Negative value not allowed for LogN';
InvModNegativeNotAllowed = 'Negative value not allowed for Modular Inverse.';
ModPowExponentCantbeNegative =
'Exponent Can''t be Negative for Modular Exponentiation.';
ModPowModulusCantbeZeroorNegative = 'Modulus Can''t be Zero or Negative';
Overflow_TIntXInfinity = 'TIntX cannot represent infinity.';
Overflow_NotANumber = 'The value is not a number.';
OverFlow_Data = 'TIntX value won''t fit in destination type';
implementation
end.
|
unit UTotalGastoMes;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.StdCtrls, Generics.Collections,
Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, UTotalGastoMesVO,
UTotalGastoMesController, Biblioteca;
type
TFTelaCadastroTotalGastoMes = class(TFTelaCadastro)
MaskEditDtInicio: TMaskEdit;
Label1: TLabel;
EdtValor: TEdit;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
function DoSalvar: boolean; override;
function MontaFiltro: string;
procedure DoConsultar; override;
function DoExcluir: boolean; override;
procedure BitBtnNovoClick(Sender: TObject);
procedure GridParaEdits; override;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MaskEditDtInicioExit(Sender: TObject);
procedure EdtValorKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
function EditsToObject(TotalGastoMes: TTotalGastoMesVO): TTotalGastoMesVO;
end;
var
FTelaCadastroTotalGastoMes: TFTelaCadastroTotalGastoMes;
ControllerTotalGastoMes : TTotalGastoMesController;
implementation
{$R *.dfm}
uses UEmpresaTrab;
{ TFTelaCadastroTotalGastoMes }
procedure TFTelaCadastroTotalGastoMes.BitBtnNovoClick(Sender: TObject);
begin
inherited;
MaskEditDtInicio.SetFocus;
end;
procedure TFTelaCadastroTotalGastoMes.DoConsultar;
var
listaTotalGastoMes: TObjectList<TTotalGastoMesVo>;
filtro: string;
begin
filtro := MontaFiltro;
listaTotalGastoMes := ControllerTotalGastoMes.Consultar(filtro, 'ORDER BY DTMESANO DESC');
PopulaGrid<TTotalGastoMesVo>(listaTotalGastoMes);
end;
function TFTelaCadastroTotalGastoMes.DoExcluir: boolean;
var
TotalGastoMes : TTotalGastoMesVo;
begin
try
try
TotalGastoMes := TTotalGastoMesVo.Create;
TotalGastoMes.idToTalGastoMes := CDSGrid.FieldByName('IDTOTALGASTOMES')
.AsInteger;
ControllerTotalGastoMes.Excluir(TotalGastoMes);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroTotalGastoMes.DoSalvar: boolean;
var
TotalGastoMes: TTotalGastoMesVO;
begin
begin
TotalGastoMes:=EditsToObject(TTotalGastoMesVO.Create);
try
try
TotalGastoMes.ValidarCampos();
if (StatusTela = stInserindo) then
begin
TotalGastoMes.idcondominio := FormEmpresaTrab.CodigoEmpLogada;
ControllerTotalGastoMes.Inserir(TotalGastoMes);
Result := true;
end
else if (StatusTela = stEditando) then
begin
TotalGastoMes := ControllerTotalGastoMes.ConsultarPorId(CDSGrid.FieldByName('IDTOTALGASTOMES')
.AsInteger);
TotalGastoMes := EditsToObject(TotalGastoMes);
ControllerTotalGastoMes.Alterar(TotalGastoMes);
Result := true;
end;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
end;
function TFTelaCadastroTotalGastoMes.EditsToObject(
TotalGastoMes: TTotalGastoMesVO): TTotalGastoMesVO;
begin
if(EdtValor.Text<>'')then
TotalGastoMes.vlTotal := StrToFloat(EdtValor.Text);
if(MaskEditDtInicio.Text<>' / / ')then
TotalGastoMes.dtMesAno := StrToDateTime(MaskEditDtInicio.Text);
Result := TotalGastoMes;
end;
procedure TFTelaCadastroTotalGastoMes.EdtValorKeyPress(Sender: TObject;
var Key: Char);
begin
EventoFormataCurrency(Sender,key);
end;
procedure TFTelaCadastroTotalGastoMes.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerTotalGastoMes);
end;
procedure TFTelaCadastroTotalGastoMes.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TTotalGastoMesVO;
ControllerTotalGastoMes := TTotalGastoMesController.Create;
inherited;
end;
procedure TFTelaCadastroTotalGastoMes.GridParaEdits;
var
TotalGastoMes: TTotalGastoMesVo;
begin
inherited;
if not CDSGrid.IsEmpty then
TotalGastoMes := ControllerTotalGastoMes.ConsultarPorId
(CDSGrid.FieldByName('IDTOTALGASTOMES').AsInteger);
if Assigned(TotalGastoMes) then
begin
EdtValor.Text := FloatToStr(TotalGastoMes.vlTotal);
MaskEditDtInicio.Text := DateTimeToStr(TotalGastoMes.dtMesAno);
end;
end;
procedure TFTelaCadastroTotalGastoMes.MaskEditDtInicioExit(Sender: TObject);
begin
EventoValidaData(sender);
end;
function TFTelaCadastroTotalGastoMes.MontaFiltro: string;
begin
result := '';
if (editBusca.Text <> '') then
Result := ' VLTOTAL LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%');
end;
end.
|
unit UII2XAbout;
interface
uses
Windows,
SysUtils,
Classes,
Graphics,
Forms,
Controls,
StdCtrls,
Buttons,
ExtCtrls,
uImage2XML,
ShellAPI;
type
TAboutBox = class(TForm)
pnlAbout: TPanel;
ProgramIcon: TImage;
lblProductName: TLabel;
lblVersion: TLabel;
lblCopyright: TLabel;
lblURL: TLabel;
lblComments: TLabel;
lblSupport: TLabel;
procedure FormCreate(Sender: TObject);
procedure lblURLClick(Sender: TObject);
procedure lblSupportClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AboutBox: TAboutBox;
implementation
{$R *.dfm}
procedure TAboutBox.FormCreate(Sender: TObject);
begin
self.lblProductName.Caption := APP_NAME;
self.lblVersion.Caption := 'V.' + sVERSION;
self.lblCopyright.Caption := 'Copyright © 2009 Noctusoft, Inc.';
self.lblURL.Caption := 'www.image2xml.com';
self.lblSupport.Caption := 'support.image2xml.com';
self.lblComments.Caption := '';
end;
procedure TAboutBox.lblSupportClick(Sender: TObject);
var
sURL : string;
begin
sURL := 'http://' + lblSupport.Caption;
ShellExecute(&0, 'open', pchar( sURL ), nil,nil,SW_SHOWNORMAL);
end;
procedure TAboutBox.lblURLClick(Sender: TObject);
var
sURL : string;
begin
sURL := 'http://' + lblURL.Caption;
ShellExecute(&0, 'open', pchar( sURL ), nil,nil,SW_SHOWNORMAL);
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
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/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_Decorators;
interface
type
IControlObject = interface
['{420914AC-6242-417E-8D18-7B163056DA60}']
function ControlObject: TObject;
end;
{$IF compilerversion >= 21}
IntegerRange = class( TCustomAttribute)
private
FMin, FMax: Integer;
public
constructor Create( Min1, Max1: Integer);
property Min : integer read FMin;
property Max : Integer read FMax;
end;
DesignDescription = class( TCustomAttribute)
private
FDescription: string;
public
constructor Create( const Description1: string);
property Description: string read FDescription;
end;
{$ENDIF}
IVariableSeedSize = Interface
['{38096CBB-5ACB-43D7-826A-C21812F6E447}']
function MinSeedByteSize: integer;
function MaxSeedByteSize: integer;
property Min : integer read MinSeedByteSize;
property Max : Integer read MaxSeedByteSize;
end;
implementation
{$IF compilerversion >= 21}
constructor IntegerRange.Create( Min1, Max1: Integer);
begin
inherited Create;
FMin := Min1;
FMax := Max1
end;
constructor DesignDescription.Create( const Description1: string);
begin
FDescription := Description1
end;
{$ENDIF}
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
Panel1: TPanel;
LabeledEdit1: TLabeledEdit;
LabeledEdit2: TLabeledEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure SetUpGrid;
procedure LoadStrings(const ASourcePath, ADestinationPath: string);
procedure SaveStrings(const ADestinationPath: string);
function LoadFile(const AFileName: string): string;
procedure SaveFile(const AFileName, AText: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
System.Types,
Vcl.FileCtrl,
System.IOUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
Directory: string;
begin
if SelectDirectory(Directory, [], 0) then
LabeledEdit1.Text := Directory;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Directory: string;
begin
if SelectDirectory(Directory, [], 0) then
LabeledEdit2.Text := Directory;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
SetUpGrid;
LoadStrings(LabeledEdit1.Text, LabeledEdit2.Text);
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
SaveStrings(LabeledEdit2.Text);
end;
procedure TForm1.LoadStrings(const ASourcePath, ADestinationPath: string);
var
SourceFiles: TStringDynArray;
FileName: string;
DestinationPath: string;
LC: Integer;
DestinationExists: Boolean;
begin
if not TDirectory.Exists(ASourcePath) then
raise Exception.Create('Source directory not found');
DestinationExists := TDirectory.Exists(ADestinationPath);
SourceFiles := TDirectory.GetFiles(ASourcePath);
StringGrid1.RowCount := High(SourceFiles) + 1;
for LC := 0 to High(SourceFiles) do
begin
FileName := ExtractFileName(SourceFiles[LC]);
StringGrid1.Cells[0, LC + 1] := FileName;
StringGrid1.Cells[1, LC + 1] := LoadFile(SourceFiles[LC]);
if DestinationExists then
begin
DestinationPath := TPath.Combine(ADestinationPath, FileName);
StringGrid1.Cells[2, LC + 1] := LoadFile(DestinationPath);
if StringGrid1.Cells[1, LC + 1] <> StringGrid1.Cells[2, LC + 1] then
StringGrid1.Cells[3, LC + 1] := '*';
end;
end;
end;
function TForm1.LoadFile(const AFileName: string): string;
begin
Result := '';
with TStreamReader.Create(AFileName, TEncoding.UTF8) do
try
Result := ReadToEnd;
finally
Free;
end;
end;
procedure TForm1.SaveStrings(const ADestinationPath: string);
var
LC: Integer;
FileName : string;
DestinationFilePath: string;
begin
if StringGrid1.RowCount < 2 then
raise Exception.Create('Nothing to save');
if not TDirectory.Exists(ADestinationPath) then
raise Exception.Create('Target directory not found');
for LC := 1 to StringGrid1.RowCount - 1 do
begin
FileName := StringGrid1.Cells[0, LC];
DestinationFilePath := TPath.Combine(ADestinationPath, FileName);
SaveFile(DestinationFilePath, StringGrid1.Cells[2, LC]);
end;
end;
procedure TForm1.SaveFile(const AFileName, AText: string);
begin
with TStreamWriter.Create(AFileName, False, TEncoding.UTF8) do
try
BaseStream.Size := 0;
Write(AText);
finally
Free;
end;
end;
procedure TForm1.SetUpGrid;
begin
StringGrid1.RowCount := 1;
StringGrid1.RowCount := 2;
StringGrid1.ColCount := 4;
StringGrid1.FixedRows := 1;
StringGrid1.Cells[0, 0] := 'Resource ID';
StringGrid1.Cells[1, 0] := 'Original value';
StringGrid1.Cells[2, 0] := 'Translated value';
StringGrid1.Cells[3, 0] := 'Diff';
StringGrid1.ColWidths[1] := 300;
StringGrid1.ColWidths[2] := 300;
StringGrid1.ColWidths[3] := 20;
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
GridOptions: TGridOptions;
begin
GridOptions := StringGrid1.Options;
if ACol = 2 then
Include(GridOptions, TGridOption.goEditing)
else
Exclude(GridOptions, TGridOption.goEditing);
StringGrid1.Options := GridOptions;
end;
procedure TForm1.StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer;
const Value: string);
begin
if Value = StringGrid1.Cells[ACol - 1, ARow] then
StringGrid1.Cells[ACol + 1, ARow] := ''
else
StringGrid1.Cells[ACol + 1, ARow] := '*';
end;
end.
|
unit ini_type_region_FORM;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
pFIBDatabase, Buttons, ToolWin, ComCtrls, ExtCtrls, FIBQuery, FIBDataSet,
pFIBDataSet, pFIBStoredProc, ActnList, Menus, COMMON, Grids, Db, DBGrids,
pFIBQuery, StdCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxControls, cxGridCustomView, cxGrid, cxContainer, cxTextEdit, ImgList,
FIBDatabase, Ibase, variants, dxBar, dxBarExtItems, cxTL;
type
TFini_type_region = class(TForm)
DataSource: TDataSource;
DataSet: TpFIBDataSet;
StoredProc: TpFIBStoredProc;
ActionList1: TActionList;
Action_Add: TAction;
Action_Del: TAction;
Action_Mod: TAction;
Action_Refresh: TAction;
Action_Up: TAction;
Action_Down: TAction;
Action_Sel: TAction;
Action_Exit: TAction;
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DBTableView1ID_TYPE_PLACE: TcxGridDBColumn;
cxGrid1DBTableView1NAME_FULL: TcxGridDBColumn;
cxGrid1DBTableView1NAME_SHORT: TcxGridDBColumn;
cxGrid1DBTableView1ORDER: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
dxBarManager1: TdxBarManager;
AddButton: TdxBarLargeButton;
UpdateButton: TdxBarLargeButton;
DelButton: TdxBarLargeButton;
ChooseButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
CloseButton: TdxBarLargeButton;
DownButton: TdxBarLargeButton;
UpButton: TdxBarLargeButton;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
cxStyle29: TcxStyle;
cxStyle30: TcxStyle;
cxStyle31: TcxStyle;
cxStyle32: TcxStyle;
cxStyle33: TcxStyle;
cxStyle34: TcxStyle;
cxStyle35: TcxStyle;
cxStyle36: TcxStyle;
cxStyle37: TcxStyle;
cxStyle38: TcxStyle;
cxStyle39: TcxStyle;
cxStyle40: TcxStyle;
cxStyle41: TcxStyle;
cxStyle42: TcxStyle;
TreeListStyleSheetDevExpress: TcxTreeListStyleSheet;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
procedure ExitButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure ModButtonClick(Sender: TObject);
procedure DelButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure DataSetAfterScroll(DataSet: TDataSet);
procedure UpButtonClick(Sender: TObject);
procedure DownButtonClick(Sender: TObject);
procedure Action_AddExecute(Sender: TObject);
procedure Action_DelExecute(Sender: TObject);
procedure Action_ModExecute(Sender: TObject);
procedure Action_RefreshExecute(Sender: TObject);
procedure Action_DownExecute(Sender: TObject);
procedure Action_UpExecute(Sender: TObject);
procedure Action_SelExecute(Sender: TObject);
procedure Action_ExitExecute(Sender: TObject);
procedure SelButtonClick(Sender: TObject);
procedure PM_AddButtonClick(Sender: TObject);
procedure PM_DelButtonClick(Sender: TObject);
procedure PM_ModButtonClick(Sender: TObject);
procedure PM_RefreshButtonClick(Sender: TObject);
procedure PM_DownButtonClick(Sender: TObject);
procedure PM_UpButtonClick(Sender: TObject);
procedure PM_SelButtonClick(Sender: TObject);
procedure PM_ExitButtonClick(Sender: TObject);
procedure DBGridDblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char);
procedure SearchEditKeyPress(Sender: TObject; var Key: Char);
procedure CloseButtonClick(Sender: TObject);
public
CurFS:TFormStyle;
ActualDate:TDateTime;
ResultValue:Variant;
constructor Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle; ActualDate:TDateTime);overload;
procedure CheckButtonsState;
procedure SelectAll;
procedure LocateRecord(const id : integer);
end;
function GetIniTypeRegion(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant;stdcall;
exports GetIniTypeRegion;
implementation
uses BaseTypes, ini_type_region_FORM_ADD;
{$R *.DFM}
function GetIniTypeRegion(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant;
var T:TFini_type_region;
Res:Variant;
begin
If FS=fsNormal
then begin
T:=TFini_type_region.Create(AOwner, DBHANDLE,FS,ActualDate);
if T.ShowModal=mrYes
then begin
Res:=T.ResultValue;
end;
T.Free;
end
else begin
T:=TFini_type_region.Create(AOwner, DBHANDLE,FS,ActualDate);
Res:=NULL;
end;
GetIniTypeRegion:=Res;
end;
constructor TFini_type_region.Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle; ActualDate:TDateTime);
begin
inherited Create(AOwner);
Self.WorkDatabase.Handle:=DBHAndle;
self.ActualDate:=ActualDate;
CurFS:=FS;
if CurFS=fsNormal
then ChooseButton.Enabled:=true;
DataSet.SQLs.SelectSQL.Text := 'select * from VIEW_INI_TYPE_REGION ORDER BY "ORDER"';
DataSet.Open;
self.FormStyle:=FS;
end;
procedure TFini_type_region.SelectAll;
begin
DataSet.Active := false;
DataSet.SQLs.SelectSQL.Text := 'select * from VIEW_INI_TYPE_REGION ORDER BY "ORDER"';
DataSet.Active := true;
CheckButtonsState;
end;
//////////////////////////////////////////////////////////////
// Button processing procedures
//////////////////////////////////////////////////////////////
//Add record
procedure TFini_type_region.AddButtonClick(Sender: TObject);
var
add_form : Tfini_type_region_form_add;
id_type_region : integer;
full_name, short_name : string;
begin
add_form := Tfini_type_region_form_add.Create(Self);
add_form.Caption := 'Добавить';
if add_form.ShowModal = mrOK then begin
full_name := add_form.FullNameEdit.Text;
short_name := add_form.ShortNameEdit.Text;
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_INI_TYPE_REGION_ADD', [full_name, short_name]);
id_type_region:=StoredProc.ParamByName('ID_TYPE_REGION').AsInteger;
StoredProc.Transaction.Commit;
SelectAll;
LocateRecord(id_type_region);
end;
add_form.Free;
end;
//Modify record
procedure TFini_type_region.ModButtonClick(Sender: TObject);
var
mod_form : Tfini_type_region_form_add;
id_type_region : integer;
full_name, short_name : string;
begin
id_type_region := DataSet['ID_TYPE_REGION'];
full_name := DataSet['NAME_FULL'];
short_name := DataSet['NAME_SHORT'];
mod_form := Tfini_type_region_form_add.Create(Self);
mod_form.Caption := 'Удалить';
mod_form.FullNameEdit.Text := full_name;
mod_form.ShortNameEdit.Text := short_name;
if mod_form.ShowModal = mrOK then begin
full_name := mod_form.FullNameEdit.Text;
short_name := mod_form.ShortNameEdit.Text;
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_INI_TYPE_REGION_MOD', [id_type_region, full_name, short_name]);
StoredProc.Transaction.Commit;
SelectAll;
LocateRecord(id_type_region);
end;
mod_form.Free;
end;
//Delete record
procedure TFini_type_region.DelButtonClick(Sender: TObject);
var
id_type_region : integer;
selected_id : integer;
begin
if agMessageDlg('Увага', DELETE_QUESTION, mtWarning, [mbYes, mbNo]) = mrNo then exit;
id_type_region := DataSet['ID_TYPE_REGION'];
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_INI_TYPE_REGION_DEL', [id_type_region]);
StoredProc.Transaction.Commit;
selected_id := cxGrid1DBTableView1.Controller.FocusedRowIndex;
SelectAll;
cxGrid1DBTableView1.Controller.FocusedRowIndex := selected_id;
end;
//Refresh dbgrid
procedure TFini_type_region.RefreshButtonClick(Sender: TObject);
var
selected_id : integer;
begin
if DataSet.RecordCount = 0 then begin
SelectAll;
exit;
end;
selected_id := DataSet.FieldByName('ID_TYPE_REGION').AsInteger;
SelectAll;
DataSet.Locate('ID_TYPE_REGION', selected_id, [loCaseInsensitive]);
end;
//Close form
procedure TFini_type_region.ExitButtonClick(Sender: TObject);
begin
if FormStyle = fsMDIChild then Close else ModalResult := mrCancel;
end;
//Select record
procedure TFini_type_region.SelButtonClick(Sender: TObject);
begin
if DataSet.Active and (dataSet.RecordCount>0)
then begin
ResultValue:=VarArrayCreate([0,1],varVariant);
ResultValue[0]:=DataSet['ID_TYPE_REGION'];
ResultValue[1]:=DataSet['NAME_FULL'];
ModalResult := mrYes;
end;
end;
//Move record up
procedure TFini_type_region.UpButtonClick(Sender: TObject);
var
id_type_region : integer;
begin
id_type_region := DataSet['ID_TYPE_REGION'];
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_INI_TYPE_REGION_MOVE_UP', [id_type_region]);
StoredProc.Transaction.Commit;
SelectAll;
LocateRecord(id_type_region);
end;
//Move record down
procedure TFini_type_region.DownButtonClick(Sender: TObject);
var
id_type_region : integer;
begin
id_type_region := DataSet['ID_TYPE_REGION'];
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_INI_TYPE_REGION_MOVE_DOWN', [id_type_region]);
StoredProc.Transaction.Commit;
SelectAll;
LocateRecord(id_type_region);
end;
//////////////////////////////////////////////////////////////
// Other procedures(database dependent)
//////////////////////////////////////////////////////////////
procedure TFini_type_region.LocateRecord(const id : integer);
begin
DataSet.Locate('ID_TYPE_REGION', id, []);
end;
//////////////////////////////////////////////////////////////
// Other procedures(database independent)
//////////////////////////////////////////////////////////////
procedure TFini_type_region.CheckButtonsState;
begin
if DataSet.RecordCount = 0 then begin
DelButton.Enabled := false;
UpdateButton.Enabled := false;
DownButton.Enabled := false;
UpButton.Enabled := false;
end else begin
DelButton.Enabled := true;
UpdateButton.Enabled := true;
end;
end;
//Procedure checks up and down buttons accessibility
procedure TFini_type_region.DataSetAfterScroll(DataSet: TDataSet);
begin
if DataSet.RecNo = DataSet.RecordCount then begin
DownButton.Enabled := false;
end else begin
DownButton.Enabled := true;
end;
if DataSet.RecNo = 1 then begin
UpButton.Enabled := false;
end else begin
UpButton.Enabled := true;
end;
end;
procedure TFini_type_region.DBGridDblClick(Sender: TObject);
begin
if ChooseButton.Enabled then SelButtonClick(Self);
end;
//////////////////////////////////////////////////////////////
// Actions procedures
//////////////////////////////////////////////////////////////
procedure TFini_type_region.Action_AddExecute(Sender: TObject);
begin
AddButtonClick(Self);
end;
procedure TFini_type_region.Action_DelExecute(Sender: TObject);
begin
if DelButton.Enabled then DelButtonClick(Self);
end;
procedure TFini_type_region.Action_ModExecute(Sender: TObject);
begin
if UpdateButton.Enabled then ModButtonClick(Self);
end;
procedure TFini_type_region.Action_RefreshExecute(Sender: TObject);
begin
RefreshButtonClick(Self);
end;
procedure TFini_type_region.Action_DownExecute(Sender: TObject);
begin
if DownButton.Enabled then DownButtonClick(Self);
end;
procedure TFini_type_region.Action_UpExecute(Sender: TObject);
begin
if UpButton.Enabled then UpButtonClick(Self);
end;
procedure TFini_type_region.Action_SelExecute(Sender: TObject);
begin
if ChooseButton.Enabled then SelButtonClick(Self);
end;
procedure TFini_type_region.Action_ExitExecute(Sender: TObject);
begin
ExitButtonClick(Self);
end;
//////////////////////////////////////////////////////////////
// Popup menu procedures
//////////////////////////////////////////////////////////////
procedure TFini_type_region.PM_AddButtonClick(Sender: TObject);
begin
AddButtonClick(Self);
end;
procedure TFini_type_region.PM_DelButtonClick(Sender: TObject);
begin
DelButtonClick(Self);
end;
procedure TFini_type_region.PM_ModButtonClick(Sender: TObject);
begin
ModButtonClick(Self);
end;
procedure TFini_type_region.PM_RefreshButtonClick(Sender: TObject);
begin
RefreshButtonClick(Self);
end;
procedure TFini_type_region.PM_DownButtonClick(Sender: TObject);
begin
DownButtonClick(Self);
end;
procedure TFini_type_region.PM_UpButtonClick(Sender: TObject);
begin
UpButtonClick(Self);
end;
procedure TFini_type_region.PM_SelButtonClick(Sender: TObject);
begin
SelButtonClick(Self);
end;
procedure TFini_type_region.PM_ExitButtonClick(Sender: TObject);
begin
ExitButtonClick(Self);
end;
procedure TFini_type_region.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then Action := caFree;
end;
procedure TFini_type_region.cxGrid1DBTableView1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then if ChooseButton.Enabled then SelButtonClick(Self);
if Key = #27 then Close;
end;
procedure TFini_type_region.SearchEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then cxGrid1.SetFocus;
end;
procedure TFini_type_region.CloseButtonClick(Sender: TObject);
begin
Close;
end;
end.
|
{: MathsDXF<p>
DXF Maths<p>
<b>History :</b><font size=-1><ul>
<li>12/01/03 - DA - Unit creation
</ul></font>
}
unit MathsDXF;
interface
uses
System.Math,
GLVectorGeometry,
GLVectorTypes,
TypesDXF;
{: Compute the angle between two points }
function Angle(P1, P2: T3DPoint): Extended;
{: This function returns a 3-D point at an angle and distance from another point.
The given point is rotated by the angle specified in radians, then moved the
specified distance from the point. }
function Polar(Point: T3DPoint; Angle, Distance: Single): T3DPoint;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Angle
//
{: @return The angle between two points in degrees
@param P1 The first point
@param P2 the Second point }
function Angle(P1, P2: T3DPoint): Extended;
var
Delta: T3DPoint;
begin
Delta.X := P2.X - P1.X;
Delta.Y := P2.Y - P1.Y;
if (Delta.X = 0) then begin
if ( P2.Y < P1.Y) then Result :=270.0 else Result := 90.0;
Exit;
end;
if (Delta.Y = 0) then begin
if (P2.X < P1.X) then Result := 180.0 else Result :=0.0;
Exit;
end;
Result := RadToDeg(ArcTan(Delta.Y / Delta.X));
if (Result <0) then Result := - Result;
if (P2.X>P1.X) and (P2.Y>P1.Y) then Result := 0.0 + Result; // 1. Quadrant
if (P2.X<P1.X) and (P2.Y>P1.Y) then Result := 180.0 - Result; // 2. Quadrant
if (P2.X<P1.X) and (P2.Y<P1.Y) then Result := 180.0 + Result; // 3. Quadrant
if (P2.X>P1.X) and (P2.Y<P1.Y) then Result := 360.0 - Result; // 4. Quadrant
end;
// Polar
//
{: @return The new point
@param Point the pole
@param Angle Angle from the pole and the new point
@param Distance Distance from the pole and the new point }
function Polar(Point: T3DPoint; Angle, Distance: Single): T3DPoint;
var
ResultPoint: TAffineVector;
begin
// move from the distance
ResultPoint := AffineVectorMake(Distance, 0, 0);
// rotate the point by the angle
ResultPoint := VectorRotateAroundZ(ResultPoint, -Angle);
// translate to the reference point
AddVector(ResultPoint, AffineVectorMake(Point.X, Point.Y, Point.Z));
Result.X := ResultPoint.X;
Result.Y := ResultPoint.Y;
Result.Z := ResultPoint.Z;
end;
end.
|
unit Ils.Redis.Subscriber;
interface
uses
Redis.Client, System.Classes, Ils.Redis.Conf, SysUtils, Ils.Logger;
type
TArrayOfString = array of string;
TOnRedisSubscribeMessage = procedure (const AChan, AMessage: string) of object;
TRedisSubscriber = class(TThread)
private
FRCli: TRedisClient;
FChan, FMessage: string;
FHost: string;
FPort: Integer;
FSSL: Boolean;
FPassword: string;
FSubscribeChans: TArrayOfString;
FOnMessage: TOnRedisSubscribeMessage;
FOnLog: TLogFunction;
function OnTimeOut: boolean;
procedure OnRedisMessage(AChan, AMessage: string);
procedure DoMessage;
function TryConnect: Boolean;
protected
procedure Execute; override;
procedure ToLog(const AMessage: string);
public
procedure Start;
property OnMessage: TOnRedisSubscribeMessage read FOnMessage write FOnMessage;
constructor Create(const AChans: TArrayOfString; const AConf: TRedisConf; const AOnMessage: TOnRedisSubscribeMessage; const AOnLog: TLogFunction = nil; const APaused: Boolean = False);
destructor Destroy; override;
end;
implementation
{ TRedisSubscribe }
constructor TRedisSubscriber.Create(const AChans: TArrayOfString; const AConf: TRedisConf; const AOnMessage: TOnRedisSubscribeMessage; const AOnLog: TLogFunction = nil; const APaused: Boolean = False);
begin
inherited Create(True);
FOnMessage := AOnMessage;
FOnLog := AOnLog;
FSubscribeChans := AChans;
FreeOnTerminate := True;
FHost := AConf.Host;
FPort := AConf.Port;
FSSL := AConf.SSL;
FPassword := AConf.Password;
TryConnect;
Suspended := APaused;
end;
destructor TRedisSubscriber.Destroy;
begin
FRCli.Free;
end;
function TRedisSubscriber.TryConnect: Boolean;
begin
FRCli := TRedisClient.Create(FHost, FPort, FSSL);
try
FRCli.Connect;
if FPassword <> '' then
FRCli.AUTH(FPassword);
Result := True;
except
FreeAndNil(FRCli);
raise;
end;
end;
procedure TRedisSubscriber.Execute;
begin
while not Terminated do
try
if Assigned(FRCli) or TryConnect then
FRCli.SUBSCRIBE(FSubscribeChans, OnRedisMessage, OnTimeOut)
except
on E: Exception do begin
ToLog('Error on redis subscribe: ' + E.ClassName + ':' + E.Message);
FreeAndNil(FRCli);
Sleep(2500);
end;
end;
end;
procedure TRedisSubscriber.DoMessage;
begin
if Assigned(FOnMessage) then
try
FOnMessage(FChan, FMessage);
except
//TODO:!!!
end;
end;
procedure TRedisSubscriber.ToLog(const AMessage: string);
begin
if Assigned(FOnLog) then
FOnLog(AMessage);
end;
procedure TRedisSubscriber.OnRedisMessage(AChan, AMessage: string);
begin
FChan := AChan;
FMessage := AMessage;
Synchronize(Self, DoMessage);
end;
function TRedisSubscriber.OnTimeOut: boolean;
begin
Result := not Terminated;
end;
procedure TRedisSubscriber.Start;
begin
Suspended := False;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171013
////////////////////////////////////////////////////////////////////////////////
unit android.icu.text.RuleBasedCollator;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.icu.text.CollationElementIterator,
java.text.CharacterIterator,
android.icu.text.UCharacterIterator,
android.icu.text.Collator,
android.icu.text.UnicodeSet,
android.icu.text.CollationKey,
android.icu.util.VersionInfo;
type
JRuleBasedCollator = interface;
JRuleBasedCollatorClass = interface(JObjectClass)
['{FFAEDD83-0BC4-42A8-B3CD-B3CBB1706796}']
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function cloneAsThawed : JRuleBasedCollator; cdecl; // ()Landroid/icu/text/RuleBasedCollator; A: $1
function compare(source : JString; target : JString) : Integer; cdecl; // (Ljava/lang/String;Ljava/lang/String;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function freeze : JCollator; cdecl; // ()Landroid/icu/text/Collator; A: $1
function getCollationElementIterator(source : JCharacterIterator) : JCollationElementIterator; cdecl; overload;// (Ljava/text/CharacterIterator;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationElementIterator(source : JString) : JCollationElementIterator; cdecl; overload;// (Ljava/lang/String;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationElementIterator(source : JUCharacterIterator) : JCollationElementIterator; cdecl; overload;// (Landroid/icu/text/UCharacterIterator;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationKey(source : JString) : JCollationKey; cdecl; // (Ljava/lang/String;)Landroid/icu/text/CollationKey; A: $1
function getDecomposition : Integer; cdecl; // ()I A: $1
function getMaxVariable : Integer; cdecl; // ()I A: $1
function getNumericCollation : boolean; cdecl; // ()Z A: $1
function getReorderCodes : TJavaArray<Integer>; cdecl; // ()[I A: $1
function getRules : JString; cdecl; overload; // ()Ljava/lang/String; A: $1
function getRules(fullrules : boolean) : JString; cdecl; overload; // (Z)Ljava/lang/String; A: $1
function getStrength : Integer; cdecl; // ()I A: $1
function getTailoredSet : JUnicodeSet; cdecl; // ()Landroid/icu/text/UnicodeSet; A: $1
function getUCAVersion : JVersionInfo; cdecl; // ()Landroid/icu/util/VersionInfo; A: $1
function getVariableTop : Integer; cdecl; // ()I A: $1
function getVersion : JVersionInfo; cdecl; // ()Landroid/icu/util/VersionInfo; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init(rules : JString) : JRuleBasedCollator; cdecl; // (Ljava/lang/String;)V A: $1
function isAlternateHandlingShifted : boolean; cdecl; // ()Z A: $1
function isCaseLevel : boolean; cdecl; // ()Z A: $1
function isFrenchCollation : boolean; cdecl; // ()Z A: $1
function isFrozen : boolean; cdecl; // ()Z A: $1
function isLowerCaseFirst : boolean; cdecl; // ()Z A: $1
function isUpperCaseFirst : boolean; cdecl; // ()Z A: $1
function setMaxVariable(group : Integer) : JRuleBasedCollator; cdecl; // (I)Landroid/icu/text/RuleBasedCollator; A: $1
procedure getContractionsAndExpansions(contractions : JUnicodeSet; expansions : JUnicodeSet; addPrefixes : boolean) ; cdecl;// (Landroid/icu/text/UnicodeSet;Landroid/icu/text/UnicodeSet;Z)V A: $1
procedure setAlternateHandlingDefault ; cdecl; // ()V A: $1
procedure setAlternateHandlingShifted(shifted : boolean) ; cdecl; // (Z)V A: $1
procedure setCaseFirstDefault ; cdecl; // ()V A: $11
procedure setCaseLevel(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setCaseLevelDefault ; cdecl; // ()V A: $1
procedure setDecomposition(decomposition : Integer) ; cdecl; // (I)V A: $1
procedure setDecompositionDefault ; cdecl; // ()V A: $1
procedure setFrenchCollation(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setFrenchCollationDefault ; cdecl; // ()V A: $1
procedure setLowerCaseFirst(lowerfirst : boolean) ; cdecl; // (Z)V A: $1
procedure setNumericCollation(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setNumericCollationDefault ; cdecl; // ()V A: $1
procedure setReorderCodes(order : TJavaArray<Integer>) ; cdecl; // ([I)V A: $81
procedure setStrength(newStrength : Integer) ; cdecl; // (I)V A: $1
procedure setStrengthDefault ; cdecl; // ()V A: $1
procedure setUpperCaseFirst(upperfirst : boolean) ; cdecl; // (Z)V A: $1
end;
[JavaSignature('android/icu/text/RuleBasedCollator')]
JRuleBasedCollator = interface(JObject)
['{8210A628-6C2D-4970-834E-AAF6512737EB}']
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function cloneAsThawed : JRuleBasedCollator; cdecl; // ()Landroid/icu/text/RuleBasedCollator; A: $1
function compare(source : JString; target : JString) : Integer; cdecl; // (Ljava/lang/String;Ljava/lang/String;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function freeze : JCollator; cdecl; // ()Landroid/icu/text/Collator; A: $1
function getCollationElementIterator(source : JCharacterIterator) : JCollationElementIterator; cdecl; overload;// (Ljava/text/CharacterIterator;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationElementIterator(source : JString) : JCollationElementIterator; cdecl; overload;// (Ljava/lang/String;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationElementIterator(source : JUCharacterIterator) : JCollationElementIterator; cdecl; overload;// (Landroid/icu/text/UCharacterIterator;)Landroid/icu/text/CollationElementIterator; A: $1
function getCollationKey(source : JString) : JCollationKey; cdecl; // (Ljava/lang/String;)Landroid/icu/text/CollationKey; A: $1
function getDecomposition : Integer; cdecl; // ()I A: $1
function getMaxVariable : Integer; cdecl; // ()I A: $1
function getNumericCollation : boolean; cdecl; // ()Z A: $1
function getReorderCodes : TJavaArray<Integer>; cdecl; // ()[I A: $1
function getRules : JString; cdecl; overload; // ()Ljava/lang/String; A: $1
function getRules(fullrules : boolean) : JString; cdecl; overload; // (Z)Ljava/lang/String; A: $1
function getStrength : Integer; cdecl; // ()I A: $1
function getTailoredSet : JUnicodeSet; cdecl; // ()Landroid/icu/text/UnicodeSet; A: $1
function getUCAVersion : JVersionInfo; cdecl; // ()Landroid/icu/util/VersionInfo; A: $1
function getVariableTop : Integer; cdecl; // ()I A: $1
function getVersion : JVersionInfo; cdecl; // ()Landroid/icu/util/VersionInfo; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isAlternateHandlingShifted : boolean; cdecl; // ()Z A: $1
function isCaseLevel : boolean; cdecl; // ()Z A: $1
function isFrenchCollation : boolean; cdecl; // ()Z A: $1
function isFrozen : boolean; cdecl; // ()Z A: $1
function isLowerCaseFirst : boolean; cdecl; // ()Z A: $1
function isUpperCaseFirst : boolean; cdecl; // ()Z A: $1
function setMaxVariable(group : Integer) : JRuleBasedCollator; cdecl; // (I)Landroid/icu/text/RuleBasedCollator; A: $1
procedure getContractionsAndExpansions(contractions : JUnicodeSet; expansions : JUnicodeSet; addPrefixes : boolean) ; cdecl;// (Landroid/icu/text/UnicodeSet;Landroid/icu/text/UnicodeSet;Z)V A: $1
procedure setAlternateHandlingDefault ; cdecl; // ()V A: $1
procedure setAlternateHandlingShifted(shifted : boolean) ; cdecl; // (Z)V A: $1
procedure setCaseLevel(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setCaseLevelDefault ; cdecl; // ()V A: $1
procedure setDecomposition(decomposition : Integer) ; cdecl; // (I)V A: $1
procedure setDecompositionDefault ; cdecl; // ()V A: $1
procedure setFrenchCollation(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setFrenchCollationDefault ; cdecl; // ()V A: $1
procedure setLowerCaseFirst(lowerfirst : boolean) ; cdecl; // (Z)V A: $1
procedure setNumericCollation(flag : boolean) ; cdecl; // (Z)V A: $1
procedure setNumericCollationDefault ; cdecl; // ()V A: $1
procedure setStrength(newStrength : Integer) ; cdecl; // (I)V A: $1
procedure setStrengthDefault ; cdecl; // ()V A: $1
procedure setUpperCaseFirst(upperfirst : boolean) ; cdecl; // (Z)V A: $1
end;
TJRuleBasedCollator = class(TJavaGenericImport<JRuleBasedCollatorClass, JRuleBasedCollator>)
end;
implementation
end.
|
unit http;
interface
uses
Classes, blcksock, winsock, Synautil, SysUtils, fpjson, jsonparser,
variants, DB, Graphics, log, sndkey32;
type
TTCPHttpDaemon = class(TThread)
private
Sock: TTCPBlockSocket;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
{ TTCPHttpThrd }
TTCPHttpThrd = class(TThread)
private
Sock: TTCPBlockSocket;
public
Headers: TStringList;
InputData, OutputData: TMemoryStream;
constructor Create(hsock: tSocket);
destructor Destroy; override;
procedure Execute; override;
procedure UpdateCalls;
function ProcessHttpRequest(Request, URI, RequestData: string): integer;
function ProcessRequest(ClientLocation, RequestFunction: string;
RequestParams: array of variant; RequestID: string): string;
procedure Log(msg: string);
end;
var
Json: TJSONObject;
implementation
uses libutil, main;
{ TTCPHttpDaemon }
constructor TTCPHttpDaemon.Create;
begin
inherited Create(False);
sock := TTCPBlockSocket.Create;
FreeOnTerminate := True;
Priority := tpNormal;
end;
destructor TTCPHttpDaemon.Destroy;
begin
Sock.Free;
inherited Destroy;
end;
procedure TTCPHttpDaemon.Execute;
var
ClientSock: TSocket;
begin
with sock do
begin
CreateSocket;
setLinger(True, 10);
bind('0.0.0.0', '3088');
listen;
repeat
if terminated then
break;
if canread(500) then
begin
ClientSock := accept;
if lastError = 0 then
TTCPHttpThrd.Create(ClientSock);
end;
until False;
end;
end;
{ TTCPHttpThrd }
constructor TTCPHttpThrd.Create(Hsock: TSocket);
begin
inherited Create(False);
sock := TTCPBlockSocket.Create;
Headers := TStringList.Create;
InputData := TMemoryStream.Create;
OutputData := TMemoryStream.Create;
Sock.socket := HSock;
FreeOnTerminate := True;
Priority := tpNormal;
end;
destructor TTCPHttpThrd.Destroy;
begin
Sock.Free;
Headers.Free;
InputData.Free;
OutputData.Free;
inherited Destroy;
end;
procedure TTCPHttpThrd.Execute;
var
timeout: integer;
s: string;
method, uri, protocol: string;
size: integer;
x, n: integer;
resultcode: integer;
slData: TStringList;
begin
timeout := 12000;
//read request line
s := sock.RecvString(timeout);
if sock.lasterror <> 0 then
Exit;
if s = '' then
Exit;
method := fetch(s, ' ');
if (s = '') or (method = '') then
Exit;
uri := fetch(s, ' ');
if uri = '' then
Exit;
protocol := fetch(s, ' ');
headers.Clear;
size := -1;
//read request headers
if protocol <> '' then
begin
if pos('HTTP/', protocol) <> 1 then
Exit;
repeat
s := sock.RecvString(Timeout);
if sock.lasterror <> 0 then
Exit;
if s <> '' then
Headers.add(s);
if Pos('CONTENT-LENGTH:', Uppercase(s)) = 1 then
Size := StrToIntDef(SeparateRight(s, ' '), -1);
until s = '';
end;
//recv document...
InputData.Clear;
if size >= 0 then
begin
InputData.SetSize(Size);
x := Sock.RecvBufferEx(InputData.Memory, Size, Timeout);
InputData.SetSize(x);
if sock.lasterror <> 0 then
Exit;
end;
InputData.Seek(0, soFromBeginning);
try
slData := TStringList.Create;
slData.Clear;
slData.LoadFromStream(InputData);
OutputData.Clear;
ResultCode := ProcessHttpRequest(method, uri, slData.Text);
finally
FreeAndNil(slData);
end;
sock.SendString('HTTP/1.0 ' + IntToStr(ResultCode) + CRLF);
if protocol <> '' then
begin
headers.Add('Content-length: ' + IntToStr(OutputData.Size));
headers.Add('Connection: close');
headers.Add('Date: ' + Rfc822DateTime(now));
headers.Add('Server: BCP2PC');
headers.Add('');
for n := 0 to headers.Count - 1 do
sock.sendstring(headers[n] + CRLF);
end;
if sock.lasterror <> 0 then
Exit;
Sock.SendBuffer(OutputData.Memory, OutputData.Size);
end;
procedure TTCPHttpThrd.UpdateCalls;
begin
Form1.label2.Caption := IntToStr(StrToInt(Form1.label2.Caption) + 1);
end;
function TTCPHttpThrd.ProcessHttpRequest(Request, URI, RequestData: string): integer;
var
l: TStringList;
I, vCount: integer;
ReqObject: TJSONObject;
Parser: TJSONParser;
ReqContent, ReqFunction, ReqID, sParam: string;
ArrParams: array of variant;
OutputDataString, ResContent: string;
CheckFileName, ContentType: string;
begin
Result := 504;
if request = 'GET' then
begin
headers.Clear;
CheckFileName := UriToFileName(uri);
ContentType := GetContentType(CheckFileName);
headers.Add(Format('Content-type: %s', [ContentType]));
if IsImage(CheckFileName) or IsFileDownload(CheckFileName) then
begin
if FileExists(CheckFileName) then
begin
try
OutputData.LoadFromFile(CheckFileName);
finally
Result := 200;
end;
end
else
Result := GetPageResult(404, OutputData);
end
else
begin
if FileExists(CheckFileName) then
begin
l := TStringList.Create;
try
l.LoadFromFile(CheckFileName);
l.SaveToStream(OutputData);
finally
l.Free;
end;
Result := 200;
end
else
begin
headers.Clear;
headers.Add('Content-type: text/html');
Result := GetPageResult(404, OutputData);
end;
end;
end
else
if request = 'POST' then
begin
try
ReqContent := RequestData;
if trim(ReqContent) <> '' then
begin
Parser := TJSONParser.Create(ReqContent);
ReqObject := Parser.Parse as TJSONObject;
ReqFunction := ReqObject.Elements['method'].Value;
ReqID := ReqObject.Elements['id'].AsJSON;
if Parser <> nil then
begin
vCount := ReqObject.Elements['params'].Count;
ArrParams := VarArrayCreate([1, vCount], vtVariant);
for i := 0 to vCount - 1 do
begin
sParam := ReqObject.Elements['params'].Items[i].AsJSON;
ArrParams[i] := sParam;
end;
ResContent := ProcessRequest(Sock.GetRemoteSinIP, ReqFunction,
ArrParams, ReqID);
OutputDataString := format('{"jsonrpc": "2.0", "result": %s, "id": %s}',
[ResContent, ReqID]);
end
else
begin
OutputDataString :=
'{"jsonrpc": "2.0", "result": "Request Invalid Content", "id": 1}';
end;
end
else
begin
OutputDataString := '{"jsonrpc": "2.0", "result": "Invalid command", "id": 1}';
end;
headers.Clear;
headers.Add('application/json');
l := TStringList.Create;
try
l.Text := OutputDataString;
l.SaveToStream(OutputData);
finally
l.Free;
end;
Result := 200;
finally
if trim(ReqContent) <> '' then
begin
FreeAndNil(parser);
FreeAndNil(ReqObject);
end;
end;
end;
end;
function TTCPHttpThrd.ProcessRequest(ClientLocation, RequestFunction: string;
RequestParams: array of variant; RequestID: string): string;
var
params: string;
sResult: string;
begin
params := vartostr(RequestParams[0]);
if RequestFunction = 'READBARCODE' then
begin
SendKeys(PChar(stringreplace(params,'"','',[rfReplaceAll])),true);
//SendKeys(#13#10,true); //send return key
Log(stringreplace(params,'"','',[rfReplaceAll]));
sResult := '"OK"';
end
else
sResult := '"NOK"';
Result := sResult;
Synchronize(UpdateCalls);
end;
procedure TTCPHttpThrd.Log(msg: string);
begin
if frmLog <> nil then
frmLog.memLog.Lines.Add(msg);
end;
end.
|
unit Serialialize.JSON;
interface
uses
{$IF VER330}
System.JSON,
{$ELSE}
Data.DBXJSON,
{$ENDIF}
Serialialize.JSON.Interfaces;
type
TJsonSerialize<T: Class> = class(TInterfacedObject, IJSON<T>)
private
FArrayJson: TJSONArray;
public
constructor Create;
destructor Destroy; override;
class function New: IJSON<T>;
function Add(AJsonObjct: String): IJSON<T>; overload;
function Add(AJsonObjct: T): IJSON<T>; overload;
function JsonArray: String;
end;
implementation
uses
{$IF VER330}
Rest.JSON.types,
{$ENDIF}
Rest.JSON;
{ TJsonSerialize }
function TJsonSerialize<T>.Add(AJsonObjct: T): IJSON<T>;
begin
Result := Self;
FArrayJson.Add(TJson.ObjectToJsonObject(AJsonObjct
{$IFDEF VER330}, [joDateFormatParse]{$ENDIF}));
end;
function TJsonSerialize<T>.Add(AJsonObjct: String): IJSON<T>;
begin
Result := Self;
FArrayJson.Add(AJsonObjct);
end;
constructor TJsonSerialize<T>.Create;
begin
FArrayJson := TJSONArray.Create;
end;
destructor TJsonSerialize<T>.Destroy;
begin
FArrayJson.Free;
inherited;
end;
function TJsonSerialize<T>.JsonArray: String;
begin
Result := FArrayJson.ToString;
end;
class function TJsonSerialize<T>.New: IJSON<T>;
begin
Result := Self.Create;
end;
end.
|
unit fre_base_parser;
{$mode objfpc}{$H+}
{$codepage UTF8}
{$modeswitch nestedprocvars}
{$interfaces corba}
interface
uses
Classes, SysUtils,FRE_DB_INTERFACE,FOS_TOOL_INTERFACES,FRE_PROCESS,FRE_SYSTEM;
type
{ TFOS_PARSER_PROC }
TFOS_PARSER_PROC=class
private
FShellCmd : string;
FProcess : TFRE_PROCESS_NEW;
FCurrentDirectory : string;
FIsOnceMode : boolean;
protected
helpline : TStringlist;
FData : IFRE_DB_Object;
FLine : TStringlist;
FLines : TStringlist;
FLock : IFOS_LOCK;
FEnabled : Boolean;
//procedure MyOutStreamCallBack (const stream:TStream); virtual;
//procedure MyErrStreamCallBack (const stream:TStream); virtual;
procedure MyInputCallback (out input : string ; var close_input : boolean); virtual;
procedure MyOutputCallback (const output : string ; var close_output : boolean); virtual;
procedure MyErrorCallback (const output : string ; var close_error : boolean); virtual;
procedure MySetup;virtual;
procedure MyFinalize;virtual;
procedure MyParseOnOnceFinished; virtual;
public
function IsRunning: boolean;
function ExitStatus: integer;
function IsOnceMode : boolean;
constructor Create (const cmd : string);
procedure SetShellCommand(const cmd: string);
procedure SetCurrentDirectory(const dir:string);
destructor Destroy;override;
procedure Enable;
procedure Disable;
function ParseOnce : IFRE_DB_Object;
function Get_Data_Object : IFRE_DB_Object;
end;
implementation
{ TFOS_PARSER_PROC }
//procedure TFOS_PARSER_PROC.MyOutStreamCallBack(const stream: TStream);
//begin
//
//end;
//
//procedure TFOS_PARSER_PROC.MyErrStreamCallBack(const stream: TStream);
//var st : TStringStream;
// sl : TStringlist;
// i : integer;
//begin
// stream.Position:=0;
// st := TStringStream.Create('');
// try
// if stream.Size>0 then
// begin
// st.CopyFrom(stream,stream.Size);
// stream.Size:=0;
// writeln('ERRSTREAMCALLBACK: ',ClassName);
// writeln('------------------------------');
// writeln(st.DataString);
// writeln('------------------------------');
// end;
// finally
// st.Free;
// end;
//end;
procedure TFOS_PARSER_PROC.MyInputCallback(out input: string; var close_input: boolean);
begin
close_input := true;
end;
procedure TFOS_PARSER_PROC.MyOutputCallback(const output: string; var close_output: boolean);
begin
close_output := true;
end;
procedure TFOS_PARSER_PROC.MyErrorCallback(const output: string; var close_error: boolean);
begin
close_error := true;
end;
procedure TFOS_PARSER_PROC.MySetup;
begin
end;
procedure TFOS_PARSER_PROC.MyFinalize;
begin
end;
procedure TFOS_PARSER_PROC.MyParseOnOnceFinished;
begin
end;
function TFOS_PARSER_PROC.IsOnceMode: boolean;
begin
result := FIsOnceMode;
end;
constructor TFOS_PARSER_PROC.Create(const cmd: string);
begin
FLine := TStringList.Create;
FLines := TStringList.Create;
FLines.TextLineBreakStyle := tlbsLF;
FLines.StrictDelimiter:=true;
FLines.Delimiter:=#10;
FLine.StrictDelimiter:=true;
FLine.Delimiter:=',';
FIsOnceMode := false;
GFRE_TF.Get_Lock(FLock);
FData := GFRE_DBI.NewObject;
FShellCmd := cmd;
helpline := TStringlist.Create;
MySetup;
end;
procedure TFOS_PARSER_PROC.SetShellCommand(const cmd: string);
begin
FShellCmd:=cmd;
end;
procedure TFOS_PARSER_PROC.SetCurrentDirectory(const dir: string);
begin
FCurrentDirectory:=dir;
end;
destructor TFOS_PARSER_PROC.Destroy;
begin
Disable;
helpline.free;
MyFinalize;
FLine.Free;
FLines.Free;
if assigned(FData) then
FData.Finalize;
FLock.Finalize;
end;
procedure TFOS_PARSER_PROC.Enable;
var error:string;
begin
FProcess := TFRE_PROCESS_NEW.Create;
if (cFRE_REMOTE_USER<>'') and not FProcess.ConfigureRemote_SSH_Mode(cFRE_REMOTE_USER,cFRE_REMOTE_HOST,cFRE_REMOTE_SSL_ID_FILE,error,cFRE_REMOTE_SSL_PORT) then
raise EFRE_DB_Exception.Create(edb_ERROR,'PARSERPROC ENABLE: '+error);
FProcess.NewExecutePipedSpawnAsync(FShellCmd,@MyInputCallback,@MyOutputCallback,@MyErrorCallback,false);
FEnabled := true;
end;
procedure TFOS_PARSER_PROC.Disable;
begin
if FEnabled then
begin
FEnabled:=false;
FProcess.TerminateAndWaitFor;
FProcess.Free;
end;
end;
function TFOS_PARSER_PROC.ParseOnce: IFRE_DB_Object;
var error:string;
begin
FIsOnceMode := True;
FProcess := TFRE_PROCESS_NEW.Create;
try
if (cFRE_REMOTE_USER<>'') and not FProcess.ConfigureRemote_SSH_Mode(cFRE_REMOTE_USER,cFRE_REMOTE_HOST,cFRE_REMOTE_SSL_ID_FILE,error,cFRE_REMOTE_SSL_PORT) then
raise EFRE_DB_Exception.Create(edb_ERROR,'PARSERPROC ENABLE: '+error);
FProcess.NewExecutePipedSpawnAsync(FShellCmd,@MyInputCallback,@MyOutputCallback,@MyErrorCallback,true);
MyParseOnOnceFinished;
result := FData;
FData := nil;
finally
FreeAndNil(FProcess);
end;
end;
function TFOS_PARSER_PROC.Get_Data_Object: IFRE_DB_Object;
begin
FLock.Acquire;
try
result := Fdata.CloneToNewObject();
finally
FLock.Release;
end;
end;
function TFOS_PARSER_PROC.IsRunning: boolean;
begin
if Assigned(FProcess) then
result := FProcess.IsRunning
else
result := false;
end;
function TFOS_PARSER_PROC.ExitStatus: integer;
begin
if Assigned(FProcess) then
begin
result := FProcess.ExistStatus;
end
else
begin
result := -1;
end;
end;
end.
|
{
MODEL STATUS Not Working.
DOC STATUS Not Implemented.
CODEGEN STATUS Not Implemented.
}
unit utstUnitQuailfiedName;
{$mode objfpc}{$H+}
{
This test class poses a few questions.
Do we keep &| store &| show the qualified name?
The qualified name may be required for correct compilation. e.g.
In Laz-Model we have a class called TOperation.
There is also the following procedure (which may be removed as it is part
of the old mouse handling) which uses
TOperation = (opInsert, opRemove); from the fpc RTL.
procedure TRtfdBox.Notification(AComponent: TComponent; Operation: Classes.TOperation);
Here one is a Class and one is a DataType. The DataType HAS to be qualified
for proper compilation.
However there is also the usage in uTreeViewIntegrator where TClass is
fully qualified throughout the unit, without any ryhme or reason. ( although
it is probably just a case of having had to qualify in much earlier versions
of the codebase.)
Probably the best idea is to add IsQualified to TClassifiers in the model,
but keep as simple full name if thrown in the unknown bucket without the
IsQualified set
So In the above examples uModel.TClass would be represented as a
classifer with name TClass, with is Qualified, while Classes.TOperation
would be thrown in the unknown datatype bucket as a classifier with name
Classes.TOperation
If at some later date we get round to parsing the Classes unit, then at this
point it will become shown as TOperation::IsQualified=True.
}
interface
uses
Classes, SysUtils;
type
TQNClass1 = class(TObject)
public
name: string;
end;
TQNClass2 = class(TObject)
private
FClass1: utstUnitQualifiedName.TQNClass1;
FOTher: Classes.TOperation;
public
end;
implementation
end.
|
unit htTag;
interface
uses
SysUtils, Classes, Contnrs,
htAttributeList, htStyleList;
type
ThtTag = class;
//
ThtTagList = class(TObjectList)
private
function GetTags(inIndex: Integer): ThtTag;
procedure SetTags(inIndex: Integer; const Value: ThtTag);
public
property Tags[inIndex: Integer]: ThtTag read GetTags write SetTags;
end;
//
ThtTagFlag = ( tfMono, tfHideIfEmpty, tfLineBreak );
ThtTagFlags = set of ThtTagFlag;
//
ThtTag = class(ThtTagList)
private
FContent: TStringList;
FElement: string;
FAttributes: ThtAttributeList;
FStyles: ThtStyleList;
FFlags: ThtTagFlags;
FExtraAttributes: string;
protected
function GetCloseTag: string;
function GetContent: TStrings;
function GetHtml: string;
function GetOpenTag: string;
procedure SetAttributes(const Value: ThtAttributeList);
procedure SetContent(const Value: TStrings);
procedure SetElement(const Value: string);
procedure SetExtraAttributes(const Value: string);
procedure SetFlags(const Value: ThtTagFlags);
procedure SetStyles(const Value: ThtStyleList);
public
constructor Create(const inElement: string = ''; inFlags: ThtTagFlags = []);
destructor Destroy; override;
function Add: ThtTag; overload;
function HasContent: Boolean;
function HasTags: Boolean;
procedure Add(const inString: string); overload;
procedure Add(inTag: ThtTag); overload;
property Attributes: ThtAttributeList read FAttributes write SetAttributes;
property Element: string read FElement write SetElement;
property ExtraAttributes: string read FExtraAttributes write SetExtraAttributes;
property Flags: ThtTagFlags read FFlags write SetFlags;
property Content: TStrings read GetContent write SetContent;
property Styles: ThtStyleList read FStyles write SetStyles;
property Html: string read GetHtml;
end;
implementation
{ ThtTagList }
function ThtTagList.GetTags(inIndex: Integer): ThtTag;
begin
Result := ThtTag(Items[inIndex]);
end;
procedure ThtTagList.SetTags(inIndex: Integer; const Value: ThtTag);
begin
Items[inIndex] := Value;
end;
{ ThtTag }
procedure ThtTag.Add(const inString: string);
begin
Content.Add(inString);
end;
procedure ThtTag.Add(inTag: ThtTag);
begin
inherited Add(inTag);
end;
function ThtTag.Add: ThtTag;
begin
Result := ThtTag.Create;
inherited Add(Result);
end;
constructor ThtTag.Create(const inElement: string = '';
inFlags: ThtTagFlags = []);
begin
FFlags := inFlags;
FAttributes := ThtAttributeList.Create;
FStyles := ThtStyleList.Create;
Element := inElement;
end;
destructor ThtTag.Destroy;
begin
FContent.Free;
FStyles.Free;
FAttributes.Free;
inherited;
end;
function ThtTag.GetContent: TStrings;
begin
if FContent = nil then
FContent := TStringList.Create;
Result := FContent;
end;
function ThtTag.HasContent: Boolean;
begin
Result := (FContent <> nil) and (Content.Count > 0);
end;
function ThtTag.HasTags: Boolean;
begin
Result := Count > 0;
end;
function ThtTag.GetOpenTag: string;
begin
if Element = '' then
Result := ''
else begin
Result := '<' + Element + Attributes.HtmlAttributes;
if ExtraAttributes <> '' then
Result := Result + ' ' + ExtraAttributes;
if tfMono in Flags then
Result := Result + ' />'
else
Result := Result + '>';
end;
end;
function ThtTag.GetCloseTag: string;
begin
if (Element = '') or (tfMono in Flags) then
Result := ''
else
Result := '</' + Element + '>';
end;
function ThtTag.GetHtml: string;
var
i: Integer;
begin
if (tfHideIfEmpty in Flags) and not HasContent and not HasTags then
Result := ''
else begin
Result := GetOpenTag;
for i := 0 to Pred(Count) do
Result := Result + Tags[i].Html;
if HasContent then
Result := Result + Content.Text;
Result := Result + GetCloseTag;
end;
if (tfLineBreak in Flags) then
Result := Result + #13;
end;
procedure ThtTag.SetAttributes(const Value: ThtAttributeList);
begin
FAttributes.Assign(Value);
end;
procedure ThtTag.SetContent(const Value: TStrings);
begin
FContent.Assign(Value);
end;
procedure ThtTag.SetElement(const Value: string);
begin
FElement := LowerCase(Value);
if (Element = 'img') or (Element = 'input') then
Include(FFlags, tfMono);
end;
procedure ThtTag.SetFlags(const Value: ThtTagFlags);
begin
FFlags := Value;
end;
procedure ThtTag.SetStyles(const Value: ThtStyleList);
begin
FStyles.Assign(Value);
end;
procedure ThtTag.SetExtraAttributes(const Value: string);
begin
FExtraAttributes := Value;
end;
end.
|
unit MainNdsProcentEdit;
{*******************************************************************************
* MainNdsProcentEdit *
* *
* Справочник процента НДС, добавление, редактирование *
* Copyright © 2004, Бурмистрова Е. *
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxMaskEdit, cxControls, cxContainer,
cxEdit, cxTextEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxButtons,
ExtCtrls, DB, FIBDataSet, pFIBDataSet, MainNdsProcent,
FIBQuery, pFIBQuery, pFIBStoredProc;
resourcestring
errTipDogNotDBeg = 'Введите дату початку!';
errTipDogNotDEnd = 'Введите дату закінчення!';
errTipDogNotDEnd_DBeg = 'Некоректно задан період!';
errTipDogNotNDS = 'Введите відсоток ПВД!';
type
TfrmNdsProcEdit = class(TForm)
Panel1: TPanel;
GroupBox1: TGroupBox;
cxButton_ok: TcxButton;
cxButton_cl: TcxButton;
cxDateEdit_d_beg: TcxDateEdit;
cxDateEdit_d_end: TcxDateEdit;
cxMaskEdit_nds_proc: TcxMaskEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
pFIBDataSet_nds_proc_edit: TpFIBDataSet;
pFIBStoredProc_nds_edit: TpFIBStoredProc;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure cxButton_clClick(Sender: TObject);
procedure cxButton_okClick(Sender: TObject);
private
{ Private declarations }
public
constructor Create(Aowner: TComponent; id_nds_prosent :Variant; Flag :Boolean);overload;
{ Public declarations }
end;
var
frmNdsProcEdit: TfrmNdsProcEdit;
Flag_edit: Boolean;
id_nds: Variant;
implementation
{$R *.dfm}
constructor TfrmNdsProcEdit.Create(Aowner: TComponent; id_nds_prosent :Variant; Flag :Boolean);
begin
if Flag = true then
begin
inherited Create (Aowner);
pFIBDataSet_nds_proc_edit.Database := TfrmNdsProcent(Self.Owner).pFIBDatabase;
pFIBDataSet_nds_proc_edit.Transaction := TfrmNdsProcent(Self.Owner).pFIBTransactionRead;
pFIBDataSet_nds_proc_edit.Active := false;
pFIBDataSet_nds_proc_edit.ParamByName('param_nds_proc').Value := id_nds_prosent;
pFIBDataSet_nds_proc_edit.Active := true;
cxDateEdit_d_beg.Date := pFIBDataSet_nds_proc_edit.FieldByName('D_BEG').AsDateTime;
cxDateEdit_d_end.Date := pFIBDataSet_nds_proc_edit.FieldByName('D_END').AsDateTime;
cxMaskEdit_nds_proc.Text := pFIBDataSet_nds_proc_edit.FieldByName('NDS_PROCENT').AsString;
id_nds := pFIBDataSet_nds_proc_edit.FieldByName('ID_NDS_PROCENT').AsVariant;
Flag_edit := Flag;
Caption := 'Редагування';
end
else
begin
inherited Create (Aowner);
Flag_edit := Flag;
end;
end;
procedure TfrmNdsProcEdit.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmNdsProcEdit.FormCreate(Sender: TObject);
begin
//Интерфейс
{ Label1.Caption:=Resources_unit.DT_DATE_BEG;
Label2.Caption:=Resources_unit.DT_DATE_END;
Label3.Caption:=Resources_unit.DT_NDS_PROC;
cxButton_ok.Caption:=Resources_unit.PUB_BUTTON_OK_CONST;
cxButton_cl.Caption:=Resources_unit.PUB_BUTTON_CANCEL_CONST;}
end;
procedure TfrmNdsProcEdit.cxButton_clClick(Sender: TObject);
begin
Close;
end;
procedure TfrmNdsProcEdit.cxButton_okClick(Sender: TObject);
begin
// проверка на заполнение даты
if Trim(cxDateEdit_d_beg.Text) = '' then
begin
MessageDlg(errTipDogNotDBeg, mtError, [mbOk], 0);
cxDateEdit_d_beg.SetFocus;
Exit;
end;
// проверка на заполнение даты
if Trim(cxDateEdit_d_end.Text) = '' then
begin
MessageDlg(errTipDogNotDEnd, mtError, [mbOk], 0);
cxDateEdit_d_end.SetFocus;
Exit;
end;
// проверка на корректность даты
if cxDateEdit_d_beg.Date > cxDateEdit_d_end.Date then
begin
MessageDlg(errTipDogNotDEnd_DBeg, mtError, [mbOk], 0);
cxDateEdit_d_beg.SetFocus;
Exit;
end;
// проверка на NDS
if Trim(cxMaskEdit_nds_proc.Text) = '' then
begin
MessageDlg(errTipDogNotNDS, mtError, [mbOk], 0);
cxMaskEdit_nds_proc.SetFocus;
Exit;
end;
if Flag_edit=false then
begin
pFIBStoredProc_nds_edit.Database := TfrmNdsProcent(Self.Owner).pFIBDatabase;
pFIBStoredProc_nds_edit.Transaction := TfrmNdsProcent(Self.Owner).pFIBTransactionWrite;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.DefaultDatabase := TfrmNdsProcent(Self.Owner).pFIBDatabase;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.StartTransaction;
pFIBStoredProc_nds_edit.StoredProcName := 'PUB_NDS_PROCENT_INSERT';
pFIBStoredProc_nds_edit.Prepare;
pFIBStoredProc_nds_edit.ParamByName('D_D_BEG').Value := cxDateEdit_d_beg.Text;
pFIBStoredProc_nds_edit.ParamByName('D_D_END').Value := cxDateEdit_d_end.Text;
pFIBStoredProc_nds_edit.ParamByName('D_NDS_PROCENT').Value := cxMaskEdit_nds_proc.Text;
try
pFIBStoredProc_nds_edit.ExecProc;
except
begin
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.Rollback;
Exit;
end;
end;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.Commit;
Close;
end
else
begin
pFIBStoredProc_nds_edit.Database := TfrmNdsProcent(Self.Owner).pFIBDatabase;
pFIBStoredProc_nds_edit.Transaction := TfrmNdsProcent(Self.Owner).pFIBTransactionWrite;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.DefaultDatabase := TfrmNdsProcent(Self.Owner).pFIBDatabase;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.StartTransaction;
pFIBStoredProc_nds_edit.StoredProcName := 'PUB_NDS_PROCENT_UPDATE';
pFIBStoredProc_nds_edit.ParamByName('D_ID_NDS_PROCENT').Value := id_nds;
pFIBStoredProc_nds_edit.ParamByName('D_D_BEG').Value := cxDateEdit_d_beg.Text;
pFIBStoredProc_nds_edit.ParamByName('D_D_END').Value := cxDateEdit_d_end.Text;
pFIBStoredProc_nds_edit.ParamByName('D_NDS_PROCENT').Value := cxMaskEdit_nds_proc.Text;
try
pFIBStoredProc_nds_edit.ExecProc;
except
begin
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.Rollback;
Exit;
end;
end;
TfrmNdsProcent(Self.Owner).pFIBTransactionWrite.Commit;
Close;
end;
end;
end.
|
//****************************************************************************//
// Ведение правил удержания налогов //
// Форма для изменения периода функционирования //
// Серов А.Н. июль 2005 года //
//****************************************************************************//
unit TaxesTerms_Zarplata;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxSpinEdit, cxDropDownEdit, cxLabel, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, ExtCtrls, cxControls, cxGroupBox, ZProc,
cxLookAndFeelPainters, StdCtrls, cxButtons, ZTypes, IBase,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, Dates,
Unit_ZGlobal_Consts, ZMessages;
type TZTaxesTermsParameters = record
ID_TAX_NET : integer;
ID_TAX_NET_PERIOD : integer;
KodSetup1: Integer;
KodSetup2: Integer;
ControlFormStyle:TZControlFormStyle;
end;
type
TFZTaxesTerms = class(TForm)
Box: TcxGroupBox;
PeriodBegLabel: TcxLabel;
MonthesListBeg: TcxComboBox;
YearSpinEditBeg: TcxSpinEdit;
PeriodEndLabel: TcxLabel;
MonthesListEnd: TcxComboBox;
YearSpinEditEnd: TcxSpinEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
WriteTransaction: TpFIBTransaction;
StoredProc: TpFIBStoredProc;
DB: TpFIBDatabase;
procedure CancelBtnClick(Sender: TObject);
procedure YesBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure YearSpinEditBegKeyPress(Sender: TObject; var Key: Char);
procedure YearSpinEditEndKeyPress(Sender: TObject; var Key: Char);
procedure YearSpinEditBegKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure YearSpinEditEndKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
PParameter:TZTaxesTermsParameters;
PDB_Handle:TISC_DB_HANDLE;
PLanguageIndex:byte;
public
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;AParameter:TZTaxesTermsParameters); reintroduce;
property Parameter:TZTaxesTermsParameters read PParameter;
end;
function View_FZTaxesTerms(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;AParameter:TZTaxesTermsParameters):variant;stdcall;export;
implementation
uses StrUtils;
{$R *.dfm}
//****************************************************************************//
// Функция редактирования //
//****************************************************************************//
function View_FZTaxesTerms(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;AParameter:TZTaxesTermsParameters):variant;stdcall;
var ViewForm:TFZTaxesTerms;
Res:Variant;
begin
ViewForm:=TFZTaxesTerms.Create(AOwner,DB_Handle,AParameter);
if ViewForm.ModalResult=mrNone then
ViewForm.ShowModal;
if AParameter.ControlFormStyle=zcfsInsert then
begin
Res:=VarArrayCreate([0,1],varVariant);
Res[1]:=ViewForm.Parameter.ID_TAX_NET_PERIOD;
end
else
Res:=VarArrayCreate([0,0],varVariant);
Res[0]:=ViewForm.ModalResult;
ViewForm.Free;
View_FZTaxesTerms:=Res;
end;
constructor TFZTaxesTerms.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;AParameter:TZTaxesTermsParameters);
begin
inherited Create(AOwner);
PParameter:=AParameter;
PLanguageIndex := LanguageIndex;
//******************************************************************************
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
PeriodBegLabel.Caption := GridClBegPeriod_Caption[PLanguageIndex];
PeriodEndLabel.Caption := GridClEndPeriod_Caption[PLanguageIndex];
MonthesListBeg.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
MonthesListEnd.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
MonthesListBeg.ItemIndex:=0;
MonthesListEnd.ItemIndex:=0;
PDB_Handle:=DB_Handle;
case PParameter.ControlFormStyle of
zcfsInsert:
begin
self.Caption := ZTaxesTerms_Caption_Insert[PLanguageIndex];
MonthesListBeg.ItemIndex:=YearMonthFromKodSetup(DateToKodSetup(date),False)-1;
YearSpinEditBeg.Value :=YearMonthFromKodSetup(DateToKodSetup(date));
MonthesListEnd.ItemIndex:=YearMonthFromKodSetup(DateToKodSetup(date),False)-1;
YearSpinEditEnd.Value :=YearMonthFromKodSetup(DateToKodSetup(date));
end;
zcfsUpdate:
begin
self.Caption := ZTaxesTerms_Caption_Update[PLanguageIndex];
MonthesListBeg.ItemIndex:=YearMonthFromKodSetup(PParameter.KodSetup1,False)-1;
YearSpinEditBeg.Value :=YearMonthFromKodSetup(PParameter.KodSetup1);
MonthesListEnd.ItemIndex:=YearMonthFromKodSetup(PParameter.KodSetup2,False)-1;
YearSpinEditEnd.Value :=YearMonthFromKodSetup(PParameter.KodSetup2);
end;
zcfsShowDetails:
begin
self.Caption := ZTaxesTerms_Caption_Detail[PLanguageIndex];
MonthesListBeg.ItemIndex:=YearMonthFromKodSetup(PParameter.KodSetup1,False)-1;
YearSpinEditBeg.Value :=YearMonthFromKodSetup(PParameter.KodSetup1);
MonthesListEnd.ItemIndex:=YearMonthFromKodSetup(PParameter.KodSetup2,False)-1;
YearSpinEditEnd.Value :=YearMonthFromKodSetup(PParameter.KodSetup2);
YesBtn.Visible:=False;
CancelBtn.Caption:=ExitBtn_Caption[PLanguageIndex];
Box.Enabled:=False;
end;
end;
end;
procedure TFZTaxesTerms.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFZTaxesTerms.YesBtnClick(Sender: TObject);
begin
if PeriodToKodSetup(YearSpinEditBeg.Value,MonthesListBeg.ItemIndex+1)>
PeriodToKodSetup(YearSpinEditEnd.Value,MonthesListEnd.ItemIndex+1) then
begin
ZShowMessage(ZeInputError_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
MonthesListBeg.SetFocus;
end
else
case PParameter.ControlFormStyle of
zcfsInsert:
try
DB.Handle:=PDB_Handle;
StoredProc.Database:=DB;
StoredProc.Transaction:=WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName:='Z_TAX_NET_PERIOD_I';
StoredProc.Prepare;
StoredProc.ParamByName('ID_TAX_NET').AsInteger := PParameter.ID_TAX_NET;
StoredProc.ParamByName('KOD_SETUP_1').AsInteger:= PeriodToKodSetup(YearSpinEditBeg.Value,MonthesListBeg.ItemIndex+1);
StoredProc.ParamByName('KOD_SETUP_2').AsInteger:= PeriodToKodSetup(YearSpinEditEnd.Value,MonthesListEnd.ItemIndex+1);
StoredProc.ExecProc;
PParameter.ID_TAX_NET_PERIOD:=StoredProc.ParamByName('ID_TAX_NET_PERIOD').AsInteger;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:Exception do
begin
StoredProc.Transaction.Rollback;
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
end;
end;
zcfsUpdate:
try
DB.Handle:=PDB_Handle;
StoredProc.Database:=DB;
StoredProc.Transaction:=WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName:='Z_TAX_NET_PERIOD_U';
StoredProc.Prepare;
StoredProc.ParamByName('ID_TAX_NET_PERIOD').AsInteger := PParameter.ID_TAX_NET_PERIOD;
StoredProc.ParamByName('ID_TAX_NET').AsInteger := PParameter.ID_TAX_NET;
StoredProc.ParamByName('KOD_SETUP_1').AsInteger:= PeriodToKodSetup(YearSpinEditBeg.Value,MonthesListBeg.ItemIndex+1);
StoredProc.ParamByName('KOD_SETUP_2').AsInteger:= PeriodToKodSetup(YearSpinEditEnd.Value,MonthesListEnd.ItemIndex+1);
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:Exception do
begin
StoredProc.Transaction.Rollback;
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
end;
end;
end;
end;
procedure TFZTaxesTerms.FormCreate(Sender: TObject);
begin
if PParameter.ControlFormStyle=zcfsDelete then
begin
if ZShowMessage(ZTaxesTerms_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then
try
DB.Handle:=PDB_Handle;
StoredProc.Database:=DB;
StoredProc.Transaction:=WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName:='Z_TAX_NET_PERIOD_D';
StoredProc.Prepare;
StoredProc.ParamByName('ID_TAX_NET_PERIOD').AsInteger := PParameter.ID_TAX_NET_PERIOD;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:Exception do
begin
StoredProc.Transaction.Rollback;
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
end;
end
else
ModalResult:=mrCancel;
end;
end;
procedure TFZTaxesTerms.YearSpinEditBegKeyPress(Sender: TObject;
var Key: Char);
begin
Key:=#0;
end;
procedure TFZTaxesTerms.YearSpinEditEndKeyPress(Sender: TObject;
var Key: Char);
begin
Key:=#0;
end;
procedure TFZTaxesTerms.YearSpinEditBegKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key=VK_DELETE then Key:=VK_ESCAPE;
end;
procedure TFZTaxesTerms.YearSpinEditEndKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key=VK_DELETE then Key:=VK_ESCAPE;
end;
end.
|
unit Invoice.View.Order;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls,
Invoice.Controller.Interfaces;
type
TFormOrder = class(TForm)
PanelBar: TPanel;
PanelGrid: TPanel;
DBGridRecords: TDBGrid;
DataSource: TDataSource;
ComboBoxField: TComboBox;
LabelField: TLabel;
LabelValue: TLabel;
EditValue: TEdit;
ButtonFind: TButton;
ButtonOrder: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DataSourceDataChange(Sender: TObject; Field: TField);
procedure ButtonFindClick(Sender: TObject);
procedure DBGridRecordsTitleClick(Column: TColumn);
procedure FormResize(Sender: TObject);
procedure ButtonOrderClick(Sender: TObject);
private
{ Private declarations }
FEntity: iEntity;
procedure FindRecords;
procedure ListComboBoxField;
public
{ Public declarations }
end;
var
FormOrder: TFormOrder;
implementation
{$R *.dfm}
uses Invoice.Controller.DataModule, Invoice.Controller.Facade, Invoice.View.OrderProduct;
procedure TFormOrder.ButtonFindClick(Sender: TObject);
begin
FindRecords;
//
FormResize(Sender);
end;
procedure TFormOrder.ButtonOrderClick(Sender: TObject);
begin
try
FormOrderProduct := TFormOrderProduct.Create(Self);
//
FormOrderProduct.SetidCustomer(DataSource.DataSet.FieldByName('idCustomer').AsInteger);
FormOrderProduct.SetnameCustomer(DataSource.DataSet.FieldByName('nameCustomer').AsString);
//
FormOrderProduct.ShowModal;
finally
FormOrderProduct.Free;
end;
end;
procedure TFormOrder.DataSourceDataChange(Sender: TObject; Field: TField);
begin
ButtonOrder.Visible := DataSource.DataSet.Active and (DataSource.DataSet.State = dsBrowse) and (DataSource.DataSet.RecordCount > 0);
end;
procedure TFormOrder.DBGridRecordsTitleClick(Column: TColumn);
begin
FEntity.OrderBy(Column.FieldName);
end;
procedure TFormOrder.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if DataSource.DataSet.Active then
DataSource.DataSet.Close;
//
Action := caFree;
end;
procedure TFormOrder.FormCreate(Sender: TObject);
begin
try
FEntity := TControllerGeneralFacade.New.EntityFactory.Customer(DataModuleLocal.GetConnection);
//
FEntity.List;
//
DataSource.DataSet := FEntity.DataSet;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
procedure TFormOrder.FormResize(Sender: TObject);
var
aCount: Integer;
aSizeGrid: Integer;
aSizeColunm: Integer;
begin
if DataSource.DataSet.Active then
begin
aSizeGrid := DBGridRecords.Width - 40;
aSizeColunm := 0;
//
for aCount := 0 to DBGridRecords.Columns.Count - 1 do
begin
if (DBGridRecords.Columns.Items[aCount].Width > 100) then
DBGridRecords.Columns.Items[aCount].Width := 100;
//
aSizeColunm := aSizeColunm + DBGridRecords.Columns.Items[aCount].Width;
end;
//
if (aSizeGrid >= aSizeColunm) then
DBGridRecords.Columns.Items[1].Width := DBGridRecords.Columns.Items[1].Width + (aSizeGrid - aSizeColunm)
else
DBGridRecords.Columns.Items[1].Width := DBGridRecords.Columns.Items[1].Width - (aSizeColunm - aSizeGrid);
end;
end;
procedure TFormOrder.FormShow(Sender: TObject);
begin
if not DataSource.DataSet.Active then
DataSource.DataSet.Open;
//
ListComboBoxField;
end;
procedure TFormOrder.FindRecords;
begin
try
if (EditValue.Text <> '') then
FEntity.ListWhere(ComboBoxField.Text + ' = ' + QuotedStr(EditValue.Text))
else
FEntity.ListWhere(ComboBoxField.Text + ' IS NOT NULL');
//
DataSource.DataSet := FEntity.DataSet;
//
DataSource.DataSet.Open;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
procedure TFormOrder.ListComboBoxField;
begin
ComboBoxField.Items.Clear;
//
if (DataSource.DataSet.Fields.Count > 0) then
begin
DataSource.DataSet.Fields.GetFieldNames(ComboBoxField.Items);
//
ComboBoxField.ItemIndex := 1;
end;
end;
Initialization
RegisterClass(TFormOrder);
Finalization
UnRegisterClass(TFormOrder);
end.
|
unit project1_unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Memo1: TMemo;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
FThread: TThread;
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
uses
Lua54, l4l_object;
{$R *.lfm}
type
{ TLuaThread }
TLuaThread = class(TThread)
private
L: Plua_State;
msg: string;
{$IF FPC_FULLVERSION < 30000}
finished: boolean;
{$ENDIF}
procedure ShowMsg;
procedure Last;
protected
procedure Execute; override;
public
property Terminated;
constructor Create(aL: plua_state); overload;
destructor Destroy; override;
end;
{ TLuaMyObject }
TLuaMyObject = class(TLuaObject)
private
procedure DoPrint;
procedure DoSetCaption;
protected
public
published
function l4l_print: integer;
function l4l_SetCaption: integer;
end;
function Alloc({%H-}ud, ptr: Pointer; {%H-}osize, nsize: size_t) : Pointer; cdecl;
begin
try
Result:= ptr;
ReallocMem(Result, nSize);
except
Result:= nil;
end;
end;
procedure hook({%H-}L: plua_State; {%H-}ar: plua_Debug); cdecl;
begin
if TLuaThread(Form1.FThread).Terminated then SysUtils.Abort;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
L: Plua_State;
s: string;
begin
if Assigned(FThread) and not TLuaThread(FThread).finished then begin
// Stop thread.
FThread.Free;
FThread := nil;
Exit;
end;
// Start thread.
Memo2.Clear;
L:= lua_newstate(@alloc, nil);
lua_sethook(L, @hook, LUA_MASKLINE, 0);
l4l_PushLuaObject(TLuaMyObject.Create(L)); lua_setglobal(L, 'my'); // set global value.
s:= Memo1.Text;
if luaL_loadbuffer(L, PChar(s), Length(s), 'sample') <> 0 then begin
Form1.Memo2.Lines.Add(lua_tostring(L, -1));
Form1.Memo2.SelStart:= 0;
Form1.Memo2.SelLength:= 0;
lua_close(L);
Exit;
end;
if Assigned(FThread) then FThread.Free;
FThread := TLuaThread.Create(L);
Form1.Button1.Caption:= 'Stop';
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FThread:= nil;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
end;
procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if Assigned(FThread) then begin
FThread.Free;
FThread:= nil;
end;
end;
{ TLuaThread }
procedure TLuaThread.Execute;
begin
{$IF FPC_FULLVERSION < 30000}
finished:= False;
{$ENDIF}
try
try
if lua_pcall(L, 0, 0, 0) <> 0 then Exception.Create('');
except
on E: EAbort do begin
msg := 'Abort.';
Synchronize(@ShowMsg);
end;
else begin
msg := lua_tostring(L, -1);
Synchronize(@ShowMsg);
end;
end;
finally
{$IF FPC_FULLVERSION < 30000}
finished:= True;
{$ENDIF}
msg := ''; // For economy.
lua_close(L);
Synchronize(@Last);
end;
end;
constructor TLuaThread.Create(aL: plua_state);
begin
L := aL;
FreeOnTerminate:= False;
inherited Create(False);
end;
procedure TLuaThread.ShowMsg;
begin
Form1.Memo2.Lines.Add(msg);
Form1.Memo2.SelStart:= 0;
Form1.Memo2.SelLength:= 0;
end;
procedure TLuaThread.Last;
begin
Form1.Button1.Caption:= 'Start';
end;
destructor TLuaThread.Destroy;
begin
inherited Destroy;
end;
{ TLuaMyObject }
procedure TLuaMyObject.DoPrint;
var
i, c: integer;
begin
c:= lua_gettop(LS);
for i:= 1 to c do
Form1.Memo2.Lines.Add(lua_tostring(LS, i));
Form1.Memo2.SelStart:= 0;
Form1.Memo2.SelLength:= 0;
end;
procedure TLuaMyObject.DoSetCaption;
begin
Form1.Label1.Caption:= lua_tostring(LS, 1);
end;
function TLuaMyObject.l4l_print: integer;
begin
TThread.Synchronize(nil, @DoPrint);
Result := 0;
end;
function TLuaMyObject.l4l_SetCaption: integer;
begin
TThread.Synchronize(nil, @DoSetCaption);
Result := 0;
end;
end.
|
//=============================================================================
// sgSprites.pas
//=============================================================================
//
// Create and manage sprites in SwinGame.
//
//=============================================================================
/// SwinGame Sprites are game elements that can be moved, and animated. Sprites are
/// located at a position in the game, have a velocity, and an animation. The
/// Sprite can also have arbitary data associated with it for game specific purposes.
///
/// @module Sprites
unit sgSprites;
//=============================================================================
interface
uses sgTypes;
//=============================================================================
//---------------------------------------------------------------------------
// Sprite creation routines
//---------------------------------------------------------------------------
/// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
/// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
/// pixel level collisions, no animations, and have one layer named 'layer1'.
///
/// This version of the constructor will assign a default name to the sprite for resource management purposes.
///
/// @lib CreateBasicSprite
///
/// @class Sprite
/// @constructor
/// @csn initWithBitmap:%s
function CreateSprite(layer: Bitmap): Sprite; overload;
/// Creates a sprite. The bitmapName is used to indicate the bitmap the sprite will use, and the
/// animationName is used to indicate which AnimationScript to use.
///
/// @lib CreateSpriteWithBitmapAndAnimationName
///
/// @class Sprite
/// @constructor
/// @csn initWithBitmapNamed:%s animationScriptNamed:%s
function CreateSprite(const bitmapName, animationName: String): Sprite; overload;
/// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
/// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
/// pixel level collisions, the specified animation template, the layer have name 'layer1'.
///
/// This version of the constructor will assign a default name to the sprite for resource management purposes.
///
/// @lib CreateSpriteWithAnimation
/// @sn createSpriteWithLayer:%s animationScript:%s
///
/// @class Sprite
/// @constructor
/// @csn initWithBitmap:%s animationScript:%s
function CreateSprite(layer: Bitmap; ani: AnimationScript): Sprite; overload;
/// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
/// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
/// pixel level collisions, no animation, the layer have name 'layer1'.
///
/// @lib CreateBasicSpriteNamed
/// @sn createSpriteNamed:%s layer:%s
///
/// @class Sprite
/// @constructor
/// @csn initNamed:%s withBitmap:%s
function CreateSprite(const name: String; layer: Bitmap): Sprite; overload;
/// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
/// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
/// pixel level collisions, the specified animation template, the layer have name 'layer1'.
///
/// @lib CreateSpriteWithAnimationNamed
/// @sn createSpriteNamed:%s layer:%s animationScript:%s
///
/// @class Sprite
/// @constructor
/// @csn initNamed:%s withBitmap:%s animationScript:%s
function CreateSprite(const name: String; layer: Bitmap; ani: AnimationScript): Sprite; overload;
/// Free the resources associated with a sprite.
///
/// @lib
/// @class Sprite
/// @dispose
procedure FreeSprite(var s : Sprite);
//---------------------------------------------------------------------------
// Sprite Resource Management code
//---------------------------------------------------------------------------
/// Determines if SwinGame has a sprite for the supplied name.
/// This checks against all sprites, those loaded without a name
/// are assigned a default.
///
/// @lib
function HasSprite(const name: String): Boolean;
/// Returns the `Sprite` with the specified name,
/// see `CreateBasicSprite`.
///
/// @lib
function SpriteNamed(const name: String): Sprite;
/// Releases the SwinGame resources associated with the sprite of the
/// specified ``name``.
///
/// @lib
procedure ReleaseSprite(const name: String);
/// Releases all of the sprites that have been loaded.
///
/// @lib
procedure ReleaseAllSprites();
//---------------------------------------------------------------------------
// Event Code
//---------------------------------------------------------------------------
/// Register a procedure to be called when an events occur on any sprite.
///
/// @lib
/// @sn callOnSpriteEvent:%s
procedure CallOnSpriteEvent(handler: SpriteEventHandler);
/// Removes an global event handler, stopping events calling the indicated procedure.
///
/// @lib
/// @sn stopCallingOnSpriteEvent:%s
procedure StopCallingOnSpriteEvent(handler: SpriteEventHandler);
/// Register a procedure to call when events occur on the sprite.
///
/// @lib
/// @sn sprite:%s callOnEvent:%s
///
/// @class Sprite
/// @method CallOnEvent
/// @csn callOnEvent:%s
procedure SpriteCallOnEvent(s: Sprite; handler: SpriteEventHandler);
/// Removes an event handler from the sprite, stopping events from this
/// Sprite calling the indicated method.
///
/// @lib
/// @sn sprite:%s stopCallingOnEvent:%s
///
/// @class Sprite
/// @method StopCallingOnEvent
/// @csn stopCallingOnEvent:%s
procedure SpriteStopCallingOnEvent(s: Sprite; handler: SpriteEventHandler);
//---------------------------------------------------------------------------
// Layer code
//---------------------------------------------------------------------------
/// Adds a new layer to the sprite.
///
/// @lib
/// @sn sprite:%s addLayer:%s named:%s
///
/// @class Sprite
/// @method AddLayer
/// @csn addLayer:%s named:%s
function SpriteAddLayer(s: Sprite; newLayer: Bitmap; const layerName: String): Longint;
/// Returns the bitmap of the indicated layer of the sprite.
///
/// @lib SpriteLayerNamed
/// @sn sprite:%s layerNamed:%s
///
/// @class Sprite
/// @method LayerNamed
/// @csn layerNamed:%s
function SpriteLayer(s: Sprite; const name: String): Bitmap; overload;
/// Returns the bitmap of the indicated layer of the sprite.
///
/// @lib SpriteLayerAtIdx
/// @sn sprite:%s layerAtIdx:%s
///
/// @class Sprite
/// @method LayerAtIdx
/// @csn layerAtIdx:%s
function SpriteLayer(s: Sprite; idx: Longint): Bitmap; overload;
/// Returns the index of the specified layer.
///
/// @lib SpriteLayerIndex
/// @sn sprite:%s indexOfLayer:%s
///
/// @class Sprite
/// @method IndexOfLayer
/// @csn indexOfLayer:%s
function SpriteLayerIndex(s: Sprite; const name: String): Longint;
/// Returns the name of the specified layer.
///
/// @lib SpriteLayerName
/// @sn sprite:%s layerName:%s
///
/// @class Sprite
/// @method LayerName
/// @csn layerName:%s
function SpriteLayerName(s: Sprite; idx: Longint): String;
/// Show the specified layer of the sprite.
///
/// @lib SpriteShowLayerNamed
/// @sn sprite:%s showLayerNamed:%s
///
/// @class Sprite
/// @overload ShowLayer ShowLayerNamed
/// @csn showLayerNamed:%s
function SpriteShowLayer(s: Sprite; const name: String): Longint; overload;
/// Show the specified layer of the sprite.
///
/// @lib SpriteShowLayer
/// @sn sprite:%s showLayer:%s
///
/// @class Sprite
/// @method ShowLayer
/// @csn showLayer:%s
function SpriteShowLayer(s: Sprite; id: Longint): Longint; overload;
/// Hide the specified layer of the sprite.
///
/// @lib SpriteHideLayerNamed
/// @sn sprite:%s hideLayerNamed:%s
///
/// @class Sprite
/// @overload HideLayer HideLayerNamed
/// @csn hideLayerNamed:%s
procedure SpriteHideLayer(s: Sprite; const name: String); overload;
/// Hide the specified layer of the sprite.
///
/// @lib SpriteHideLayer
/// @sn sprite:%s hideLayer:%s
///
/// @class Sprite
/// @method HideLayer
/// @csn hideLayer:%s
procedure SpriteHideLayer(s: Sprite; id: Longint); overload;
/// Toggle the visibility of the specified layer of the sprite.
///
/// @lib SpriteToggleLayerNamedVisible
/// @sn sprite:%s toggleVisibleLayerNamed:%s
///
/// @class Sprite
/// @overload ToggleLayerVisible ToggleLayerNamedVisible
/// @csn toggleLayerNamedVisible:%s
procedure SpriteToggleLayerVisible(s: Sprite; const name: String); overload;
/// Toggle the visibility of the specified layer of the sprite.
///
/// @lib SpriteToggleLayerVisible
/// @sn sprite:%s toggleVisibleLayer:%s
///
/// @class Sprite
/// @method ToggleLayerVisible
/// @csn toggleLayerVisible:%s
procedure SpriteToggleLayerVisible(s: Sprite; id: Longint); overload;
/// Returns the index (z-order) of the sprite's layer.
///
/// @lib SpriteVisibleIndexOfLayerNamed
/// @sn sprite:%s visibleIndexOfLayerNamed:%s
///
/// @class Sprite
/// @overload VisibleIndexOfLayer VisibleIndexOfLayerNamed
/// @csn visibleIndexOfLayerNamed:%s
function SpriteVisibleIndexOfLayer(s: Sprite; const name: String): Longint; overload;
/// Returns the index (z-order) of the sprite's layer.
///
/// @lib SpriteVisibleIndexOfLayer
/// @sn sprite:%s visibleIndexOfLayer:%s
///
/// @class Sprite
/// @method VisibleIndexOfLayer
/// @csn visibleIndexOfLayer:%s
function SpriteVisibleIndexOfLayer(s: Sprite; id: Longint): Longint; overload;
/// Returns the number of layers within the Sprite.
///
/// @lib
///
/// @class Sprite
/// @getter LayerCount
function SpriteLayerCount(s: Sprite): Longint;
///Returns the number of layers that are currently visible for the sprite.
///
/// @lib
///
/// @class Sprite
/// @getter VisibleLayerCount
function SpriteVisibleLayerCount(s: Sprite): Longint;
/// Returns the id of the layer at index `idx` that is currently visible.
/// Index 0 is the background, with larger indexes moving toward the foreground.
/// This returns -1 if there are no visible layers.
///
/// @lib
///
/// @class Sprite
/// @method VisibleLayerIdAt
function SpriteVisibleLayerId(s: Sprite; idx: Longint) : Longint;
/// Gets the offset of the specified layer.
///
/// @lib SpriteLayerOffsetNamed
/// @sn sprite:%s offsetOfLayerNamed:%s
///
/// @class Sprite
/// @overload LayerOffset LayerNamedOffset
/// @csn offsetOfLayerNamed:%s
function SpriteLayerOffset(s: Sprite; const name: String): Point2D; overload;
/// Gets the offset of the specified layer.
///
/// @lib
/// @sn sprite:%s offsetOfLayer:%s
///
/// @class Sprite
/// @method LayerOffset
/// @csn offsetOfLayer:%s
function SpriteLayerOffset(s: Sprite; idx: Longint): Point2D; overload;
/// Sets the offset of the specified layer.
///
/// @lib SpriteSetLayerOffsetNamed
/// @sn sprite:%s setOffsetOfLayerNamed:%s to:%s
///
/// @class Sprite
/// @overload SetLayerOffset SetLayerNamedOffset
/// @csn layerNamed:%s setOffset:%s
procedure SpriteSetLayerOffset(s: Sprite; const name: String; const value: Point2D); overload;
/// Sets the offset of the specified layer.
///
/// @lib
/// @sn sprite:%s setOffsetOfLayer:%s to:%s
///
/// @class Sprite
/// @overload SetLayerOffset SetLayerNamedOffset
/// @csn layer:%s setOffset:%s
procedure SpriteSetLayerOffset(s: Sprite; idx: Longint; const value: Point2D); overload;
/// Returns the index of the n'th (idx parameter) visible layer.
///
/// @lib
/// @sn sprite:%s visibleLayer:%s
///
/// @class Sprite
/// @method VisibleLayer
function SpriteVisibleLayer(s: Sprite; idx: Longint): Longint;
/// Sends the layer specified to the back in the visible layer order.
///
/// @lib
/// @sn sprite:%s sendLayerToBack:%s
///
/// @class Sprite
/// @method SendLayerToBack
procedure SpriteSendLayerToBack(s: Sprite; visibleLayer: Longint);
/// Sends the layer specified backward in the visible layer order.
///
/// @lib
/// @sn sprite:%s sendLayerToBackward:%s
///
/// @class Sprite
/// @method SendLayerToBackward
procedure SpriteSendLayerBackward(s: Sprite; visibleLayer: Longint);
/// Sends the layer specified forward in the visible layer order.
///
/// @lib
/// @sn sprite:%s sendLayerForward:%s
///
/// @class Sprite
/// @method SendLayerForward
procedure SpriteBringLayerForward(s: Sprite; visibleLayer: Longint);
/// Sends the layer specified to the front in the visible layer order.
///
/// @lib
/// @sn sprite:%s sendLayerToFront:%s
///
/// @class Sprite
/// @method SendLayerToFront
procedure SpriteBringLayerToFront(s: Sprite; visibleLayer: Longint);
/// Gets a rectangle that surrounds the indicated layer.
///
/// @lib SpriteLayerNamedRectangle
/// @sn sprite:%s rectangleForLayerNamed:%s
///
/// @class Sprite
/// @method RectangleForLayerNamed
function SpriteLayerRectangle(s: Sprite; const name: String): Rectangle; overload;
/// Gets a rectangle that surrounds the indicated layer.
///
/// @lib
/// @sn sprite:%s rectangleForLayer:%s
///
/// @class Sprite
/// @method RectangleForLayer
function SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle; overload;
/// Returns the collision rectangle for the specified sprite.
///
/// @lib
///
/// @class Sprite
/// @getter CollisionRectangle
function SpriteCollisionRectangle(s: Sprite): Rectangle;
/// Gets a circle in the bounds of the indicated layer.
///
/// @lib SpriteLayerNamedCircle
/// @sn sprite:%s circleForLayerNamed:%s
///
/// @class Sprite
/// @method CircleForLayerNamed
function SpriteLayerCircle(s: Sprite; const name: String): Circle; overload;
/// Gets a circle in the bounds of the indicated layer.
///
/// @lib
/// @sn sprite:%s circleForLayer:%s
///
/// @class Sprite
/// @method CircleForLayer
function SpriteLayerCircle(s: Sprite; idx: Longint): Circle; overload;
/// Gets a circle in the bounds of the base layer of the indicated sprite.
///
/// @lib
/// @sn spriteCircle:%s
///
/// @class Sprite
/// @method Circle
function SpriteCircle(s: Sprite): Circle; overload;
/// Gets a circle in the bounds of the indicated sprite's collision rectangle.
///
/// @lib
///
/// @class Sprite
/// @method CollisionCircle
function SpriteCollisionCircle(s: Sprite): Circle;
/// Returns a matrix that can be used to transform points into the coordinate space
/// of the passed in sprite.
///
/// @lib
///
/// @class Sprite
/// @getter LocationMatrix
/// @csn locationMatrix
function SpriteLocationMatrix(s: Sprite): Matrix2D;
//---------------------------------------------------------------------------
// Sprite Animation code
//---------------------------------------------------------------------------
/// Restart the sprite's current animation, this will play a sound if the
/// first cell of the animation is associated with a sound effect.
///
/// @lib
///
/// @class Sprite
/// @method ReplayAnimation
procedure SpriteReplayAnimation(s : Sprite);
/// Restart the sprite's current animation, this will play a sound if
/// withSound is true and the first cell of the animation is associated with a sound effect.
///
/// @lib ReplayAnimationWithSound
/// @sn sprite:%s replayAnimationWithSound:%s
///
/// @class Sprite
/// @overload ReplayAnimation ReplayAnimationWithSound
/// @csn replayAnimationWithSound:%s
procedure SpriteReplayAnimation(s: Sprite; withSound: Boolean);
/// Start playing an animation from the sprite's animation template.
/// This will play a sound effect if the first cell of the animation
/// has a sound.
///
/// @lib SpriteStartAnimationNamed
/// @sn sprite:%s startAnimationNamed:%s
///
/// @class Sprite
/// @overload StartAnimation StartAnimationNamed
/// @csn startAnimationNamed:%s
procedure SpriteStartAnimation(s: Sprite; const named: String); overload;
/// Start playing an animation from the sprite's animation template.
/// The withSound parameter determines whether to play a sound effect
/// if the first cell of the animation has a sound.
///
/// @lib SpriteStartAnimationNamedWithSound
/// @sn sprite:%s startAnimationNamed:%s withSound:%s
///
/// @class Sprite
/// @overload StartAnimation StartAnimationNamedWithSound
/// @csn startAnimationNamed:%s withSound:%s
procedure SpriteStartAnimation(s: Sprite; const named: String; withSound: Boolean); overload;
/// Start playing an animation from the sprite's animation template.
/// This will play a sound effect if the first cell of the animation
/// has a sound.
///
/// @lib SpriteStartAnimation
/// @sn sprite:%s startAnimation:%s
///
/// @class Sprite
/// @method StartAnimation
/// @csn startAnimation:%s
procedure SpriteStartAnimation(s: Sprite; idx: Longint); overload;
/// Start playing an animation from the sprite's animation template.
/// The withSound parameter determines whether to play a sound effect
/// if the first cell of the animation has a sound.
///
/// @lib SpriteStartAnimationWithSound
/// @sn sprite:%s startAnimation:%s withSound:%s
///
/// @class Sprite
/// @overload StartAnimation StartAnimationWithSound
/// @csn startAnimation:%s withSound:%s
procedure SpriteStartAnimation(s: Sprite; idx: Longint; withSound: Boolean); overload;
/// Returns the name of the Sprite's current animation.
///
/// @lib SpriteAnimationName
/// @sn spriteAnimationName:%s
///
/// @class Sprite
/// @method animationName
function SpriteAnimationName(s: Sprite): String;
//---------------------------------------------------------------------------
// Sprite Update code
//---------------------------------------------------------------------------
/// Update the position and animation details of the Sprite.
/// This will play a sound effect if the new cell of the animation
/// has a sound.
///
/// @lib UpdateSpritePctWithSound(s, 1.0, true)
/// @uname UpdateSprite
/// @sn updateSprite:%s
///
/// @class Sprite
/// @method Update
procedure UpdateSprite(s: Sprite); overload;
/// Update the position and animation details of the Sprite.
/// This will play a sound effect if the new cell of the animation
/// has a sound and withSound is true.
///
/// @lib UpdateSpritePctWithSound(s, 1.0, withSound)
/// @uname UpdateSpriteWithSound
/// @sn updateSprite:%s withSound:%s
///
/// @class Sprite
/// @overload Update UpdateWithSound
/// @csn updateWithSound:%s
procedure UpdateSprite(s: Sprite; withSound:Boolean); overload;
/// Update the position and animation details of the Sprite by a
/// given percentage of a single unit of movement/animation.
/// This will play a sound effect if the new cell of the animation
/// has a sound.
///
/// @lib UpdateSpritePctWithSound(s, pct, true)
/// @uname UpdateSpritePercent
/// @sn updateSprite:%s percent:%s
///
/// @class Sprite
/// @overload Update UpdatePercent
/// @csn updatePercent:%s
procedure UpdateSprite(s: Sprite; pct: Single); overload;
/// Update the position and animation details of the Sprite by a
/// given percentage of a single unit of movement/animation.
/// This will play a sound effect if the new cell of the animation
/// has a sound and withSound is true.
///
/// @lib UpdateSpritePctWithSound
/// @sn updateSprite:%s percent:%s withSound:%s
///
/// @class Sprite
/// @overload Update UpdatePercentWithSound
/// @csn updatePercent:%s withSound:%s
procedure UpdateSprite(s: Sprite; pct: Single; withSound: Boolean); overload;
/// Updates the animation details of the sprite.
/// This will play a sound effect if the new cell of the animation
/// has a sound.
///
/// @lib UpdateSpriteAnimationPctWithSound(s, 1.0, true)
/// @uname UpdateSpriteAnimation
///
/// @class Sprite
/// @method UpdateAnimation
procedure UpdateSpriteAnimation(s: Sprite); overload;
/// Update the animation details of the Sprite.
/// This will play a sound effect if the new cell of the animation
/// has a sound and withSound is true.
///
/// @lib UpdateSpriteAnimationPctWithSound(s, 1.0, withSound)
/// @uname UpdateSpriteAnimationWithSound
/// @sn sprite:%s updateAnimationWithSound:%s
///
/// @class Sprite
/// @overload UpdateAnimation UpdateAnimationWithSound
/// @csn updateAnimationWithSound:%s
procedure UpdateSpriteAnimation(s: Sprite; withSound: Boolean); overload;
/// Update the animation details of the Sprite by a
/// given percentage of a single unit of movement/animation.
/// This will play a sound effect if the new cell of the animation
/// has a sound.
///
/// @lib UpdateSpriteAnimationPctWithSound(s, pct, true)
/// @uname UpdateSpriteAnimationPercent
/// @sn sprite:%s updateAnimationPct:%s
///
/// @class Sprite
/// @overload UpdateAnimation UpdateAnimationPct
/// @csn updateAnimationPct:%s
procedure UpdateSpriteAnimation(s: Sprite; pct: Single); overload;
/// Update the position and animation details of the Sprite by a
/// given percentage of a single unit of movement/animation.
/// This will play a sound effect if the new cell of the animation
/// has a sound and withSound is true.
///
/// @lib UpdateSpriteAnimationPctWithSound
/// @sn sprite:%s updateAnimationPct:%s withSound:%s
///
/// @class Sprite
/// @overload UpdateAnimation UpdateAnimationPctWithSound
/// @csn updateAnimationPct:%s withSound:%s
procedure UpdateSpriteAnimation(s: Sprite; pct: Single; withSound: Boolean); overload;
/// Indicates if the sprites animation has ended.
///
/// @lib
///
/// @class Sprite
/// @getter AnimationHasEnded
function SpriteAnimationHasEnded(s: Sprite): Boolean;
//---------------------------------------------------------------------------
// Positioning code
//---------------------------------------------------------------------------
/// Returns a `Vector` that is the difference in the position of two sprites
/// (``s1`` and ``s2``).
///
/// @lib
/// @sn vectorFromSprite:%s toSprite:%s
///
/// @class Sprite
/// @method VectorTo
/// @csn vectorToSprite:%s
function VectorFromTo(s1, s2: Sprite): Vector;
/// Returns a `Vector` that is the difference in location from the center of
/// the sprite ``s`` to the point ``pt``.
///
/// @lib
/// @sn vectorFromCenterOfSprite:%s toPoint:%s
///
/// @class Sprite
/// @overload VectorTo VectorToPoint
/// @csn vectorToPoint:%s
function VectorFromCenterSpriteToPoint(s: Sprite; const pt: Point2D): Vector;
//---------------------------------------------------------------------------
// Drawing code
//---------------------------------------------------------------------------
/// Draws the sprite at its location in the world. This is effected by the
/// position of the camera and the sprites current location.
///
/// This is the standard routine for drawing sprites to the screen and should be
/// used in most cases.
///
/// @lib DrawSpriteOffsetXY(s, 0, 0)
/// @uname DrawSprite
///
/// @class Sprite
/// @method Draw
procedure DrawSprite(s : Sprite); overload;
/// Draws the sprite at its position in the game offset by a given amount. Only
/// use this method when you want to draw the sprite displaced from its location
/// in your game. Otherwise you should change the sprite's location and then
/// use the standard ''DrawSprite'' routine.
///
/// @lib DrawSpriteOffsetXY
/// @sn sprite:%s drawOffsetX:%s y:%s
///
/// @class Sprite
/// @overload Draw DrawOffsetXY
/// @csn drawOffsetX:%s y:%s
procedure DrawSprite(s : Sprite; xOffset, yOffset: Longint); overload;
/// Draws the sprite at its position in the game offset by a given amount. Only
/// use this method when you want to draw the sprite displaced from its location
/// in your game. Otherwise you should change the sprite's location and then
/// use the standard ''DrawSprite'' routine.
///
/// @lib DrawSpriteOffsetPoint
/// @sn sprite:%s drawOffset:%s
///
/// @class Sprite
/// @overload Draw DrawOffsetPoint
/// @csn drawOffset:%s
procedure DrawSprite(s : Sprite; const position: Point2D); overload;
//---------------------------------------------------------------------------
// Movement code
//---------------------------------------------------------------------------
/// Moves the sprite as indicated by its velocity. You can call this directly ot
/// alternatively, this action is performed when the sprite is updated using
/// the ''UpdateSprite'' routine.
///
/// @lib MoveSpritePct(s, 1.0)
/// @uname MoveSprite
///
/// @class Sprite
/// @method Move
procedure MoveSprite(s: Sprite); overload;
/// Moves the sprite as indicated by a percentage of its velocity. You can call
/// this directly ot alternatively, this action is performed when the sprite is
/// updated using the ''UpdateSprite'' routines that require a percentage.
///
/// @lib MoveSpritePct
/// @sn sprite:%s movePct:%s
///
/// @class Sprite
/// @overload Move MovePct
/// @csn movePct:%s
procedure MoveSprite(s: Sprite; pct: Single); overload;
/// Moves the sprite a given distance based on the value passed in rather than
/// based on the sprite's velocity. Typically this method is used to apply
/// other movement actions to the sprite and the velocity of the sprite is
/// used the intended movement of the sprite.
///
/// @lib MoveSpriteVecPct(s, distance, 1.0)
/// @uname MoveSpriteVec
/// @sn sprite:%s move:%s
///
/// @class Sprite
/// @overload Move MoveVec
/// @csn move:%s
procedure MoveSprite(s : Sprite; const distance: Vector); overload;
/// Moves the sprite a percentage of a given distance based on the value
/// passed in rather than based on the sprite's velocity. Typically this
/// method is used to apply other movement actions to the sprite and the
/// velocity of the sprite is used the intended movement of the sprite.
///
/// @lib MoveSpriteVecPct
/// @sn sprite:%s move:%s pct:%s
///
/// @class Sprite
/// @overload Move MoveVecPct
/// @csn move:%s pct:%s
procedure MoveSprite(s : Sprite; const distance: Vector; pct: Single); overload;
/// This method moves a sprite to a given position in the game.
///
/// @lib
/// @sn sprite:%s moveToX:%s y:%s
///
/// @class Sprite
/// @method MoveTo
/// @csn moveToX:%s y:%s
procedure MoveSpriteTo(s : Sprite; x,y : Longint);
/// This procedure starts the sprite moving to the indicated
/// destination point, over a specified number of seconds. When the
/// sprite arrives it will raise the SpriteArrived event.
///
/// @lib
/// @sn sprite:%s moveTo:%s takingSeconds:%s
///
/// @class Sprite
/// @overload MoveTo MoveToTakingSeconds
/// @csn moveTo:%s takingSeconds:%s
procedure SpriteMoveTo(s: Sprite; const pt: Point2D; takingSeconds: Longint);
//---------------------------------------------------------------------------
// Sprite Screen Position Tests
//---------------------------------------------------------------------------
/// Returns True if a pixel of the `Sprite` ``s`` is at the screen location
/// specified (``x`` and ``y``) which is converted to a world location.
///
/// @lib
/// @sn sprite:%s onScreenAtX:%s y:%s
///
/// @class Sprite
/// @method OnScreenAt
/// @csn onScreenAtX:%s y:%s
function SpriteOnScreenAt(s: Sprite; x, y: Longint): Boolean; overload;
/// Returns True if a pixel of the `Sprite` ``s`` is at the screen location
/// specified (``pt``), which is converted to a world location.
///
/// @lib SpriteOnScreenAtPoint
/// @sn sprite:%s onScreenAt:%s
///
/// @class Sprite
/// @overload OnScreenAt OnScreenAtPoint
/// @csn onScreenAt:%s
function SpriteOnScreenAt(s: Sprite; const pt: Point2D): Boolean; overload;
/// Returns True if the sprite is entirely off the screen.
///
/// @lib
///
/// @class Sprite
/// @method Offscreen
function SpriteOffscreen(s : Sprite): Boolean;
//---------------------------------------------------------------------------
// Sprite Width and Heigth - CenterPoint
//---------------------------------------------------------------------------
/// The current Height of the sprite (aligned to the Y axis).
///
/// @lib
///
/// @class Sprite
/// @getter Height
function SpriteHeight(s: Sprite): Longint;
/// The height of a given layer of the Sprite (aligned to the Y axis).
///
/// @lib SpriteLayerNamedHeight
/// @sn sprite:%s heightOfLayerNamed:%s
///
/// @class Sprite
/// @overload LayerHeight LayerNamedHeight
/// @csn heightOfLayerNamed:%s
function SpriteLayerHeight(s: Sprite; const name: String): Longint; overload;
/// The height of a given layer of the Sprite (aligned to the Y axis).
///
/// @lib SpriteLayerHeight
/// @sn sprite:%s heightOfLayer:%s
///
/// @class Sprite
/// @method LayerHeight
/// @csn heightOfLayer:%s
function SpriteLayerHeight(s: Sprite; idx: Longint): Longint; overload;
/// The current Width of the sprite (aligned to the X axis).
///
/// @lib
/// @class Sprite
/// @getter Width
function SpriteWidth(s: Sprite): Longint;
/// The width of a given layer of the Sprite (aligned to the X axis).
///
/// @lib SpriteLayerNamedWidth
/// @sn sprite:%s widthOfLayerNamed:%s
///
/// @class Sprite
/// @overload LayerWidth LayerNamedWidth
/// @csn widthOfLayerNamed:%s
function SpriteLayerWidth(s: Sprite; const name: String): Longint; overload;
/// The width of a given layer of the Sprite (aligned to the X axis).
///
/// @lib SpriteLayerWidth
/// @sn sprite:%s widthOfLayer:%s
///
/// @class Sprite
/// @method LayerWidth
/// @csn widthOfLayer:%s
function SpriteLayerWidth(s: Sprite; idx: Longint): Longint; overload;
/// Returns the center point of the passed in Sprite. This is based on the Sprite's
/// Position, Width and Height.
///
/// @lib CenterPoint
///
/// @class Sprite
/// @getter CenterPoint
function CenterPoint(s: Sprite): Point2D; overload;
/// Returns the anchor point of the sprite. This is the point around which the sprite rotates.
/// This is in sprite coordinates, so as if the Sprite is drawn at 0,0.
///
/// @lib
///
/// @class Sprite
/// @getter AnchorPoint
function SpriteAnchorPoint(s: Sprite): Point2D;
/// Allows you to set the anchor point for the sprite. This is the point around
/// which the sprite rotates. This is in sprite coordinates, so as if the Sprite
/// is drawn at 0,0.
///
/// @lib
///
/// @class Sprite
/// @setter AnchorPoint
procedure SpriteSetAnchorPoint(s: Sprite; pt: Point2D);
/// Indicates if the sprite is moved from its anchor point, or from its top left.
/// When this returns true the location of the Sprite will indicate its anchor point.
/// When this returns false the location of the Sprite is its top left corner.
///
/// @lib
///
/// @class Sprite
/// @getter MoveFromAnchorPoint
function SpriteMoveFromAnchorPoint(s: Sprite): Boolean;
/// Allows you to indicate if the sprite is moved from its anchor point, or from its
/// top left.
/// When set to true the location of the Sprite will be its anchor point.
/// When set to false the location of the Sprite is its top left corner.
///
/// @lib
///
/// @class Sprite
/// @setter MoveFromAnchorPoint
procedure SpriteSetMoveFromAnchorPoint(s: Sprite; value: Boolean);
//---------------------------------------------------------------------------
// Sprite velocity
//---------------------------------------------------------------------------
/// Returns the current velocity of the Sprite. When the Sprite is updated (see ``UpdateSprite``)
/// this vector is used to move the Sprite.
///
/// @lib
///
/// @class Sprite
/// @getter Velocity
function SpriteVelocity(s: Sprite): Vector;
/// Sets the current velocity of the Sprite. When the Sprite is updated (see ``UpdateSprite``)
/// this vector is used to move the Sprite.
///
/// @lib
/// @sn sprite:%s setVelocity:%s
///
/// @class Sprite
/// @setter Velocity
procedure SpriteSetVelocity(s: Sprite; const value: Vector);
/// Alters the current velocity of the Sprite, adding the passed in vector to the current velocity.
///
/// When the Sprite is updated (see ``UpdateSprite``)
/// this vector is used to move the Sprite.
///
/// @lib
/// @sn sprite:%s addToVelocity:%s
///
/// @class Sprite
/// @method AddToVelocity
procedure SpriteAddToVelocity(s: Sprite; const value: Vector);
//---------------------------------------------------------------------------
// Sprite CellCount
//---------------------------------------------------------------------------
/// Returns a rectangle of the current cell within the Sprite's image. This is used
/// to determine what part of the bitmap should be used when the Sprite is drawn.
///
/// @lib
///
/// @class Sprite
/// @getter CurrentCellRectangle
function SpriteCurrentCellRectangle(s: Sprite): Rectangle;
/// Returns the rectangle representing the location of the Sprite on the
/// screen.
///
/// @lib
///
/// @class Sprite
/// @getter ScreenRectangle
function SpriteScreenRectangle(s: Sprite): Rectangle;
//---------------------------------------------------------------------------
// Sprite X,Y
//---------------------------------------------------------------------------
/// Sets the X position of the Sprite.
///
/// @lib
/// @sn sprite:%s setX:%s
///
/// @class Sprite
/// @setter X
procedure SpriteSetX(s: Sprite; value: Single);
/// Returns the X position of the Sprite.
///
/// @lib
///
/// @class Sprite
/// @getter X
function SpriteX(s: Sprite): Single;
/// Sets the Y position of the Sprite.
///
/// @lib
/// @sn sprite:%s setY:%s
///
/// @class Sprite
/// @setter Y
procedure SpriteSetY(s: Sprite; value: Single);
/// Returns the Y position of the Sprite.
///
/// @lib
///
/// @class Sprite
/// @getter Y
function SpriteY(s: Sprite): Single;
//---------------------------------------------------------------------------
// Sprite position
//---------------------------------------------------------------------------
/// Returns the Sprite's position.
///
/// @lib
///
/// @class Sprite
/// @getter Position
function SpritePosition(s: Sprite): Point2D;
/// Sets the Sprite's position.
///
/// @lib
/// @sn sprite:%s setPosition:%s
///
/// @class Sprite
/// @setter Position
procedure SpriteSetPosition(s: Sprite; const value: Point2D);
//---------------------------------------------------------------------------
// Sprite DX,DY
//---------------------------------------------------------------------------
/// Sets the X value of the Sprite's velocity.
///
/// @lib
/// @sn sprite:%s setDX:%s
///
/// @class Sprite
/// @setter DX
procedure SpriteSetDX(s: Sprite; value: Single);
/// Returns the X value of the Sprite's velocity.
///
/// @lib
///
/// @class Sprite
/// @getter DX
function SpriteDX(s: Sprite): Single;
/// Sets the Y value of the Sprite's velocity.
///
/// @lib
/// @sn sprite:%s setDY:%s
///
/// @class Sprite
/// @setter DY
procedure SpriteSetDY(s: Sprite; value: Single);
/// Returns the Y value of the Sprite's velocity.
///
/// @lib
///
/// @class Sprite
/// @getter DY
function SpriteDY(s: Sprite): Single;
//---------------------------------------------------------------------------
// Sprite speed and heading
//---------------------------------------------------------------------------
/// Returns the current speed (distance travelled per update) of the Sprite.
///
/// @lib
///
/// @class Sprite
/// @getter Speed
function SpriteSpeed(s: Sprite): Single;
/// Alters the speed of the Sprite without effecting the direction.
///
/// @lib
/// @sn sprite:%s setSpeed:%s
///
/// @class Sprite
/// @setter Speed
procedure SpriteSetSpeed(s: Sprite; value: Single);
/// Returns the direction the Sprite is heading in degrees.
///
/// @lib
///
/// @class Sprite
/// @getter Heading
function SpriteHeading(s: Sprite): Single;
/// Alters the direction the Sprite is heading without changing the speed.
///
/// @lib
/// @sn sprite:%s setHeading:%s
///
/// @class Sprite
/// @setter Heading
procedure SpriteSetHeading(s: Sprite; value: Single);
//---------------------------------------------------------------------------
// Sprite Current Frame
//---------------------------------------------------------------------------
/// Returns the current animation cell for an Animated Sprite. The cell is
/// updated when the sprite's animation data is updated.
///
/// @lib
///
/// @class Sprite
/// @getter CurrentCell
function SpriteCurrentCell(s: Sprite): Longint;
//---------------------------------------------------------------------------
// Sprite collision details
//---------------------------------------------------------------------------
/// Returns the bitmap used by the Sprite to determine if it has collided with
/// other objects in the game.
///
/// @lib
///
/// @class Sprite
/// @getter CollisionBitmap
function SpriteCollisionBitmap(s: Sprite): Bitmap;
/// Sets the bitmap used by the Sprite to determine if it has collided with
/// other objects in the game. By default the CollisionBitmap is set to the
/// bitmap from the Sprite's first layer.
///
/// @lib
/// @sn sprite:%s setCollisionBitmap:%s
///
/// @class Sprite
/// @setter CollisionBitmap
procedure SpriteSetCollisionBitmap(s: Sprite; bmp: Bitmap);
/// Returns the kind of collision used with this Sprite. This is used when
/// determining if the Sprite has collided with other objects in the game.
///
/// @lib
///
/// @class Sprite
/// @getter CollisionKind
function SpriteCollisionKind(s: Sprite): CollisionTestKind;
/// Sets the kind of collision used with this Sprite. This is used when
/// determining if the Sprite has collided with other objects in the game.
///
/// @lib
/// @sn sprite:%s setCollisionKind:%s
///
/// @class Sprite
/// @setter CollisionKind
procedure SpriteSetCollisionKind(s: Sprite; value: CollisionTestKind);
//---------------------------------------------------------------------------
// Sprite mass
//---------------------------------------------------------------------------
/// This indicates the mass of the Sprite for any of the collide methods from
/// Physics. The mass of two colliding sprites will determine the relative
/// velocitys after the collision.
///
/// @lib
///
/// @class Sprite
/// @getter Mass
function SpriteMass(s: Sprite): Single;
/// Allows you to change the mass of a Sprite.
///
/// @lib
/// @sn sprite:%s sestMass:%s
///
/// @class Sprite
/// @setter Mass
procedure SpriteSetMass(s: Sprite; value: Single);
//---------------------------------------------------------------------------
// Sprite rotation
//---------------------------------------------------------------------------
/// This indicates the angle of rotation of the Sprite. This will rotate any
/// images of the sprite before drawing, which can be very slow. Avoid using
/// this method with bitmap based Sprites where possible.
///
/// @lib
///
/// @class Sprite
/// @getter Rotation
function SpriteRotation(s: Sprite): Single;
/// Allows you to change the rotation of a Sprite.
///
/// @lib
/// @sn sprite:%s setRotation:%s
///
/// @class Sprite
/// @setter Rotation
procedure SpriteSetRotation(s: Sprite; value: Single);
//---------------------------------------------------------------------------
// Sprite scale
//---------------------------------------------------------------------------
/// This indicates the scale of the Sprite. This will scale any
/// images of the sprite before drawing, which can be very slow. Avoid using
/// this method with bitmap based Sprites where possible.
///
/// @lib
/// @class Sprite
/// @getter Scale
function SpriteScale(s: Sprite): Single;
/// Allows you to change the scale of a Sprite.
///
/// @lib
/// @sn sprite:%s setScale:%s
///
/// @class Sprite
/// @setter Scale
procedure SpriteSetScale(s: Sprite; value: Single);
//---------------------------------------------------------------------------
// Sprite value code
//---------------------------------------------------------------------------
/// Returns the count of sprite's values.
///
/// @lib
///
/// @class Sprite
/// @getter ValueCount
function SpriteValueCount(s: Sprite) : Longint;
/// Returns the names of all of the values of the sprite
///
/// @lib
///
/// @class Sprite
/// @method ValueNameAt
function SpriteValueName(s: Sprite; idx: Longint): String;
/// Returns the sprite's value at the index specified
///
/// @lib
/// @sn sprite:%s valueAt:%s
///
/// @class Sprite
/// @overload Value ValueAt
function SpriteValue(s: Sprite; index: Longint): Single; overload;
/// Returns the indicated value of the sprite
///
/// @lib SpriteValueNamed
/// @sn sprite:%s valueOf:%s
///
/// @class Sprite
/// @method Value
function SpriteValue(s: Sprite; const name: String): Single; overload;
/// Adds a new kind of value to the Sprite
///
/// @lib SpriteAddValue
/// @sn sprite:%s addValue:%s
///
/// @class Sprite
/// @method AddValue
procedure SpriteAddValue(s: Sprite; const name: String);
/// Adds a new kind of value to the Sprite, setting the initial value
/// to the value passed in.
///
/// @lib SpriteAddValueWithInitialValue
/// @sn sprite:%s addValue:%s initally:%s
///
/// @class Sprite
/// @overload AddValue AddValueWithDefault
/// @csn addValue:%s initally:%s
procedure SpriteAddValue(s: Sprite; const name: String; initVal: Single);
/// Assigns a value to the Sprite.
///
/// @lib SpriteSetValueNamed
/// @sn sprite:%s setValueNamed:%s to:%s
///
/// @class Sprite
/// @overload SetValue SetValueNamed
/// @csn setValueNamed:%s to:%s
procedure SpriteSetValue(s: Sprite; const name: String; val: Single); overload;
/// Assigns a value to the Sprite.
///
/// @lib SpriteSetValue
/// @sn sprite:%s setValue:%s to:%s
///
/// @class Sprite
/// @method SetValue
/// @csn setValue:%s to:%s
procedure SpriteSetValue(s: Sprite; idx: Longint; val: Single); overload;
//---------------------------------------------------------------------------
// Sprite name
//---------------------------------------------------------------------------
/// Returns the name of the sprite. This name is used for resource management
/// and can be used to interact with the sprite in various routines.
///
/// @lib SpriteName
///
/// @class Sprite
/// @getter Name
function SpriteName(sprt: Sprite): String;
//---------------------------------------------------------------------------
// Sprite Packs
//---------------------------------------------------------------------------
/// Draws all of the sprites in the current Sprite pack. Packs can be
/// switched to select between different sets of sprites.
///
/// @lib
procedure DrawAllSprites();
/// Update all of the sprites in the current Sprite pack.
///
/// @lib
procedure UpdateAllSprites(); overload;
/// Update all of the sprites in the current Sprite pack, passing in a
/// percentage value to indicate the percentage to update.
///
/// @lib UpdateAllSpritesPct
procedure UpdateAllSprites(pct: Single); overload;
/// Call the supplied function for all sprites.
///
/// @lib
procedure CallForAllSprites(fn: SpriteFunction);
/// Create a new SpritePack with a given name. This pack can then be
/// selected and used to control which sprites are drawn/updated in
/// the calls to DrawAllSprites and UpdateAllSprites.
///
/// @lib
procedure CreateSpritePack(const name: String);
/// Indicates if a given SpritePack has already been created.
///
/// @lib
function HasSpritePack(const name: String): Boolean;
/// Selects the named SpritePack (if it has been created). The
/// selected SpritePack determines which sprites are drawn and updated
/// with the DrawAllSprites and UpdateAllSprites code.
///
/// @lib
procedure SelectSpritePack(const name: String);
/// Returns the name of the currently selected SpritePack.
///
/// @lib
function CurrentSpritePack(): String;
//=============================================================================
implementation
uses
Classes, SysUtils, Math, // System
stringhash, sgBackendTypes,
sgNamedIndexCollection, SpritePack, //libsrc
sgAnimations, sgGraphics, sgGeometry, sgPhysics, sgInput, sgCamera, sgShared, sgResources, sgImages, sgTrace, sgTimers, sgDrawingOptions; //SwinGame
//=============================================================================
var
_GlobalSpriteEventHandlers: array of SpriteEventHandler;
_Sprites: TStringHash;
_SpritePacks: TStringHash;
_spriteTimer: Timer;
_CurrentPack: TSpritePack;
const
MASS_IDX = 0; // The index of the sprite's mass value
ROTATION_IDX = 1; // The index of the sprite's rotation value
SCALE_IDX = 2; // The index of the sprite's scale value
// WIDTH_IDX = 3; // The index of the sprite's width value
// HEIGHT_IDX = 4; // The index of the sprite's height value
//-----------------------------------------------------------------------------
// Event Utility Code
//-----------------------------------------------------------------------------
//
// Loop through all event listeners and notify them of the event
//
procedure SpriteRaiseEvent(s: Sprite; evt: SpriteEventKind);
var
i: Integer;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
// this sprite's event handlers
for i := 0 to High(sp^.evts) do
begin
SpriteEventHandler(sp^.evts[i])(s, evt);
end;
// global sprite event handlers
for i := 0 to High(_GlobalSpriteEventHandlers) do
begin
SpriteEventHandler(_GlobalSpriteEventHandlers[i])(s, evt);
end;
end;
//-----------------------------------------------------------------------------
// ...
//-----------------------------------------------------------------------------
function VectorFromTo(s1, s2: Sprite): Vector;
begin
result := VectorFromPoints(CenterPoint(s1), CenterPoint(s2));
end;
function VectorFromCenterSpriteToPoint(s: Sprite; const pt: Point2D): Vector;
begin
result := VectorFromPoints(CenterPoint(s), pt);
end;
function CreateSprite(layer: Bitmap): Sprite; overload;
begin
result := CreateSprite(layer, AnimationScript(nil));
end;
function CreateSprite(const bitmapName, animationName: String): Sprite; overload;
begin
result := CreateSprite(BitmapNamed(bitmapName), AnimationScriptNamed(animationName));
end;
function CreateSprite(layer: Bitmap; ani: AnimationScript): Sprite; overload;
begin
result := CreateSprite('Sprite', layer, ani);
end;
function CreateSprite(const name: String; layer: Bitmap): Sprite; overload;
begin
result := CreateSprite(name, layer, nil);
end;
function CreateSprite(const name: String; layer: Bitmap; ani: AnimationScript): Sprite; overload;
var
sn: String;
idx: Longint;
obj: tResourceContainer;
sp: SpritePtr;
layerNames: StringArray;
begin
result := nil;
// Find a unique name for this sprite
idx := 0;
sn := name;
while HasSprite(sn) do
begin
sn := name + IntToStr(idx);
idx += 1;
end;
SetLength(layerNames, 1);
layerNames[0] := 'BaseLayer';
//Allocate the space for the sprite
New(sp);
sp^.id := SPRITE_PTR;
sp^.name := sn;
//Set lengths of the layer arrays
SetLength(sp^.layers, 1);
SetLength(sp^.layerOffsets, 1);
sp^.layers[0] := layer;
sp^.layerOffsets[0] := PointAt(0,0);
sp^.anchorPoint := PointAt(BitmapWidth(layer) / 2, BitmapHeight(layer) / 2);
sp^.positionAtAnchorPoint := false;
// Setup the layer name <-> id mapping
InitNamedIndexCollection(sp^.layerIds, layerNames);
// Set the first layer as visible.
SetLength(sp^.visibleLayers, 1);
sp^.visibleLayers[0] := 0; //The first layer (at idx 0) is drawn
// Setup the values
SetLength(sp^.values, 3);
InitNamedIndexCollection(sp^.valueIds);
AddName(sp^.valueIds, 'mass'); //idx 0 = mass, default to 1
sp^.values[MASS_IDX] := 1;
AddName(sp^.valueIds, 'rotation'); //idx 1 = rotation, default to 0
sp^.values[ROTATION_IDX] := 0;
AddName(sp^.valueIds, 'scale'); //idx 2 = scale, default to 1
sp^.values[SCALE_IDX] := 1;
// Position the sprite
sp^.position := PointAt(0,0);
// Initialise sprite movement
sp^.velocity := VectorTo(0,0);
// Setup animation detials
sp^.animationScript := ani;
sp^.animationInfo := nil;
// Setup collision details
sp^.collisionKind := PixelCollisions;
sp^.collisionBitmap := sp^.layers[0];
// Event details
sp^.announcedAnimationEnd := false;
sp^.isMoving := false;
sp^.destination := PointAt(0,0);
sp^.movingVec := VectorTo(0,0);
sp^.arriveInSec := 0;
sp^.lastUpdate := TimerTicks(_spriteTimer);
SetLength(sp^.evts, 0);
// Register in _Sprites
obj := tResourceContainer.Create(sp);
// WriteLn('Adding for ', name, ' ', HexStr(obj));
if not _Sprites.setValue(sn, obj) then
begin
RaiseWarning('** Leaking: Caused by loading Sprite created twice, ' + sn);
result := nil;
exit;
end;
sp^.pack := _CurrentPack;
_CurrentPack.AddSprite(sp);
result := sp;
end;
function HasSprite(const name: String): Boolean;
begin
result := _Sprites.containsKey(name);
end;
function SpriteNamed(const name: String): Sprite;
var
tmp : TObject;
begin
tmp := _Sprites.values[name];
if Assigned(tmp) then
result := Sprite(tResourceContainer(tmp).Resource)
else
result := nil;
end;
procedure ReleaseSprite(const name: String);
var
sprt: Sprite;
begin
{$IFDEF TRACE}
TraceEnter('sgSprites', 'ReleaseSprite', 'name = ' + name);
{$ENDIF}
sprt := SpriteNamed(name);
if (Assigned(sprt)) then
begin
FreeSprite(sprt);
end;
{$IFDEF TRACE}
TraceExit('sgSprites', 'ReleaseSprite');
{$ENDIF}
end;
procedure ReleaseAllSprites();
begin
ReleaseAll(_Sprites, @ReleaseSprite);
end;
procedure FreeSprite(var s : Sprite);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
// Free arrays
SetLength(sp^.layers, 0);
SetLength(sp^.visibleLayers, 0);
SetLength(sp^.values, 0);
SetLength(sp^.layerOffsets, 0);
// Free the name <-> id maps
FreeNamedIndexCollection(sp^.layerIds);
FreeNamedIndexCollection(sp^.valueIds);
// Free pointers
FreeAnimation(sp^.animationInfo);
// Nil pointers to resources managed by sgResources
sp^.animationScript := nil;
//Free buffered rotation image
sp^.collisionBitmap := nil;
TSpritePack(sp^.pack).RemoveSprite(s);
// Remove from hashtable
// WriteLn('Freeing Sprite named: ', s^.name);
_Sprites.remove(sp^.name).Free();
//Dispose sprite
CallFreeNotifier(s);
sp^.id := NONE_PTR;
Dispose(sp);
end;
s := nil;
end;
function SpriteAddLayer(s: Sprite; newLayer: Bitmap; const layerName: String): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if newLayer = nil then begin RaiseWarning('Cannot add non-existing bitmap as layer to Sprite'); exit; end;
if sp = nil then begin RaiseWarning('No sprite to add layer to'); exit; end;
result := AddName(sp^.layerIds, layerName);
if (result <> Length(sp^.layers)) then begin RaiseException('Error adding layer ' + layerName); exit; end;
//Resize the array
SetLength(sp^.layers, Length(sp^.layers) + 1);
SetLength(sp^.layerOffsets, Length(sp^.layerOffsets) + 1);
//Add the values to the array
sp^.layers[result] := newLayer;
sp^.layerOffsets[result] := PointAt(0,0);
end;
procedure SpriteReplayAnimation(s: Sprite);
begin
SpriteReplayAnimation(s, true);
end;
procedure SpriteReplayAnimation(s: Sprite; withSound: Boolean);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if sp = nil then exit;
RestartAnimation(sp^.animationInfo, withSound);
if not SpriteAnimationHasEnded(s) then sp^.announcedAnimationEnd := false;
end;
procedure SpriteStartAnimation(s: Sprite; const named: String);
begin
SpriteStartAnimation(s, named, true);
end;
procedure SpriteStartAnimation(s: Sprite; const named: String; withSound: Boolean);
var
idx: Integer;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
if not Assigned(sp^.animationScript) then exit;
idx := AnimationIndex(sp^.animationScript, named);
if (idx < 0) or (idx >= AnimationCount(sp^.animationScript)) then
begin
RaiseWarning('Unable to create animation "' + named + '" for sprite ' + sp^.name + ' from script ' + AnimationScriptName(sp^.animationScript));
exit;
end;
SpriteStartAnimation(s, idx, withSound);
end;
procedure SpriteStartAnimation(s: Sprite; idx: Longint);
begin
SpriteStartAnimation(s, idx, true);
end;
procedure SpriteStartAnimation(s: Sprite; idx: Longint; withSound: Boolean);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
if not Assigned(sp^.animationScript) then exit;
if (idx < 0) or (idx >= AnimationCount(sp^.animationScript)) then
begin
RaiseWarning('Unable to create animation no. ' + IntToStr(idx) + ' for sprite ' + sp^.name + ' from script ' + AnimationScriptName(sp^.animationScript));
exit;
end;
if Assigned(sp^.animationInfo) then
AssignAnimation(sp^.animationInfo, idx, sp^.animationScript, withSound)
else
sp^.animationInfo := CreateAnimation(idx, sp^.animationScript, withSound);
if not SpriteAnimationHasEnded(s) then sp^.announcedAnimationEnd := false;
// WriteLn('Sprite Animation: ', HexStr(sp^.animationInfo));
end;
function SpriteAnimationName(s: Sprite): String;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then result := AnimationName(sp^.animationInfo)
else result := '';
end;
procedure UpdateSpriteAnimation(s: Sprite); overload;
begin
UpdateSpriteAnimation(s, 1.0, true);
end;
procedure UpdateSpriteAnimation(s: Sprite; withSound: Boolean); overload;
begin
UpdateSpriteAnimation(s, 1.0, withSound);
end;
procedure UpdateSpriteAnimation(s: Sprite; pct: Single); overload;
begin
UpdateSpriteAnimation(s, pct, true);
end;
procedure UpdateSpriteAnimation(s: Sprite; pct: Single; withSound: Boolean); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
UpdateAnimation(sp^.animationInfo, pct, withSound);
// WriteLn('Move ', PointToString(AnimationCurrentVector(s^.animationInfo)), ' ', pct);
MoveSprite(s, AnimationCurrentVector(sp^.animationInfo), pct);
end;
procedure UpdateSprite(s: Sprite); overload;
begin
UpdateSprite(s, 1.0, true);
end;
procedure UpdateSprite(s: Sprite; withSound: Boolean); overload;
begin
UpdateSprite(s, 1.0, withSound);
end;
procedure UpdateSprite(s: Sprite; pct: Single); overload;
begin
UpdateSprite(s, pct, true);
end;
procedure UpdateSprite(s: Sprite; pct: Single; withSound: Boolean); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
MoveSprite(s, pct);
UpdateSpriteAnimation(s, pct, withSound);
{$IFDEF IOS}
if MouseClicked(LeftButton) and CircleCircleCollision(SpriteCollisionCircle(s), CircleAt(MouseX(), MouseY(), 17)) then
begin
SpriteRaiseEvent(s, SpriteTouchedEvent);
end;
{$ELSE}
if MouseClicked(LeftButton) and CircleCircleCollision(SpriteCollisionCircle(s), CircleAt(MouseX(), MouseY(), 1)) then
begin
SpriteRaiseEvent(s, SpriteClickedEvent);
end;
{$ENDIF}
if SpriteAnimationHasEnded(s) and (not sp^.announcedAnimationEnd) then
begin
sp^.announcedAnimationEnd := true;
SpriteRaiseEvent(s, SpriteAnimationEndedEvent);
end;
end;
end;
procedure DrawSprite(s: Sprite); overload;
begin
DrawSprite(s, 0, 0);
end;
procedure DrawSprite(s : Sprite; const position: Point2D); overload;
begin
DrawSprite(s, Round(position.x), Round(position.y));
end;
procedure DrawSprite(s: Sprite; xOffset, yOffset: Longint); overload;
var
i, idx: Longint;
angle, scale: Single;
sp: SpritePtr;
opts: DrawingOptions;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
angle := SpriteRotation(s);
if angle <> 0 then
opts := OptionRotateBmp( angle, sp^.anchorPoint.x - SpriteLayerWidth(s, 0) / 2, sp^.anchorPoint.y - SpriteLayerHeight(s, 0) / 2 )
else
opts := OptionDefaults();
scale := SpriteScale(s);
if scale <> 1 then
opts := OptionScaleBmp( scale, scale, opts );
for i := 0 to High(sp^.visibleLayers) do
begin
idx := sp^.visibleLayers[i];
DrawCell(SpriteLayer(s, idx), SpriteCurrentCell(s),
Round(sp^.position.x + xOffset + sp^.layerOffsets[idx].x),
Round(sp^.position.y + yOffset + sp^.layerOffsets[idx].y),
opts);
end;
end;
function SpriteOffscreen(s : Sprite): Boolean;
begin
if s = nil then
result := false
else
result := not RectOnScreen(SpriteLayerRectangle(s, 0));
end;
procedure MoveSprite(s : Sprite; const distance : Vector); overload;
begin
MoveSprite(s, distance, 1.0);
end;
procedure MoveSprite(s : Sprite; const distance : Vector; pct: Single); overload;
var
mvmt: Vector;
trans: Matrix2D;
sp: SpritePtr;
angle: Single;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then begin RaiseWarning('No sprite supplied to MoveSprite'); exit; end;
angle := SpriteRotation(s);
if angle <> 0 then
begin
trans := RotationMatrix(angle);
mvmt := MatrixMultiply(trans, distance);
end
else
mvmt := distance;
sp^.position.x := sp^.position.x + (pct * mvmt.x);
sp^.position.y := sp^.position.y + (pct * mvmt.y);
if sp^.isMoving then
begin
pct := (TimerTicks(_spriteTimer) - sp^.lastUpdate) / 1000;
if pct <= 0 then exit;
sp^.lastUpdate := TimerTicks(_spriteTimer);
sp^.position.x += pct * sp^.movingVec.x;
sp^.position.y += pct * sp^.movingVec.y;
sp^.arriveInSec -= pct;
if sp^.arriveInSec <= 0 then
begin
sp^.isMoving := false;
sp^.arriveInSec := 0;
SpriteRaiseEvent(s, SpriteArrivedEvent);
end;
end;
end;
procedure MoveSpriteTo(s : Sprite; x,y : Longint);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if sp = nil then begin RaiseException('No sprite supplied'); exit; end;
sp^.position.x := x;
sp^.position.y := y;
if sp^.positionAtAnchorPoint then
sp^.position += sp^.anchorPoint;
end;
procedure MoveSprite(s: Sprite); overload;
begin
MoveSprite(s, 1.0);
end;
procedure MoveSprite(s: Sprite; pct: Single); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
MoveSprite(s, sp^.velocity, pct);
end;
function SpriteOnScreenAt(s: Sprite; x, y: Longint): Boolean; overload;
var
cellRect: Rectangle;
wx, wy: Single;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := false;
if not Assigned(sp) then exit;
wx := ToWorldX(x);
wy := ToWorldY(y);
if wy > sp^.position.y + SpriteHeight(s) then result := false
else if wy < sp^.position.y then result := false
else if wx > sp^.position.x + SpriteWidth(s) then result := false
else if wx < sp^.position.x then result := false
else if sp^.collisionKind = AABBCollisions then result := true
else
begin
cellRect := SpriteCurrentCellRectangle(s);
result := PixelDrawnAtPoint(sp^.collisionBitmap, Round(wx - sp^.position.x + cellRect.x), Round(wy - sp^.position.y + cellRect.y));
end;
end;
function SpriteOnScreenAt(s: Sprite; const pt: Point2D): Boolean; overload;
begin
result := SpriteOnScreenAt(s, Round(pt.x), Round(pt.y));
end;
function SpriteVelocity(s: Sprite): Vector;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
result := VectorTo(0,0);
exit;
end;
result := sp^.velocity;
end;
procedure SpriteSetVelocity(s: Sprite; const value: Vector);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
exit;
end;
sp^.velocity := value;
end;
procedure SpriteAddToVelocity(s: Sprite; const value: Vector);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
exit;
end;
sp^.velocity := AddVectors(sp^.velocity, value);
end;
function SpriteCurrentCellRectangle(s: Sprite): Rectangle;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if (not Assigned(sp)) then
result := RectangleFrom(0,0,0,0)
else
result := BitmapRectangleOfCell(sp^.layers[0], AnimationCurrentCell(sp^.animationInfo));
end;
function SpriteScreenRectangle(s: Sprite): Rectangle;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if (not Assigned(sp)) or (not Assigned(sp^.animationInfo)) then
result := RectangleFrom(0,0,0,0)
else
result := ToScreen(SpriteLayerRectangle(s, 0));
end;
procedure SpriteSetX(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
exit;
end;
sp^.position.x := value;
end;
function SpriteX(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
result := 0;
exit;
end;
result := sp^.position.x;
end;
procedure SpriteSetY(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
exit;
end;
sp^.position.y := value;
end;
function SpriteY(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
begin
result := 0;
exit;
end;
result := sp^.position.y;
end;
function SpriteLayer(s: Sprite; const name: String): Bitmap;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := nil
else result := SpriteLayer(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayer(s: Sprite; idx: Longint): Bitmap;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := nil
else if (idx < 0) or (idx > High(sp^.layers)) then begin result := nil; RaiseException('Sprite layer index out of range - ' + IntToStr(idx)); exit; end
else result := sp^.layers[idx];
end;
function SpriteLayerIndex(s: Sprite; const name: String): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := -1
else result := IndexOf(sp^.layerIds, name);
end;
function SpriteLayerName(s: Sprite; idx: Longint): String;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := ''
else result := NameAt(sp^.layerIds, idx);
end;
function SpriteShowLayer(s: Sprite; const name: String): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := -1
else result := SpriteShowLayer(s, IndexOf(sp^.layerIds, name));
end;
function SpriteShowLayer(s: Sprite; id: Longint): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then
result := -1
else
begin
if (id < 0) or (id > Length(sp^.layers)) then begin result := -1; RaiseWarning('Cannot show layer ' + IntToStr(id) + ' of sprite.'); exit; end;
//Scan for the current ID
result := SpriteVisibleIndexOfLayer(s, id);
if result >= 0 then exit;
//Extend layers and add index
SetLength(sp^.visibleLayers, Length(sp^.visibleLayers) + 1);
result := High(sp^.visibleLayers);
sp^.visibleLayers[result] := id;
end;
end;
procedure SpriteHideLayer(s: Sprite; const name: String);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit
else SpriteHideLayer(s, IndexOf(sp^.layerIds, name));
end;
procedure SpriteHideLayer(s: Sprite; id: Longint);
var
i, idx: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
idx := SpriteVisibleIndexOfLayer(s, id);
if idx < 0 then exit; // The layer is not shown
//Shift all later layers back over removed layer
for i := idx to High(sp^.visibleLayers) - 1 do
begin
sp^.visibleLayers[i] := sp^.visibleLayers[i + 1];
end;
//Resize the array to remove element
SetLength(sp^.visibleLayers, Length(sp^.visibleLayers) - 1);
end;
procedure SpriteToggleLayerVisible(s: Sprite; const name: String); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit
else SpriteToggleLayerVisible(s, IndexOf(sp^.layerIds, name));
end;
procedure SpriteToggleLayerVisible(s: Sprite; id: Longint); overload;
begin
if SpriteVisibleIndexOfLayer(s, id) < 0 then
SpriteShowLayer(s, id)
else
SpriteHideLayer(s, id);
end;
function SpriteLayerCount(s: Sprite): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := Length(sp^.layers);
end;
function SpriteVisibleLayerCount(s: Sprite): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := Length(sp^.visibleLayers);
end;
function SpriteVisibleLayerId(s: Sprite; idx: Longint) : Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if (not Assigned(sp)) or (idx < 0) or (idx > High(sp^.visibleLayers)) then result := -1
else result := sp^.visibleLayers[idx];
end;
function SpriteLayerOffsets(s: Sprite): Point2DArray;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then begin result := nil; exit; end;
result := sp^.layerOffsets;
end;
procedure SpriteSetLayerOffsets(s: Sprite; const values: Point2DArray);
var
i: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(s) then exit;
if not Length(values) = Length(sp^.layerOffsets) then begin RaiseException('Unable to set sprite layer offsets as lengths are not equal.'); exit; end;
for i := 0 to High(values) do
begin
sp^.layerOffsets[i] := values[i];
end;
end;
function SpriteLayerOffset(s: Sprite; const name: String): Point2D;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := PointAt(0,0)
else result := SpriteLayerOffset(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayerOffset(s: Sprite; idx: Longint): Point2D;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := PointAt(0,0)
else if (idx < 0) or (idx >= Length(sp^.layerOffsets)) then begin RaiseException('Error fetching layer offset out of range.'); result := PointAt(0,0); exit; end
else result := sp^.layerOffsets[idx];
end;
procedure SpriteSetLayerOffset(s: Sprite; const name: String; const value: Point2D);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
SpriteSetLayerOffset(s, IndexOf(sp^.layerIds, name), value);
end;
procedure SpriteSetLayerOffset(s: Sprite; idx: Longint; const value: Point2D);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
sp^.layerOffsets[idx] := value;
end;
function SpriteVisibleIndexOfLayer(s: Sprite; const name: String): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := -1
else result := SpriteVisibleIndexOfLayer(s, IndexOf(sp^.layerIds, name));
end;
function SpriteVisibleIndexOfLayer(s: Sprite; id: Longint): Longint;
var
i: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := -1;
if not Assigned(sp) then exit
else
begin
for i := 0 to High(sp^.visibleLayers) do
begin
if sp^.visibleLayers[i] = id then
begin
result := i;
exit;
end;
end;
end;
end;
function SpriteVisibleLayer(s: Sprite; idx: Longint): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := -1;
if not Assigned(sp) then exit
else result := sp^.visibleLayers[idx];
end;
procedure Swap(var val1, val2: Longint);
var
temp: Longint;
begin
temp := val1;
val1 := val2;
val2 := temp;
end;
procedure SpriteSendLayerToBack(s: Sprite; visibleLayer: Longint);
var
i: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
//Check not last or beyond in array
if (visibleLayer < 0) or (visibleLayer >= Length(sp^.visibleLayers) - 1) then exit;
// Bubble layer up
for i := visibleLayer to High(sp^.visibleLayers) - 1 do
begin
Swap(sp^.visibleLayers[i], sp^.visibleLayers[i + 1]);
end;
end;
procedure SpriteSendLayerBackward(s: Sprite; visibleLayer: Longint);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(s) then exit;
//Check not last or beyond in array
if (visibleLayer < 0) or (visibleLayer >= Length(sp^.visibleLayers) - 1) then exit;
Swap(sp^.visibleLayers[visibleLayer], sp^.visibleLayers[visibleLayer + 1]);
end;
procedure SpriteBringLayerForward(s: Sprite; visibleLayer: Longint);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
//Check not first or lower
if (visibleLayer < 1) or (visibleLayer >= Length(sp^.visibleLayers)) then exit;
Swap(sp^.visibleLayers[visibleLayer], sp^.visibleLayers[visibleLayer - 1]);
end;
procedure SpriteBringLayerToFront(s: Sprite; visibleLayer: Longint);
var
i: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(s) then exit;
//Check not last or beyond in array
if (visibleLayer < 0) or (visibleLayer >= Length(sp^.visibleLayers) - 1) then exit;
// Bubble layer down
for i := visibleLayer downto 1 do
begin
Swap(sp^.visibleLayers[i], sp^.visibleLayers[i - 1]);
end;
end;
function SpriteLayerRectangle(s: Sprite; const name: String): Rectangle; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := RectangleFrom(0,0,0,0)
else result := SpriteLayerRectangle(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
{$IFDEF TRACE}
TraceEnter('sgSprites', 'SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle', '');
{$ENDIF}
if not Assigned(sp) then result := RectangleFrom(0,0,0,0)
else result := BitmapCellRectangle(sp^.position.x + sp^.layerOffsets[idx].x, sp^.position.y + sp^.layerOffsets[idx].y, sp^.layers[idx]);
{$IFDEF TRACE}
TraceExit('sgSprites', 'SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle', '');
{$ENDIF}
end;
function SpriteCollisionRectangle(s: Sprite): Rectangle;
var
sp: SpritePtr;
pts: array [0..3] of Point2D;
cw, ch: Single;
m: Matrix2D;
minX, minY, maxX, maxY: Single;
i: Integer;
begin
sp := ToSpritePtr(s);
{$IFDEF TRACE}
TraceEnter('sgSprites', 'SpriteCollisionRectangle(s: Sprite): Rectangle', '');
{$ENDIF}
if not Assigned(s) then
result := RectangleFrom(0,0,0,0)
else if (SpriteRotation(s) = 0) and (SpriteScale(s) = 1) then
result := BitmapCellRectangle(sp^.position.x, sp^.position.y, sp^.collisionBitmap)
else
begin
cw := BitmapCellWidth(sp^.collisionBitmap);
ch := BitmapCellHeight(sp^.collisionBitmap);
pts[0] := PointAt(0, 0);
pts[1] := PointAt(0, ch - 1);
pts[2] := PointAt(cw - 1, 0);
pts[3] := PointAt(cw - 1, ch - 1);
m := SpriteLocationMatrix(s);
for i := 0 to 3 do
begin
pts[i] := MatrixMultiply(m, pts[i]);
end;
minX := pts[0].x;
maxX := pts[0].x;
minY := pts[0].y;
maxY := pts[0].y;
for i := 1 to 3 do
begin
if pts[i].x < minX then minX := pts[i].x
else if pts[i].x > maxX then maxX := pts[i].x;
if pts[i].y < minY then minY := pts[i].y
else if pts[i].y > maxY then maxY := pts[i].y;
end;
result := RectangleFrom(minX, minY, maxX - minX, maxY - minY);
end;
{$IFDEF TRACE}
TraceExit('sgSprites', 'SpriteCollisionRectangle(s: Sprite): Rectangle', '');
{$ENDIF}
end;
function SpriteCircle(s: Sprite): Circle; overload;
begin
result := SpriteLayerCircle(s, 0);
end;
function SpriteLayerCircle(s: Sprite; const name: String): Circle; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := CircleAt(0,0,0)
else result := SpriteLayerCircle(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayerCircle(s: Sprite; idx: Longint): Circle; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
{$IFDEF TRACE}
TraceEnter('sgSprites', 'SpriteLayerCircle(s: Sprite): Circle', '');
{$ENDIF}
if not Assigned(sp) then result := CircleAt(0, 0, 0)
else if (idx < 0) or (idx > High(sp^.layers)) then result := CircleAt(0,0,0)
else
begin
result := BitmapCellCircle(sp^.layers[idx], CenterPoint(s), SpriteScale(s));
end;
{$IFDEF TRACE}
TraceExit('sgSprites', 'SpriteLayerCircle(s: Sprite): Circle', '');
{$ENDIF}
end;
function SpriteCollisionCircle(s: Sprite): Circle;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
{$IFDEF TRACE}
TraceEnter('sgSprites', 'SpriteLayerCircle(s: Sprite): Circle', '');
{$ENDIF}
if (not Assigned(sp)) or (not Assigned(sp^.collisionBitmap)) then result := CircleAt(0, 0, 0)
else result := BitmapCellCircle(sp^.collisionBitmap, CenterPoint(s), SpriteScale(s));
{$IFDEF TRACE}
TraceExit('sgSprites', 'SpriteLayerCircle(s: Sprite): Circle', '');
{$ENDIF}
end;
//---------------------------------------------------------------------------
// Sprite position
//---------------------------------------------------------------------------
function SpritePosition(s: Sprite): Point2D;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := PointAt(0,0)
else result := sp^.position;
end;
procedure SpriteSetPosition(s: Sprite; const value: Point2D);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.position := value;
end;
//---------------------------------------------------------------------------
// Sprite DX,DY
//---------------------------------------------------------------------------
procedure SpriteSetDX(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.velocity.x := value;
end;
function SpriteDX(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := sp^.velocity.x;
end;
procedure SpriteSetDY(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.velocity.y := value;
end;
function SpriteDY(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := sp^.velocity.y;
end;
//---------------------------------------------------------------------------
// Sprite speed and heading
//---------------------------------------------------------------------------
function SpriteSpeed(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := VectorMagnitude(sp^.velocity);
end;
procedure SpriteSetSpeed(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.velocity := VectorMultiply(UnitVector(sp^.velocity), value);
end;
function SpriteHeading(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := VectorAngle(sp^.velocity);
end;
procedure SpriteSetHeading(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.velocity := VectorFromAngle(value, VectorMagnitude(sp^.velocity));
end;
//---------------------------------------------------------------------------
// Sprite Current cell
//---------------------------------------------------------------------------
function SpriteCurrentCell(s: Sprite): Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := -1
else result := AnimationCurrentCell(sp^.animationInfo);
end;
function SpriteAnimationHasEnded(s: Sprite): Boolean;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := false
else result := AnimationEnded(sp^.animationInfo);
end;
//---------------------------------------------------------------------------
// Sprite width/height
//---------------------------------------------------------------------------
function SpriteLayerHeight(s: Sprite; const name: String): Longint; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(s) then result := 0
else result := SpriteLayerHeight(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayerHeight(s: Sprite; idx: Longint): Longint; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else if (idx < 0) or (idx >= Length(sp^.layers)) then result := 0
else result := BitmapCellHeight(sp^.layers[idx]);
end;
function SpriteLayerWidth(s: Sprite; const name: String): Longint; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := SpriteLayerWidth(s, IndexOf(sp^.layerIds, name));
end;
function SpriteLayerWidth(s: Sprite; idx: Longint): Longint; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else if (idx < 0) or (idx >= Length(sp^.layers)) then result := 0
else result := BitmapCellWidth(sp^.layers[idx]);
end;
function SpriteWidth(s: Sprite): Longint;
begin
result := SpriteLayerWidth(s, 0);
end;
function SpriteHeight(s: Sprite): Longint;
begin
result := SpriteLayerHeight(s, 0);
end;
function SpriteAnchorPoint(s: Sprite): Point2D;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
result := sp^.anchorPoint;
end
else
begin
result := PointAt(0,0);
end;
end;
procedure SpriteSetAnchorPoint(s: Sprite; pt: Point2D);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
sp^.anchorPoint := pt;
end;
end;
function SpriteMoveFromAnchorPoint(s: Sprite): Boolean;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
result := sp^.positionAtAnchorPoint;
end
else
begin
result := false;
end;
end;
procedure SpriteSetMoveFromAnchorPoint(s: Sprite; value: Boolean);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
sp^.positionAtAnchorPoint := value;
end;
end;
//---------------------------------------------------------------------------
// Sprite mass
//---------------------------------------------------------------------------
function SpriteMass(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := sp^.values[MASS_IDX];
end;
procedure SpriteSetMass(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.values[MASS_IDX] := value;
end;
//---------------------------------------------------------------------------
// Sprite rotation
//---------------------------------------------------------------------------
function SpriteRotation(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := sp^.values[ROTATION_IDX];
end;
procedure SpriteSetRotation(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
if value < 0 then
begin
value := 360 + (value + Abs(Trunc(value / 360) * 360));
end;
if value > 360 then
begin
value := value - Trunc(value / 360) * 360;
end;
sp^.values[ROTATION_IDX] := value;
end;
end;
//---------------------------------------------------------------------------
// Sprite scale
//---------------------------------------------------------------------------
function SpriteScale(s: Sprite): Single;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := 0
else result := sp^.values[SCALE_IDX];
end;
procedure SpriteSetScale(s: Sprite; value: Single);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
sp^.values[SCALE_IDX] := value;
end;
end;
//---------------------------------------------------------------------------
// Sprite center point
//---------------------------------------------------------------------------
function CenterPoint(s: Sprite): Point2D;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
{$IFDEF TRACE}
TraceEnter('sgSprites', 'CenterPoint(s: Sprite): Point2D', '');
{$ENDIF}
if not Assigned(sp) then
begin
result := PointAt(0,0);
exit;
end;
result.x := sp^.position.x + SpriteWidth(s) / 2;
result.y := sp^.position.y + SpriteHeight(s) / 2;
{$IFDEF TRACE}
TraceExit('sgSprites', 'CenterPoint(s: Sprite): Point2D', '');
{$ENDIF}
end;
//---------------------------------------------------------------------------
// Sprite collision details
//---------------------------------------------------------------------------
function SpriteCollisionKind(s: Sprite): CollisionTestKind;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := AABBCollisions
else result := sp^.collisionKind;
end;
procedure SpriteSetCollisionKind(s: Sprite; value: CollisionTestKind);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.collisionKind := value;
end;
function SpriteCollisionBitmap(s: Sprite): Bitmap;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then result := nil
else result := sp^.collisionBitmap;
end;
procedure SpriteSetCollisionBitmap(s: Sprite; bmp: Bitmap);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then sp^.collisionBitmap := bmp;
end;
//---------------------------------------------------------------------------
// Sprite value code
//---------------------------------------------------------------------------
function SpriteValueCount(s: Sprite) : Longint;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := -1;
if not Assigned(sp) then exit;
result := NameCount(sp^.valueIds);
end;
function SpriteValueName(s: Sprite; idx: Longint) : String;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := '';
if not Assigned(sp) then exit;
result := NameAt(sp^.valueIds, idx);
end;
function SpriteValue(s: Sprite; index: Longint): Single; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := 0;
if not Assigned(sp) then exit;
result := sp^.values[index];
end;
function SpriteValue(s: Sprite; const name: String): Single; overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
result := 0;
if not Assigned(sp) then exit;
result := SpriteValue(s, IndexOf(sp^.valueIds, name));
end;
procedure SpriteAddValue(s: Sprite; const name: String);
begin
SpriteAddValue(s, name, 0);
end;
procedure SpriteAddValue(s: Sprite; const name: String; initVal: Single);
var
idx: Longint;
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
if HasName(sp^.valueIds, name) then exit;
idx := AddName(sp^.valueIds, name);
SetLength(sp^.values, Length(sp^.values) + 1);
sp^.values[idx] := initVal;
end;
procedure SpriteSetValue(s: Sprite; const name: String; val: Single); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
SpriteSetValue(s, IndexOf(sp^.valueIds, name), val);
end;
procedure SpriteSetValue(s: Sprite; idx: Longint; val: Single); overload;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not Assigned(sp) then exit;
if (idx < 0) or (idx > High(sp^.values)) then exit;
sp^.values[idx] := val;
end;
function SpriteName(sprt: Sprite): String;
var
sp: SpritePtr;
begin
sp := ToSpritePtr(sprt);
result := '';
if not Assigned(sp) then exit;
result := sp^.name;
end;
procedure SpriteMoveTo(s: Sprite; const pt: Point2D; takingSeconds: Longint);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if not assigned(sp) then exit;
sp^.destination := pt;
sp^.arriveInSec := takingSeconds;
sp^.isMoving := true;
sp^.movingVec := VectorMultiply(UnitVector(VectorFromPoints(CenterPoint(s), pt)), PointPointDistance(CenterPoint(s), pt) / takingSeconds);
sp^.lastUpdate := TimerTicks(_spriteTimer);
end;
function SpriteLocationMatrix(s: Sprite): Matrix2D;
var
scale, newX, newY, w, h: Single;
anchorMatrix: Matrix2D;
// sp: SpritePtr;
begin
result := IdentityMatrix();
// sp := ToSpritePtr(s);
// if not Assigned(sp) then exit;
scale := SpriteScale(s);
w := SpriteLayerWidth(s, 0);
h := SpriteLayerHeight(s, 0);
anchorMatrix := TranslationMatrix(SpriteAnchorPoint(s));
result := MatrixMultiply(MatrixInverse(anchorMatrix), result);
result := MatrixMultiply(RotationMatrix(SpriteRotation(s)), result);
result := MatrixMultiply(anchorMatrix, result);
newX := SpriteX(s) - (w * scale / 2.0) + (w / 2.0);
newY := SpriteY(s) - (h * scale / 2.0) + (h / 2.0);
result := MatrixMultiply(TranslationMatrix(newX / scale, newY / scale), result);
result := MatrixMultiply(ScaleMatrix(scale), result);
end;
//---------------------------------------------------------------------------
// Event Code
//---------------------------------------------------------------------------
procedure _AddSpriteEventHandler(var arr: SpriteEventHandlerArray; handler: SpriteEventHandler);
begin
if Assigned(handler) then
begin
SetLength(arr, Length(arr) + 1);
arr[High(arr)] := handler;
end;
end;
function _IndexOfSpriteEventHandler(const arr: SpriteEventHandlerArray; handler: SpriteEventHandler): Integer;
var
i: Integer;
begin
for i := 0 to High(arr) do
begin
if arr[i] = handler then
begin
result := i;
exit;
end;
end;
result := -1;
end;
procedure _RemoveSpriteEventHandler(var arr: SpriteEventHandlerArray; handler: SpriteEventHandler);
var
i, idx: Integer;
begin
idx := _IndexOfSpriteEventHandler(arr, handler);
if idx < 0 then exit;
for i := idx to High(arr) - 1 do
begin
arr[i] := arr[i + 1];
end;
SetLength(arr, Length(arr) - 1);
end;
procedure CallOnSpriteEvent(handler: SpriteEventHandler);
begin
_AddSpriteEventHandler(_GlobalSpriteEventHandlers, handler);
end;
procedure StopCallingOnSpriteEvent(handler: SpriteEventHandler);
begin
_RemoveSpriteEventHandler(_GlobalSpriteEventHandlers, handler);
end;
procedure SpriteCallOnEvent(s: Sprite; handler: SpriteEventHandler);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
_AddSpriteEventHandler(sp^.evts, handler);
end;
end;
procedure SpriteStopCallingOnEvent(s: Sprite; handler: SpriteEventHandler);
var
sp: SpritePtr;
begin
sp := ToSpritePtr(s);
if Assigned(sp) then
begin
_RemoveSpriteEventHandler(sp^.evts, handler);
end;
end;
//---------------------------------------------------------------------------
// Sprite Packs
//---------------------------------------------------------------------------
// Duplicate for the UpdateSprite for use in UpdateAllSprites... as it
// currently does not select the correct overload.
procedure _UpdateSpritePct(s: Sprite; pct: Single);
begin
UpdateSprite(s, pct);
end;
procedure DrawAllSprites();
begin
_CurrentPack.CallForAllSprites(@DrawSprite);
end;
procedure UpdateAllSprites(pct: Single); overload;
begin
_CurrentPack.CallForAllSprites(@_UpdateSpritePct, pct);
end;
procedure CallForAllSprites(fn: SpriteFunction);
begin
_CurrentPack.CallForAllSprites(fn);
end;
procedure UpdateAllSprites(); overload;
begin
UpdateAllSprites(1.0);
end;
procedure CreateSpritePack(const name: String);
begin
if not HasSpritePack(name) then
begin
_CurrentPack := TSpritePack.Create(name);
_CurrentPack.AddPackTo(_SpritePacks);
end
else
begin
RaiseWarning('The SpritePack ' + name + ' already exists');
end;
end;
function HasSpritePack(const name: String): Boolean;
begin
result := _SpritePacks.ContainsKey(name);
end;
function CurrentSpritePack(): String;
begin
result := _CurrentPack.Name;
end;
function SpritePackNamed(const name: String): TSpritePack;
begin
if HasSpritePack(name) then
result := TSpritePack(_SpritePacks.Values[name])
else
result := nil;
end;
procedure SelectSpritePack(const name: String);
begin
if HasSpritePack(name) then
begin
_CurrentPack := TSpritePack(_SpritePacks.Values[name]);
end
else
begin
RaiseWarning('No SpritePack named ' + name + ' to select.');
end;
end;
procedure ReleaseSpritePack(const name: String);
var
pack: TSpritePack;
begin
pack := SpritePackNamed(name);
if (Assigned(pack)) then
begin
FreeAndNil(pack);
end;
end;
procedure ReleaseAllSpritePacks();
begin
ReleaseAll(_SpritePacks, nil);
end;
//=============================================================================
initialization
begin
InitialiseSwinGame();
_Sprites := TStringHash.Create(False, 16384);
_SpritePacks := TStringHash.Create(False, 50);
_CurrentPack := TSpritePack.Create('Default');
_CurrentPack.AddPackTo(_SpritePacks);
// Sprite movement timer - all sprites movement is timed from this
_spriteTimer := CreateTimer('*SG* SpriteTimer');
StartTimer(_spriteTimer);
// Sprite Event Handlers
SetLength(_GlobalSpriteEventHandlers, 0);
end;
finalization
begin
ReleaseAllSprites();
ReleaseAllSpritePacks();
SetLength(_GlobalSpriteEventHandlers, 0);
FreeAndNil(_Sprites);
FreeAndNil(_SpritePacks);
end;
end. |
unit uFrLivro;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFrPadrao, Data.DB, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Buttons, Vcl.Grids,
Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, uLivroController;
type
TfrLivro = class(TfrPadrao)
edtCodigo: TLabeledEdit;
edtTitulo: TLabeledEdit;
cbxAutor: TComboBox;
lblAutor: TLabel;
cbxEditora: TComboBox;
lblEditora: TLabel;
procedure btnGravarClick(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbgPadraoDblClick(Sender: TObject);
private
FLivroController: TLivroController;
procedure LimpaCampos();
procedure IncluirRegistro();
function GravarRegistro(): Boolean;
function ExcluirRegistro(): Boolean;
procedure PesquisarRegistros();
function ValidaCampos(): Boolean;
procedure EditarRegistro();
procedure AlimentaComboAutores();
procedure AlimentaComboEditoras();
public
{ Public declarations }
end;
var
frLivro: TfrLivro;
implementation
uses uLivroModel, uAutorModel, uEditoraModel;
{$R *.dfm}
{ TfrLivro }
procedure TfrLivro.btnExcluirClick(Sender: TObject);
begin
inherited;
ExcluirRegistro();
end;
procedure TfrLivro.btnGravarClick(Sender: TObject);
begin
inherited;
GravarRegistro();
end;
procedure TfrLivro.btnIncluirClick(Sender: TObject);
begin
inherited;
IncluirRegistro();
end;
procedure TfrLivro.btnPesquisarClick(Sender: TObject);
begin
inherited;
PesquisarRegistros();
end;
procedure TfrLivro.AlimentaComboAutores;
begin
FLivroController.AlimentaComboAutores(cbxAutor);
end;
procedure TfrLivro.AlimentaComboEditoras;
begin
FLivroController.AlimentaComboEditoras(cbxEditora);
end;
procedure TfrLivro.dbgPadraoDblClick(Sender: TObject);
begin
inherited;
EditarRegistro();
end;
procedure TfrLivro.EditarRegistro;
begin
if not (qryPadrao.FieldByName('codigo').AsInteger > 0) then
Exit;
edtCodigo.Text := qryPadrao.FieldByName('codigo').AsString;
edtTitulo.Text := qryPadrao.FieldByName('titulo').AsString;
cbxAutor.ItemIndex := cbxAutor.Items.IndexOfObject(
FLivroController.RetornaObjetoAutor(qryPadrao.FieldByName('autor_codigo').AsInteger));
cbxEditora.ItemIndex := cbxEditora.Items.IndexOfObject(
FLivroController.RetornaObjetoEditora(qryPadrao.FieldByName('editora_codigo').AsInteger));
pgcPadrao.TabIndex := 1;
AjustaVisibilidadeBotoes();
end;
function TfrLivro.ExcluirRegistro: Boolean;
begin
FLivroController.frMain := frMain;
FLivroController.ExcluirRegistro(qryPadrao.FieldByName('CODIGO').AsInteger);
PesquisarRegistros();
end;
procedure TfrLivro.FormCreate(Sender: TObject);
begin
inherited;
FLivroController := TLivroController.Create;
end;
procedure TfrLivro.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FLivroController);
end;
procedure TfrLivro.FormShow(Sender: TObject);
begin
inherited;
AlimentaComboAutores();
AlimentaComboEditoras();
PesquisarRegistros();
end;
function TfrLivro.GravarRegistro: Boolean;
var LLivro: TLivroModel;
begin
if not ValidaCampos() then
Exit;
LLivro := TLivroModel.Create;
try
LLivro.Codigo := StrToIntDef(edtCodigo.Text,0);
LLivro.Titulo := edtTitulo.Text;
LLivro.Autor := TAutorModel(cbxAutor.Items.Objects[cbxAutor.ItemIndex]);
LLivro.Editora := TEditoraModel(cbxEditora.Items.Objects[cbxEditora.ItemIndex]);
FLivroController.frMain := frMain;
if FLivroController.GravarRegistro(LLivro) then
begin
LimpaCampos();
ShowMessage('Registro incluído com sucesso.');
end;
finally
FreeAndNil(LLivro);
end;
end;
procedure TfrLivro.IncluirRegistro;
begin
LimpaCampos();
end;
procedure TfrLivro.LimpaCampos;
begin
edtCodigo.Text := '';
edtTitulo.Text := '';
if cbxAutor.Items.Count > 0 then
cbxAutor.ItemIndex := 0;
if cbxEditora.Items.Count > 0 then
cbxEditora.ItemIndex := 0;
end;
procedure TfrLivro.PesquisarRegistros;
var LSQL: String;
LPesquisaComFiltro: Boolean;
begin
LSQL :=
'SELECT * FROM LIVRO ';
LPesquisaComFiltro := Trim(edtPesquisar.Text) <> '';
if LPesquisaComFiltro then
LSQL := LSQL + 'WHERE UPPER(TITULO) LIKE UPPER(:titulo)';
if qryPadrao.Active then
qryPadrao.Close;
qryPadrao.SQL.Text := LSQL;
if LPesquisaComFiltro then
qryPadrao.ParamByName('titulo').AsString := '%' + edtPesquisar.Text + '%';
qryPadrao.Open;
end;
function TfrLivro.ValidaCampos: Boolean;
var LCamposPreechidos: Boolean;
begin
LCamposPreechidos :=
(Trim(edtTitulo.Text) <> '') and
(cbxAutor.ItemIndex >= 0) and
(cbxEditora.ItemIndex >= 0);
if not (Trim(edtTitulo.Text) <> '') then
ShowMessage('Preencha o campo título');
if not (cbxAutor.ItemIndex >= 0) then
ShowMessage('Preencha o campo autor');
if not (cbxEditora.ItemIndex >= 0) then
ShowMessage('Preencha o campo editora');
Result := LCamposPreechidos;
end;
end.
|
program GameMain;
uses SwinGame, sgTypes;
procedure Main();
begin
OpenGraphicsWindow('Hello World', 800, 600);
ShowSwinGameSplashScreen();
repeat // The game loop...
ProcessEvents();
ClearScreen(ColorWhite);
DrawFramerate(0,0);
RefreshScreen(60);
until WindowCloseRequested();
end;
begin
Main();
end.
|
unit feedInstagram;
interface
uses eaterReg;
type
TInstagramFeedProcessor=class(TFeedProcessor)
public
function Determine(Store:IFeedStore;const FeedURL:WideString;
var FeedData:WideString;const FeedDataType:WideString):boolean; override;
procedure ProcessFeed(Handler:IFeedHandler;const FeedData:WideString); override;
end;
implementation
uses Windows, SysUtils, ComObj, ActiveX, Variants, jsonDoc, MSXML2_TLB,
eaterUtils, eaterSanitize, VBScript_RegExp_55_TLB;
const
Base64Codes:array[0..63] of AnsiChar=
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function Base64Encode(const x:UTF8String):UTF8String;
var
i,j,l:cardinal;
begin
l:=Length(x);
i:=(l div 3);
if (l mod 3)<>0 then inc(i);
SetLength(Result,i*4);
i:=1;
j:=0;
while (i+2<=l) do
begin
inc(j);Result[j]:=Base64Codes[ byte(x[i ]) shr 2];
inc(j);Result[j]:=Base64Codes[((byte(x[i ]) and $03) shl 4)
or (byte(x[i+1]) shr 4)];
inc(j);Result[j]:=Base64Codes[((byte(x[i+1]) and $0F) shl 2)
or (byte(x[i+2]) shr 6)];
inc(j);Result[j]:=Base64Codes[ byte(x[i+2]) and $3F];
inc(i,3);
end;
if i=l then
begin
inc(j);Result[j]:=Base64Codes[ byte(x[i ]) shr 2];
inc(j);Result[j]:=Base64Codes[((byte(x[i ]) and $03) shl 4)];
inc(j);Result[j]:='=';
inc(j);Result[j]:='=';
end
else if i+1=l then
begin
inc(j);Result[j]:=Base64Codes[ byte(x[i ]) shr 2];
inc(j);Result[j]:=Base64Codes[((byte(x[i ]) and $03) shl 4)
or (byte(x[i+1]) shr 4)];
inc(j);Result[j]:=Base64Codes[((byte(x[i+1]) and $0F) shl 2)];
inc(j);Result[j]:='=';
end;
end;
function Base64EncodeStream_JPEG(const s:IStream):UTF8String;
var
d:UTF8String;
i,j:integer;
l:FixedUInt;
//p:TJPEGImage;
//m:TMemoryStream;
begin
i:=1;
j:=0;
l:=1;
while l<>0 do
begin
inc(j,$10000);
SetLength(d,j);
OleCheck(s.Read(@d[i],$10000,@l));
inc(i,l);
end;
SetLength(d,i-1);
{
m:=TMemoryStream.Create;
try
m.Write(d[1],Length(d));
m.Position:=0;
p:=TJPEGImage.Create;
try
p.LoadFromStream(m);
p.DIBNeeded;
//???
p.CompressionQuality:=75;
p.Compress;
m.Size:=0;
p.SaveToStream(m);
finally
p.Free;
end;
m.Position:=0;
SetLength(d,m.Size);
//Move(m.Memory^,d[1],m.Size);
m.Read(d[1],m.Size);
finally
m.Free;
end;
}
Result:=Base64Encode(d);
end;
function ImageDataURL(const ImgURL:string):string;
var
r:ServerXMLHTTP60;
begin
r:=CoServerXMLHTTP60.Create;
r.open('GET',ImgURL,false,EmptyParam,EmptyParam);
r.send(EmptyParam);
//if r.status<>200 then raise?
Result:='data:image/jpeg;base64,'+
UTF8ToWideString(Base64EncodeStream_JPEG(IUnknown(r.responseStream) as IStream));
end;
{ TInstagramFeedProcessor }
function TInstagramFeedProcessor.Determine(Store:IFeedStore;const FeedURL:WideString;
var FeedData:WideString;const FeedDataType:WideString):boolean;
begin
//see also feed load: FFeed.LastMod='profile_id:'+
Result:=(StartsWith(FeedURL,'https://www.instagram.com/') or
StartsWith(FeedURL,'https://instagram.com/'));
//assert FeedDataType='application/json'
end;
procedure TInstagramFeedProcessor.ProcessFeed(Handler: IFeedHandler;
const FeedData: WideString);
var
jnodes,jcaption,jthumbs,jlinks,jchildren:IJSONDocArray;
jdoc,jdoc1,jd1,jn0,jn1,jc0,jc1:IJSONDocument;
i,j:integer;
itemid,itemurl,s:string;
pubDate:TDateTime;
title,content:WideString;
r1,r2:RegExp;
begin
jnodes:=JSONDocArray;
jdoc:=JSON(['user{'
,'edge_felix_video_timeline{','edges',jnodes,'}'
,'edge_owner_to_timeline_media{','edges',jnodes,'}'
,'edge_saved_media{','edges',jnodes,'}'
,'edge_media_collections{','edges',jnodes,'}'
]);
jdoc1:=JSON(['data',jdoc]);
try
jdoc1.Parse(FeedData);
except
on EJSONDecodeException do
;//ignore "data past end"
end;
jcaption:=JSONDocArray;
jthumbs:=JSONDocArray;
jlinks:=JSONDocArray;
jchildren:=JSONDocArray;
jn1:=JSON(
['edge_media_to_caption{','edges',jcaption,'}'
,'edge_media_to_tagged_user{','edges',jlinks,'}'
,'edge_sidecar_to_children{','edges',jchildren,'}'
,'display_resources',jthumbs
//,'thumbnail_resources',jthumbs
]);
jn0:=JSON(['node',jn1]);
jc1:=JSON();
jc0:=JSON(['node',jc1]);
r1:=CoRegExp.Create;
r1.Pattern:='@([^@#]+?)\b';
r1.Global:=true;
r2:=CoRegExp.Create;
r2.Pattern:='#([^@#]+?)\b';
r2.Global:=true;
for i:=0 to jnodes.Count-1 do
begin
jnodes.LoadItem(i,jn0);
itemid:=VarToStr(jn1['id']);
if itemid='' then raise Exception.Create('edge node without ID');
itemurl:='https://www.instagram.com/p/'+VarToStr(jn1['shortcode'])+'/';
pubDate:=int64(jn1['taken_at_timestamp'])/SecsPerDay+UnixDateDelta;//is UTC?
if Handler.CheckNewPost(itemid,itemurl,pubdate) then
begin
content:=VarToStr(jn1['title'])+' ';
for j:=0 to jcaption.Count-1 do
begin
jcaption.LoadItem(j,jc0);
content:=content+VarToStr(jc1['text'])+#13#10;
end;
if Length(content)<200 then title:=content else title:=Copy(content,1,99)+'...';
//TODO: SanitizeTitle?
content:=r1.Replace(r2.Replace(HTMLEncode(content)
,'<a href="https://instagram.com/explore/tags/$1/">#$1</a>')
,'<a href="https://instagram.com/$1/">@$1</a>');
//if jn1['is_video']=true then content:=#$25B6+content;
if jn1['is_video']=true then title:=#$25B6+title;
if jthumbs.Count=0 then s:='' else
//s:=VarToStr(JSON(jthumbs.GetJSON(jthumbs.Count-1))['src']);
s:=VarToStr(JSON(jthumbs.GetJSON(0))['src']);
if s='' then s:=VarToStr(jn1['display_url']);
if s='' then s:=VarToStr(jn1['thumbnail_src']);
if s<>'' then
begin
content:='<a href="'+HTMLEncodeQ(itemurl)+'"><img id="ig1" src="'
+ImageDataURL(s)+'" border="0" /></a><br />'#13#10
+content;
end;
jd1:=JSON(jn1['location']);
if jd1<>nil then
content:='<i>'+HTMLEncode(jd1['name'])+'</i><br />'#13#10+content;
content:='<p>'+content+'</p>'#13#10;
if jchildren.Count<>0 then
begin
content:=content
{+'<script>'#13#10
+'var ig1=document.getElementById("id1");'#13#10
+'</script>'#13#10}
+'<p>';
for j:=0 to jchildren.Count-1 do
begin
jchildren.LoadItem(j,jc0);
if jc1['is_video']=true then s:=#$25B6 else s:=#$25A0;
//content:=content+'<span onclick="ig1.src='''+HTMLEncode(jc1['display_url'])+''';">'+s+'</span> ';
content:=content+s;
end;
content:=content+'</p>'#13#10;
end;
//TODO: likes, views, owner?
if jlinks.Count<>0 then
begin
content:=content+'<p class="igLinks">'#13#10;
for j:=0 to jlinks.Count-1 do
begin
jlinks.LoadItem(j,jc0);
jd1:=JSON(jc1['user']);
content:=content+'<a href="https://instagram.com/'+jd1['username']
+'/" title="'+HTMLEncodeQ(jd1['full_name'])
+'"><img src="'+ImageDataURL(jd1['profile_pic_url'])
+'" alt="'+HTMLEncodeQ(jd1['full_name'])
+'" referrerpolicy="no-referrer" border="0" /></a>'#13#10;
end;
content:=content+'</p>'#13#10;
end;
Handler.RegisterPost(title,content);
end;
end;
Handler.ReportSuccess('Instagram');
end;
initialization
RegisterFeedProcessor(TInstagramFeedProcessor.Create);
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uThreadCompararTabelas;
interface
uses
System.Classes, uParametrosConexao, Vcl.ComCtrls, Vcl.StdCtrls,
FireDAC.Comp.Client, uEnum, uConexoes, IBX.IBDatabase, IBX.IBExtract;
type
TThreadCompararTabelas = class(TThread)
private
FcMsg: String;
FeTpLog: tpLog;
IBExtract: TIBExtract;
IBConection : TIBDatabase;
IBTransaction : TIBTransaction;
FnTotalTabelas: Integer;
FnTabelaAtual: Integer;
qryTabelasOrigem: TFDQuery;
qryTabelasDestino: TFDQuery;
FModelFirebird: TModelConexao;
FModelOracle: TModelConexao;
procedure Logar(eTpLog: tpLog; cMsg: String);
procedure SyncLogar;
procedure CompararTabelasOrigemXDestino;
procedure AbrirTabelasOrigem;
procedure AbrirTabelasDestino;
procedure CompararTabelas;
protected
procedure Execute; override;
public
FmeLog: TMemo;
FmeErros: TMemo;
FpbStatus: TProgressBar;
FParOracle, FParmFirebird: IParametrosConexao;
FDConOracle: TFDConnection;
FDConFireBird: TFDConnection;
constructor Create(CreateSuspended: Boolean); overload;
destructor Destroy; override;
procedure ConfigurarConexoes;
end;
implementation
uses
uLog, System.SysUtils;
{ TThreadCompararTabelas }
procedure TThreadCompararTabelas.AbrirTabelasOrigem;
begin
qryTabelasOrigem.Close;
qryTabelasOrigem.SQL.Clear;
qryTabelasOrigem.SQL.Add('SELECT RDB$RELATION_NAME AS TABELA FROM RDB$RELATIONS');
qryTabelasOrigem.SQL.Add('WHERE RDB$SYSTEM_FLAG = 0');
qryTabelasOrigem.SQL.Add('AND RDB$VIEW_SOURCE IS NULL');
qryTabelasOrigem.Open;
qryTabelasOrigem.FetchAll;
end;
procedure TThreadCompararTabelas.AbrirTabelasDestino;
begin
qryTabelasDestino.Close;
qryTabelasDestino.SQL.Clear;
qryTabelasDestino.SQL.Add('SELECT TABLE_NAME AS TABELA FROM DBA_TABLES');
qryTabelasDestino.SQL.Add('where owner = ''VIASOFT''');
qryTabelasDestino.Open;
qryTabelasDestino.FetchAll;
end;
procedure TThreadCompararTabelas.CompararTabelasOrigemXDestino;
begin
ConfigurarConexoes;
AbrirTabelasOrigem;
AbrirTabelasDestino;
CompararTabelas;
end;
procedure TThreadCompararTabelas.CompararTabelas;
begin
FnTotalTabelas := qryTabelasOrigem.RecordCount;
Logar(tplLog, ' : Comparação de tabelas ::');
qryTabelasOrigem.First;
while not qryTabelasOrigem.Eof do
begin
if not qryTabelasDestino.Locate('TABELA', qryTabelasOrigem.FieldByName('TABELA').AsString, []) then
begin
Logar(tplLog,': Tabela: ' + qryTabelasOrigem.FieldByName('TABELA').AsString + ' :: Não existe no destino');
//IBExtract.ExtractObject(eoTable, qryTabelasOrigem.FieldByName('TABELA').AsString, [etTable, etTrigger, etForeign, etIndex] );
//Logar(tplLog, 'SQL Da tabela: ' + IBExtract.Items.Text);
end;
qryTabelasOrigem.Next;
end;
Logar(tplLog, ' : FIM comparação de tabelas ::');
end;
procedure TThreadCompararTabelas.ConfigurarConexoes;
var
cIbCon: String;
//var
// oParOracle, oParmFirebird: IParametrosConexao;
begin
//oParmFirebird := TParametrosConexao.New('127.0.0.1', '3050', 'C:\Firebird\Migracao\AGRO_NOVO.FDB', 'SYSDBA', 'masterkey', 'FB');
//FModelFirebird := TModelConexao.Create(FParmFirebird);
//FDConFirebird := FModelFirebird.GetConexao;
// oParOracle := TParametrosConexao.New('127.0.0.1', '1521', 'LOCAL_ORCL', 'VIASOFT', 'VIASOFT', 'Ora');
//FModelOracle := TModelConexao.Create(FParOracle);
//FDConOracle := FModelOracle.GetConexao;
qryTabelasOrigem.Connection := FDConFirebird;
qryTabelasDestino.Connection := FDConOracle;
//teste para extrair o metadata das tabelas
cIbCon := FParmFirebird.GetServer + '/' + FParmFirebird.GetPorta + ':' + FParmFirebird.GetBanco;
IBConection := TIBDatabase.Create(Nil);
IBConection.DatabaseName := cIbCon;
IBConection.Params.Add('user_name='+FParmFirebird.GetUsuario);
IBConection.Params.Add('password='+FParmFirebird.GetSenha);
IBConection.Params.Add('lc_ctype=ISO8859_1');
IBConection.LoginPrompt := False;
IBConection.Connected := True;
IBTransaction := TIBTransaction.Create(Nil);
IBTransaction.DefaultDatabase := IBConection;
IBExtract := TIBExtract.Create(Nil);
IBExtract.Database := IBConection;
IBExtract.Transaction := IBTransaction;
end;
constructor TThreadCompararTabelas.Create(CreateSuspended: Boolean);
begin
inherited Create(True);
Self.FreeOnTerminate := True;
qryTabelasOrigem := TFDQuery.Create(nil);
qryTabelasDestino := TFDQuery.Create(nil);
end;
destructor TThreadCompararTabelas.Destroy;
begin
//FModelFirebird.Free;
//FModelOracle.Free;
qryTabelasOrigem.Free;
qryTabelasDestino.Free;
inherited;
end;
procedure TThreadCompararTabelas.Execute;
begin
//ConfigurarConexoes;
CompararTabelasOrigemXDestino;
end;
procedure TThreadCompararTabelas.Logar(eTpLog: tpLog; cMsg: String);
begin
FcMsg := cMsg;
FeTpLog := eTpLog;
Synchronize(SyncLogar);
end;
procedure TThreadCompararTabelas.SyncLogar;
begin
TLog.New.Logar(FcMsg);
if (FeTpLog = tplLog) then
FmeLog.Lines.Add('--' + FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg)
else if (FeTpLog = tplErro) then
FmeErros.Lines.Add('--' + FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg);
FpbStatus.Position := Round((FnTabelaAtual/FnTotalTabelas)*100);
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
(* SPELLTBL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit SpellTbl;
{-provides alternate scan table for spell checker}
{-see EDSSpell.HLP file for more information}
interface
uses
{$IFDEF Win32}
{$IFDEF Ver100}
LexLstD3;
{$ELSE}
LexLst32;
{$ENDIF}
{$ELSE}
LexLst;
{$ENDIF}
const
ScanMax = 26;
ScanTable: array[0..ScanMax - 1] of ScanStr =
('A:ED',
'B:PVN',
'C:SXV',
'D:SF',
'E:AI',
'F:DG',
'G:JFH',
'H:GJ',
'I:EUO',
'J:HK',
'K:CJL',
'L:MN',
'M:N',
'M:MB',
'O:IP',
'P:BO',
'Q:CKW',
'R:ET',
'S:CAD',
'T:RY',
'U:YI',
'V:BC',
'W:UQE',
'X:KZ',
'Y:TU',
'Z:XS');
implementation
end. { SpellTbl }
|
unit Kassensystem;
interface
uses System.SysUtils, System.Variants, ExtCtrls,
System.Classes, System.Generics.Collections, Sortiment, Kunden, Hilfsfunktionen;
type
TWarteschlange = class
private
FKundenListe : TList<TKunde>;
FWarteschlangenNummer: integer;
FIstGeoeffnet : boolean;
function getKundenAnzahl(): integer;
function getArtikelVolumen(): integer;
public
property WarteschlangenNummer: integer read FWarteschlangenNummer write FWarteschlangenNummer;
property IstGeoeffnet : boolean read FIstGeoeffnet write FIstGeoeffnet;
property KundenListe : TList<TKunde> read FKundenListe write FKundenListe;
property KundenAnzahl : integer read getKundenAnzahl;
property ArtikelVolumen : integer read getArtikelVolumen;
constructor create(WarteschlangenNummer: integer);
procedure SchlangeOeffnen();
procedure SchlangeSchliessen();
procedure EventTimer();
end;
TKasse = class
private
FKassenNummer : integer;
FKassenStatus : TKassenStatus;
FWarteschlange : TWarteschlange;
FAktuellerKunde : TKunde;
FIndexScanvorgang : integer;
FGescannteArtikel : TList<TArtikel>;
FRechnungsBetrag : double;
FKleingeldParameter: TKleingeldParameter;
procedure KassiereKunde();
procedure ScanneWare();
procedure ArtikelStornieren();
procedure NaechsterKunde();
function getKundenInSchlange(): integer;
function getRechnungsBetrag(): double;
function getOeffnungsStatus(): boolean;
public
property KassenNummer : integer read FKassenNummer write FKassenNummer;
property IstGeoffnet : boolean read getOeffnungsStatus;
property KassenStatus : TKassenStatus read FKassenStatus write FKassenStatus;
property Warteschlange : TWarteschlange read FWarteschlange write FWarteschlange;
property AktuellerKunde : TKunde read FAktuellerKunde write FAktuellerKunde;
property IndexScanvorgang : integer read FIndexScanvorgang write FIndexScanvorgang;
property KundenInSchlange : integer read getKundenInSchlange;
property KleingeldParameter: TKleingeldParameter read FKleingeldParameter
write FKleingeldParameter;
property Rechnungsbetrag : double read getRechnungsBetrag write FRechnungsBetrag;
property GescannteArtikel: TList<TArtikel> read FGescannteArtikel write FGescannteArtikel;
constructor create(KassenNummer: integer; InputWarteschlange: TWarteschlange;
KleingeldParameter: TKleingeldParameter);
procedure KasseOeffnen();
procedure KasseSchliessen();
procedure KassenTimerEvent();
end;
TKassenSystem = class
private
FKassenListe : TList<TKasse>;
FWarteschlangenListe: TList<TWarteschlange>;
FLaengsteSchlange : integer;
procedure OeffneKasse();
procedure SchliesseKasse();
procedure verwalteKassenBedarf();
procedure langsteSchlangeErmitteln();
function getWartendeKundenDurchschnitt(): double;
function getOffeneSchlangen(): double;
function getOffeneKassen(): integer;
function getWartendeKundenGesamt(): double;
function getKuerzesteWarteschlange(): integer;
public
constructor create(Parameter: TKassenParameter; KleingeldParameter: TKleingeldParameter);
property KassenListe: TList<TKasse> read FKassenListe write FKassenListe;
property WarteschlangenListe: TList<TWarteschlange> read FWarteschlangenListe
write FWarteschlangenListe;
property LaengsteSchlange: integer read FLaengsteSchlange write FLaengsteSchlange;
property WartendeKundenGesamt: double read getWartendeKundenGesamt;
property OffeneSchlangen: double read getOffeneSchlangen;
property OffeneKassen: integer read getOffeneKassen;
property WartendeKundenDurchschnitt: double read getWartendeKundenDurchschnitt;
procedure TimerEvent;
end;
implementation
{ TKasse }
/// <summary>
/// entferntden teuersten Artikel von der Rechnung
/// </summary>
procedure TKasse.ArtikelStornieren();
begin
self.GescannteArtikel.Sort;
self.GescannteArtikel.Delete(self.GescannteArtikel.Count - 1);
end;
/// <summary>Konstruktor der TKasse-Klasse</summary>
/// @param Kassennummer = Eindeutige Nummer der Kasse
/// @param InputWarteschlange = zugeordnete Warteschlange
/// @param Kleingeldparameter = record mit den Grenzwerten für den Kleingelmodus
constructor TKasse.create(KassenNummer: integer; InputWarteschlange: TWarteschlange;
KleingeldParameter: TKleingeldParameter);
begin
self.KassenNummer := KassenNummer;
self.KassenStatus := ksGeschlossen;
self.Warteschlange := InputWarteschlange;
self.KleingeldParameter := KleingeldParameter;
self.IndexScanvorgang := 0;
end;
/// <summary>Funktion zum Abfragen der Schlangenlänge</summary>
/// @return = Anzahl der Kunden in der Warteschlange
function TKasse.getKundenInSchlange: integer;
begin
result := self.Warteschlange.KundenListe.Count;
end;
/// <summary>Funktion zum Abfragen des Oeffnungsstatus</summary>
/// @return = True wenn geöffnet, sonst False
function TKasse.getOeffnungsStatus: boolean;
begin
result := not(self.KassenStatus = ksGeschlossen);
end;
/// <summary>Funktion zum ermitteln des Rechnungsbetrages</summary>
/// @return = Gesamtwert der gescannten Ware
function TKasse.getRechnungsBetrag: double;
var
i : integer;
Betrag: double;
begin
Betrag := 0;
for i := 0 to self.GescannteArtikel.Count - 1 do
Betrag := Betrag + self.GescannteArtikel[i].Wert;
result := Betrag;
end;
/// <summary>Prozedur zum Rundenbasierten Einlesen des Warenkorbes</summary>
procedure TKasse.ScanneWare();
begin
if Assigned(self.AktuellerKunde) then
begin
try
if self.IndexScanvorgang < self.AktuellerKunde.Warenkorb.ArtikelListe.Count - 1 then
begin
repeat
self.GescannteArtikel.Add(self.AktuellerKunde.Warenkorb.ArtikelListe[IndexScanvorgang]);
IndexScanvorgang := IndexScanvorgang + 1;
until ((Random(30) = 30) or
(self.IndexScanvorgang = self.AktuellerKunde.Warenkorb.ArtikelListe.Count - 1));
end
else
begin
self.KassenStatus := ksWareScannenFertig;
self.IndexScanvorgang := 0;
end;
finally
end;
end
else
self.KassenStatus := ksNaechsterKunde;
end;
/// <summary>Switch Anweisung um die aktuelle Kassenfunktion aufzurufen</summary>
procedure TKasse.KassenTimerEvent;
begin
case self.KassenStatus of
ksWareScannen:
self.ScanneWare;
ksWareScannenFertig:
self.KassiereKunde;
ksKassieren:
self.KassiereKunde;
ksKassierenFertig:
self.NaechsterKunde;
ksNaechsterKunde:
self.NaechsterKunde;
ksNaechsterKundeFertig:
self.ScanneWare;
ksBereitZumSchliessen:
self.KasseSchliessen;
end;
end;
/// <summary>Prozedur zum öffnen der Kasse und setzen des Kassenstatus</summary>
procedure TKasse.KasseOeffnen;
begin
self.Warteschlange.IstGeoeffnet := true;
self.KassenStatus := ksNaechsterKunde;
end;
/// <summary>Prozedur zum schliessen der Kasse, ist nur dann erfolgreich wenn keine Kunden anstehen</summary>
procedure TKasse.KasseSchliessen;
begin
if self.KundenInSchlange = 0 then
begin
self.KassenStatus := ksGeschlossen;
self.Warteschlange.IstGeoeffnet := false;
end;
end;
/// <summary>Prozedur zum abkassieren des aktuellen Kunden. Bei Erfolg wird der Status auf
/// ksKassierenFertig gesetzt und der Rechungsbetrag genullt</summary>
procedure TKasse.KassiereKunde();
begin
if self.Rechnungsbetrag > self.AktuellerKunde.Bargeld then
self.ArtikelStornieren;
if self.AktuellerKunde.Bezahlen(self.Rechnungsbetrag, self.KleingeldParameter) then
begin
self.Rechnungsbetrag := 0;
self.AktuellerKunde.Kundenstatus := ksZahlenFertig;
self.AktuellerKunde := nil;
self.KassenStatus := ksKassierenFertig;
self.GescannteArtikel.Free;
end;
end;
/// <summary>Prozedur zum Aufrufen des nächsten Kunden aus der Warteschlange</summary>
procedure TKasse.NaechsterKunde;
begin
self.KassenStatus := ksNaechsterKunde;
if self.KundenInSchlange > 0 then
begin
self.AktuellerKunde := self.Warteschlange.KundenListe[0];
self.GescannteArtikel := TList<TArtikel>.create;
self.Warteschlange.KundenListe.Delete(0);
self.KassenStatus := ksNaechsterKundeFertig;
end;
end;
{ TWarteschlange }
/// <summary>Konstruktor der Klasse TWarteschlange</summary>
/// @param WarteschlangenNummer = Eindeutige Nummer der Schlange
constructor TWarteschlange.create(WarteschlangenNummer: integer);
begin
self.IstGeoeffnet := false;
self.KundenListe := TList<TKunde>.create;
self.WarteschlangenNummer := WarteschlangenNummer;
end;
/// <summary>Timer Event des Warteschlangenobjekts, die Wartezeiten der Kunden
/// werden so jede Runde erhöht</summary>
procedure TWarteschlange.EventTimer;
var
i: integer;
begin
for i := 0 to self.KundenListe.Count - 1 do
begin
self.KundenListe[i].DauerWarteschlange := self.KundenListe[i].DauerWarteschlange + 1
end;
end;
function TWarteschlange.getArtikelVolumen(): integer;
var
volumen: integer;
i : integer;
begin
volumen := 0;
for i := 0 to self.KundenAnzahl - 1 do
begin
volumen := volumen + self.KundenListe[i].Warenkorb.ArtikelAnzahl;
end;
result := volumen;
end;
function TWarteschlange.getKundenAnzahl: integer;
begin
result := self.KundenListe.Count;
end;
procedure TWarteschlange.SchlangeOeffnen;
begin
self.IstGeoeffnet := true;
end;
procedure TWarteschlange.SchlangeSchliessen;
begin
self.IstGeoeffnet := false;
end;
{ TKassenVerwalter }
constructor TKassenSystem.create(Parameter: TKassenParameter;
KleingeldParameter: TKleingeldParameter);
var
i: integer;
begin
self.LaengsteSchlange := 0;
self.WarteschlangenListe := TList<TWarteschlange>.create;
for i := 0 to Parameter.AnzahlKassen - 1 do
self.WarteschlangenListe.Add(TWarteschlange.create(i));
self.KassenListe := TList<TKasse>.create;
for i := 0 to Parameter.AnzahlKassen - 1 do
self.KassenListe.Add(TKasse.create(i, self.WarteschlangenListe[i], KleingeldParameter))
end;
procedure TKassenSystem.OeffneKasse;
var
i: integer;
begin
for i := 0 to self.KassenListe.Count - 1 do
begin
if not self.KassenListe[i].IstGeoffnet or not self.WarteschlangenListe[i].IstGeoeffnet then
begin
self.KassenListe[i].KasseOeffnen;
self.WarteschlangenListe[i].SchlangeOeffnen;
exit;
end;
end;
end;
procedure TKassenSystem.SchliesseKasse;
begin
self.KassenListe[getKuerzesteWarteschlange].KasseSchliessen; { TODO -ofehler }
end;
function TKassenSystem.getWartendeKundenDurchschnitt: double;
begin
if self.WartendeKundenGesamt = 0 then
result := 0
else
result := self.WartendeKundenGesamt / self.OffeneSchlangen;
end;
function TKassenSystem.getKuerzesteWarteschlange: integer;
var
kurz : integer;
Kasse: integer;
i : integer;
begin
Kasse := 0;
kurz := 1000;
for i := 0 to self.KassenListe.Count - 1 do
begin
if self.WarteschlangenListe[i].IstGeoeffnet then
begin
if kurz > self.WarteschlangenListe[i].KundenAnzahl then
begin
kurz := self.WarteschlangenListe[i].KundenAnzahl;
Kasse := self.WarteschlangenListe[i].WarteschlangenNummer;
end;
end;
end;
result := Kasse;
end;
function TKassenSystem.getOffeneKassen: integer;
var
i : integer;
OffeneKassen: integer;
begin
OffeneKassen := 0;
for i := 0 to self.KassenListe.Count - 1 do
begin
if self.KassenListe[i].IstGeoffnet then
Inc(OffeneKassen);
end;
result := OffeneKassen;
end;
function TKassenSystem.getOffeneSchlangen: double;
var
i : integer;
OffeneSchlangen: double;
begin
OffeneSchlangen := 0;
for i := 0 to self.WarteschlangenListe.Count - 1 do
begin
if (self.WarteschlangenListe[i].IstGeoeffnet) or
(self.WarteschlangenListe[i].KundenListe.Count > 0) then
OffeneSchlangen := OffeneSchlangen + 1;
end;
result := OffeneSchlangen;
end;
function TKassenSystem.getWartendeKundenGesamt: double;
var
i : integer;
Kunden: double;
begin
Kunden := 0;
for i := 0 to self.WarteschlangenListe.Count - 1 do
if self.WarteschlangenListe[i].KundenAnzahl > 0 then
Kunden := Kunden + self.WarteschlangenListe[i].KundenAnzahl.ToDouble;
result := Kunden;
end;
procedure TKassenSystem.langsteSchlangeErmitteln;
var
i: integer;
begin
for i := 0 to self.WarteschlangenListe.Count - 1 do
if self.WarteschlangenListe[i].KundenAnzahl > self.LaengsteSchlange then
self.LaengsteSchlange := self.WarteschlangenListe[i].KundenAnzahl;
end;
procedure TKassenSystem.verwalteKassenBedarf;
begin
if (self.OffeneKassen = 0) or (self.WartendeKundenDurchschnitt > 4) then
self.OeffneKasse;
if (self.WartendeKundenDurchschnitt < 3) and (self.OffeneKassen > 1) then
self.SchliesseKasse;
end;
procedure TKassenSystem.TimerEvent;
var
i: integer;
begin
self.langsteSchlangeErmitteln;
self.verwalteKassenBedarf;
for i := 0 to self.KassenListe.Count - 1 do
self.KassenListe[i].KassenTimerEvent;
end;
end.
|
// This is universal unit containing implementation
// of basic structures on common types: trees, hashes etc...
// Copyright (C) 2002-2015 Ivan Polyacov, ivan@apus-software.com, cooler@tut.by
{$M-,H+,R-,Q-}
unit structs;
interface
uses classes,MyServis;
type
TErrorState=(
esNoError = 0,
esEmpty = 1,
esNotFound = 2,
esNoMoreItems = 3,
esOverflow = 4);
// --------------------------------------
// Structures of arbitrary items
// --------------------------------------
// Traversing modes
TraverseMode=(ChildrenFirst, // Handle children, then root (depth-search)
RootFirst, // Handle root, then children (depth-search)
byLevels); // width-search (by levels)
// Iterator for tree traverse
// depth - item's depth (distance from root, for depth-search only)
// item - TGenericTree object
TTreeIterator=procedure(depth:integer;item:TObject);
// Generic tree
TGenericTree=class
private
parent:TGenericTree;
selfIndex:integer; // index in parent's children list
children:TList;
public
data:pointer;
freeObjects:boolean; // treat data as objects and free them
preserveOrder:boolean; // true if order of children must be preserved
constructor Create(useObjects:boolean=false;useOrder:boolean=false);
destructor Destroy; override;
function GetParent:TGenericTree;
function GetIndex:integer; // return index in parent's children list
function GetChildrenCount:integer;
function GetChild(index:integer):TGenericTree;
// Add child to the end of the children list, return it's index
function AddChild(item:pointer):integer;
// Insert child item to specified position
procedure InsertChild(item:pointer;index:integer);
// Traverse this tree
procedure Traverse(mode:TraverseMode;iterator:TTreeiterator);
end;
// --------------------------------------
// Structures of comparable items
// --------------------------------------
// Base class for custom structures items
TBaseItem=class
value:integer;
function Compare(item:TBaseItem):integer; virtual;
end;
// Container with integer key
TIntItem=class(TBaseItem)
data:pointer;
constructor Create(key:integer;content:pointer);
end;
// Container with floating-point key
TFloatItem=class(TBaseItem)
value:double;
data:pointer;
constructor Create(key:double;content:pointer);
function Compare(item:TBaseItem):integer; override;
end;
// Container with string key
PString=^string;
TStrItem=class(TBaseItem)
value:PString;
data:pointer;
constructor Create(var key:string;content:pointer);
function Compare(item:TBaseItem):integer; override;
end;
THeap=class
items:array of TBaseItem;
hSize,count:integer; // can be readed: size of heap and count of elements
lastError:TErrorState; // status of the last operation
constructor Create(HeapSize:integer); // Create a new heap with given capacity
procedure Put(item:TBaseItem); // Put new item into heap
function Get:TBaseItem; // Get item from the top of the heap
destructor Destroy; override; // Destroy the heap (but not its elements if any!)
destructor ClearAndDestroy; virtual; // Destroy heap and all its elements
end;
// INCOMPLETED CODE
TTreeItem=class
weight:integer;
key:integer;
data:pointer;
left,right,parent:TTreeItem;
function Compare(item:TTreeItem):integer;
end;
TTree=class
root:TTreeItem;
constructor Create;
destructor Destroy; override;
end;
// END OF INCOMPLETED CODE
// --------------------------------------
// Hash structures
// --------------------------------------
THashItem=record
key:^string;
value:pointer;
end;
TCell=record
items:array of THashItem;
count,size:integer;
end;
// Hash String->Pointer (1:1) store pointers, DOESNT copy key strings, so this is good as auxiliary
// structure to make an existing data storage faster
TStrHash=class
Hcount,Hsize:integer;
cells:array of TCell;
LastError:TErrorState;
constructor Create;
constructor CreateSize(newsize:integer);
procedure Put(var key:string;data:pointer);
function Get(key:string):pointer;
procedure Remove(key:string);
function FirstKey:string; // Start key enumeration (no hash operation allowed)
function NextKey:string; // Fetch next key (any operation will reset enumeration)
destructor Destroy; override;
private
CurCell,CurItem:integer;
function HashValue(str:string):integer;
end;
// Another hash: string->variant(s) (1:1 or 1:n)
// Intended to STORE data, not just reference as TStrHash
// Структура не отличается офигенной скоростью, но хорошо работает в не особо критичных местах
TVariants=array of variant;
THash=object
keys:array of string;
count:integer; // number of keys (can be less than length of keys array!)
values:array of variant;
vcount:integer; // number of values (can be less than length of values array!)
constructor Init(allowMultiple:boolean=false); // or clear
procedure Put(const key:string;value:variant;replace:boolean=false);
function Get(const key:string):variant; // get value associated with the key, or Unassigned if none
function GetAll(const key:string):TVariants; // get array of values
function GetNext:variant; // get next value associated with the key, or Unassigned if none
function AllKeys:StringArr;
procedure SortKeys; // ключи без значений удаляются
private
simplemode:boolean; // простой режим - хранятся ТОЛЬКО ключи и значения, никаких ссылок и пр.
multi:boolean; // допускается несколько значений для любого ключа
// used in advanced mode
links:array of integer; // ссылки на ключи по значению хэша (голова списка)
next:array of integer; // для каждого ключа - ссылка на ключ с тем же хэшем (односвязный список)
// used in multi mode
vlinks:array of integer; // для каждого ключа - ссылка на значение
vNext:array of integer; // для каждого значения - ссылка на следующее значение, принадлежащее тому же ключу
lastIndex:integer;
hMask:integer;
function HashValue(const v:string):integer;
function Find(const key:string):integer;
procedure SwitchToAdvancedMode;
procedure AddValue(const v:variant);
procedure RemoveKey(index:integer);
procedure BuildHash;
end;
// Another hash: variant->variants
{ TVarHash=object
KeyCount:integer;
constructor Init;
procedure Add(key:variant;value:variant); // associate an item with the key
procedure Replace(key:variant;value:variant); // associate only this item with the key (can be used to clear the key)
function Get(key:variant;index:integer=0):variant; // get item for the key
function Count(key:variant):integer; // how many items are associated with the key?
function GetKey(index:integer):variant;
procedure SortKeys;
private
keys,values:array of variant;
end;}
// Simple storage of "Key->Value" pairs where both key and value are 32bit integers (or compatible)
// Returns -1 if there is no value for given key
TSimpleHash=record
keys,values:array of integer;
count:integer; // must be used instead of Length!!!
procedure Init(estimatedCount:integer);
procedure Put(key,value:integer);
function Get(key:integer):integer; // -1 if no value
function HasValue(key:integer):boolean;
procedure Remove(key:integer);
private
links:array of integer; // начало списка для каждого возможного значения хэша
next:array of integer; // номер следующей пары с таким же хэшем ключа
hMask:integer;
fFree:integer; // начало списка свободных элементов (если есть)
function HashValue(const k:integer):integer; inline;
end;
// Bit array
TBitStream=record
size:integer; // number of bits stored
procedure Init(estimatedSize:integer=1000);
procedure Put(var buf;count:integer); // append count bits to the stream
procedure Get(var buf;count:integer); // read count bits from the stream (from readPos position)
function SizeInBytes:integer; // return size of stream in bytes
private
capacity,readPos:integer;
data:array of byte;
end;
// Simple list of variants
{ TSimpleList=record
values:array of variant;
procedure Add(v:variant);
end;}
implementation
uses SysUtils,variants;
{ constructor TVarHash.Init;
begin
KeyCount:=0;
SetLength(keys,100);
SetLength(values,100);
end;
procedure TVarHash.Add;
begin
end;
procedure TVarHash.Replace(key:variant;value:variant);
begin
end;
function TVarHash.Get(key:variant;index:integer=0):variant;
begin
end;
function TVarHash.Count(key:variant):integer;
begin
end;
function TVarHash.GetKey(index:integer):variant;
begin
end;
procedure TVarHash.SortKeys;
begin
end; }
function TBaseItem.Compare;
begin
if value>item.value then result:=1 else
if value<item.value then result:=-1 else
result:=0;
end;
constructor TIntItem.Create;
begin
value:=key;
data:=content;
end;
constructor TFloatItem.Create;
begin
value:=key;
data:=content;
end;
function TFloatItem.Compare;
begin
if not (item is TFloatItem) then exit;
if value>(item as TFloatItem).value then result:=1 else
if value<(item as TFloatItem).value then result:=-1 else
result:=0;
end;
function TTreeItem.Compare;
begin
if key>item.key then result:=1 else
if key<item.key then result:=-1 else
result:=0;
end;
constructor TStrItem.Create;
begin
value:=addr(key);
data:=content;
end;
function TStrItem.Compare;
begin
if not (item is TStrItem) then exit;
if value^>(item as TStrItem).value^ then result:=1 else
if value^<(item as TStrItem).value^ then result:=-1 else
result:=0;
end;
constructor THeap.Create;
begin
hSize:=HeapSize+1;
SetLength(items,hSize);
count:=0; LastError:=esNoError;
end;
procedure THeap.Put;
var
p:integer;
begin
if count>hSize then begin
LastError:=esOverflow;
exit;
end;
inc(count);
p:=count;
while (p>1) and (item.compare(items[p div 2])<0) do begin
items[p]:=items[p div 2];
p:=p div 2;
end;
items[p]:=item;
LastError:=esNoError;
end;
function THeap.Get;
var
p,p1,p2:integer;
begin
if count=0 then begin
result:=nil;
LastError:=esEmpty;
exit;
end;
result:=items[1];
dec(count);
p:=1;
repeat
p1:=p*2;
if p1>count then break;
p2:=p1+1;
if (p2<=count) and (items[p2].compare(items[p1])<0) then
p1:=p2;
if items[p1].compare(items[count+1])<0 then begin
items[p]:=items[p1];
p:=p1;
end else break;
until false;
items[p]:=items[count+1];
LastError:=esNoError;
end;
destructor THeap.Destroy;
begin
SetLength(items,0);
count:=0;
end;
destructor THeap.ClearAndDestroy;
var
i:integer;
begin
for i:=1 to count do
items[i].destroy;
count:=0;
SetLength(items,0);
end;
constructor TStrHash.Create;
begin
CreateSize(256);
end;
constructor TStrHash.CreateSize;
var
i:integer;
begin
Hsize:=newsize;
SetLength(cells,Hsize);
Hcount:=0;
LastError:=esNoError;
for i:=0 to Hsize-1 do begin
cells[i].count:=0;
cells[i].size:=1;
SetLength(cells[i].items,1);
end;
end;
function TStrHash.HashValue;
var
i,s:integer;
begin
s:=0;
for i:=1 to length(str) do
s:=s+byte(str[i]);
result:=s mod Hsize;
end;
procedure TStrHash.Put;
var
h,i:integer;
begin
h:=HashValue(key);
with cells[h] do begin
for i:=0 to count-1 do
if items[i].key^=key then begin
items[i].value:=data;
LastError:=esNoError;
exit;
end;
if count=size then begin
inc(size,8+size div 4);
SetLength(items,size);
end;
items[count].key:=addr(key);
items[count].value:=data;
inc(count);
inc(HCount);
end;
LastError:=esNoError;
end;
function TStrHash.Get;
var
h,i:integer;
begin
h:=HashValue(key);
with cells[h] do begin
for i:=0 to count-1 do
if items[i].key^=key then begin
LastError:=esNoError;
result:=items[i].value;
exit;
end;
end;
result:=nil;
LastError:=esNotFound;
end;
procedure TStrHash.Remove;
var
h,i:integer;
begin
h:=HashValue(key);
with cells[h] do begin
for i:=0 to count-1 do
if items[i].key^=key then begin
LastError:=esNoError;
if count>i then
items[i]:=items[count-1];
dec(count);
if size-count>8 then begin
dec(size,8);
SetLength(items,size);
end;
exit;
end;
end;
LastError:=esNotFound;
end;
function TStrHash.FirstKey;
begin
CurCell:=0; CurItem:=0;
if CurItem>=cells[curCell].count then begin
repeat
inc(CurCell);
CurItem:=0;
if cells[CurCell].count>0 then begin
result:=NextKey;
exit;
end;
until CurCell>=HSize;
end else begin
if curItem<cells[curCell].count then begin
result:=cells[CurCell].items[CurItem].key^;
inc(curItem);
end else begin
result:='';
LastError:=esEmpty;
end;
end;
end;
function TStrHash.NextKey;
begin
result:='';
if (CurCell<HSize) and (curItem<cells[curCell].count) then
result:=cells[CurCell].items[CurItem].key^;
inc(CurItem);
if CurItem>=cells[curCell].count then
repeat
inc(CurCell);
if curCell>=hSize then break;
CurItem:=0;
if cells[CurCell].count>0 then begin
result:=cells[curCell].items[0].key^;
inc(curItem);
exit;
end;
until false;
LastError:=esNoMoreItems;
end;
destructor TStrHash.Destroy;
var
i:integer;
begin
for i:=0 to Hsize-1 do begin
SetLength(cells[i].items,0);
cells[i].size:=0;
cells[i].count:=0;
end;
SetLength(cells,0);
Hcount:=0;
end;
constructor TTree.Create;
begin
root:=nil;
end;
destructor TTree.Destroy;
begin
end;
{ TGenericTree }
function TGenericTree.AddChild(item: pointer): integer;
var
t:TGenericTree;
begin
t:=TGenerictree.Create(FreeObjects,PreserveOrder);
t.data:=item;
t.parent:=self;
t.SelfIndex:=children.Count;
result:=children.Add(t);
end;
constructor TGenericTree.Create;
begin
parent:=nil;
data:=nil;
children:=TList.Create;
FreeObjects:=UseObjects;
PreserveOrder:=useOrder;
end;
destructor TGenericTree.Destroy;
var
o:TObject;
item:TGenericTree;
i:integer;
begin
// Destroy children
i:=0;
while children.count>0 do begin
item:=children[children.count-1];
item.destroy;
end;
children.destroy;
// Free object
if FreeObjects then begin
o:=data;
o.Free;
end;
// Remove from parent's children
if parent<>nil then begin
if PreserveOrder then begin
parent.children.Delete(SelfIndex);
// Откорректировать SelfIndex для смещенных эл-тов
for i:=SelfIndex to parent.children.Count-1 do begin
item:=parent.children[i];
item.SelfIndex:=i;
end;
end else begin
// Удалить элемент заменив его последним
parent.children.Move(parent.children.Count-1,SelfIndex);
item:=parent.children[SelfIndex];
item.SelfIndex:=SelfIndex;
end;
end;
inherited;
end;
function TGenericTree.GetChild(index: integer): TGenericTree;
begin
result:=children[index];
end;
function TGenericTree.GetChildrenCount: integer;
begin
result:=children.count;
end;
function TGenericTree.GetIndex: integer;
begin
result:=SelfIndex;
end;
function TGenericTree.GetParent: TGenericTree;
begin
result:=parent;
end;
procedure TGenericTree.InsertChild(item: pointer; index: integer);
var
t,t2:TGenericTree;
i:integer;
begin
if index<0 then
raise EError.Create('GenericTree: invalid index');
if index>children.count then index:=children.count;
t:=TGenerictree.Create(FreeObjects,PreserveOrder);
t.data:=item;
t.parent:=self;
t.SelfIndex:=index;
if PreserveOrder then begin
children.Insert(index,item);
for i:=index to children.count-1 do begin
t:=children[i];
t.selfIndex:=i;
end;
end else begin
children.Add(nil);
t2:=children[index];
children[children.count-1]:=t2;
t2.SelfIndex:=children.count-1;
children[index]:=t;
end;
end;
procedure TGenericTree.Traverse(mode: TraverseMode;
iterator: TTreeiterator);
// Depth-search: children, then root
procedure DepthSearch(depth:integer;iterator:TTreeIterator;RootFirst:boolean);
var
i:integer;
begin
if RootFirst then
iterator(depth,self);
for i:=0 to children.count-1 do
DepthSearch(depth+1,iterator,RootFirst);
if not RootFirst then
iterator(depth,self);
end;
// Width-search
procedure WidthSearch;
var
queue:TList;
index,i:integer;
item:TGenericTree;
begin
queue:=TList.Create;
queue.add(self);
index:=0;
while index<queue.Count do begin
item:=queue[index];
inc(index);
iterator(0,item);
for i:=0 to item.children.Count-1 do
queue.Add(item.children[i]);
end;
end;
begin
case mode of
ChildrenFirst:DepthSearch(0,iterator,false);
RootFirst:DepthSearch(0,iterator,true);
ByLevels:WidthSearch;
end;
end;
{ THash }
constructor THash.Init(allowMultiple:boolean=false);
var
i:integer;
begin
count:=0; vCount:=0;
simplemode:=true;
lastIndex:=-1;
multi:=allowMultiple;
SetLength(keys,32);
if multi then begin
SetLength(vLinks,32);
SetLength(values,64);
SetLength(vNext,64);
end else
SetLength(values,32);
end;
function THash.Find(const key: string): integer;
begin
result:=links[HashValue(key)];
while (result>=0) and (keys[result]<>key) do result:=next[result];
end;
function THash.HashValue(const v: string): integer;
var
i:integer;
st:string;
begin
result:=0;
for i:=1 to length(v) do begin
// inc(result,byte(v[i]));
inc(result,byte(v[i]) shl (i and 3)); // 3 почему-то работает лучше всего...
end;
result:=result and hMask;
end;
function THash.Get(const key: string): variant;
var
h,p:integer;
index:integer;
begin
// 1. Find key index
if simplemode then begin
// simple mode
index:=0;
while (index<count) and (keys[index]<>key) do inc(index);
end else
index:=Find(key);
// 2. Get value
if (index>=0) and (index<count) then begin
if multi then begin
lastIndex:=vlinks[index];
result:=values[lastIndex];
lastIndex:=vNext[lastIndex];
end else
result:=values[index];
end else
result:=Unassigned;
end;
function THash.GetNext:variant; // get next value associated with the key, or Unassigned if none
begin
if (lastIndex>=0) and (lastIndex<vCount) then begin
result:=values[lastIndex];
lastIndex:=vNext[lastIndex];
end else
result:=Unassigned;
end;
function THash.GetAll(const key:string):TVariants; // get array of values
var
c:integer;
v:variant;
begin
SetLength(result,10);
c:=0;
v:=Get(key);
while not VarIsEmpty(v) do begin
result[c]:=v;
v:=getNext;
inc(c);
if c>=length(result) then
SetLength(result,c*2);
end;
SetLength(result,c);
end;
procedure THash.AddValue(const v:variant);
var
i:integer;
begin
if vCount>=length(values) then begin
SetLength(values,vCount*2);
SetLength(vNext,vCount*2);
for i:=vCount to vCount*2-1 do
vNext[i]:=-1;
end;
values[vCount]:=v;
end;
procedure THash.RemoveKey(index:integer);
var
h,p:integer;
begin
if simplemode then
keys[index]:=keys[count-1]
else begin
// Сперва скорректируем ссылки
h:=HashValue(keys[index]);
p:=links[h];
if p=index then // удаление из начала списка
links[h]:=next[p]
else begin // есть предыдущий элемент
while next[p]<>index do p:=next[p];
next[p]:=next[index];
end;
// теперь нужно перенести последний элемент
keys[index]:=keys[count-1];
if multi then vlinks[index]:=vlinks[count-1];
for p:=0 to count-2 do
if next[p]=count-1 then begin
next[p]:=index; break;
end;
end;
dec(count);
if multi then begin
// удалить все значения
end else begin
values[index]:=values[vCount-1];
dec(vCount);
end;
end;
procedure THash.Put(const key:string; value:variant; replace:boolean=false);
var
h,p,index,j,size:integer;
begin
// Find key index
if simplemode then begin
index:=0;
while (index<count) and (keys[index]<>key) do inc(index);
end else begin
index:=Find(key);
if index<0 then index:=count;
end;
// Add new key?
if index=count then
if simplemode then begin
keys[index]:=key;
if multi then vlinks[index]:=-1;
inc(count);
if count=6 then SwitchToAdvancedMode;
end else begin // Advanced (indexed) mode
if count>=length(keys) then begin
size:=length(keys)*2+32; // 32 -> 96 ->224 -> 480 -> 992 -> ...
SetLength(keys,size);
SetLength(next,size);
if multi then SetLength(vLinks,size);
if count>length(links)+32 then begin
hMask:=(hMask shl 2) or $F;
SetLength(links,length(links)*4);
BuildHash;
end;
end;
h:=HashValue(key);
next[count]:=links[h];
links[h]:=count;
keys[count]:=key;
if multi then vLinks[count]:=-1;
index:=count;
inc(count);
end;
// Add value
if multi then begin
// add new value
AddValue(value);
vNext[vCount]:=vLinks[index];
vLinks[index]:=vCount;
inc(vCount);
end else begin
if vCount>=length(values) then SetLength(values,vCount*2);
values[index]:=value; // fixed index
vCount:=count;
end;
end;
procedure THash.SwitchToAdvancedMode;
var
i,h:integer;
begin
simpleMode:=false;
SetLength(next,length(keys));
SetLength(links,64);
hMask:=$3F;
BuildHash;
end;
procedure THash.BuildHash;
var
i,h:integer;
begin
for i:=0 to High(links) do links[i]:=-1;
for i:=0 to count-1 do next[i]:=-1;
for i:=0 to count-1 do begin
h:=HashValue(keys[i]);
next[i]:=links[h];
links[h]:=i;
end;
end;
function THash.AllKeys:StringArr;
var
i:integer;
begin
SetLength(result,count);
for i:=0 to count-1 do
result[i]:=keys[i];
end;
procedure THash.SortKeys;
procedure QuickSort(a,b:integer);
var
lo,hi,v:integer;
mid,key:string;
vr:variant;
i,j:integer;
begin
lo:=a; hi:=b;
mid:=keys[(a+b) div 2];
repeat
while keys[lo]<mid do inc(lo);
while keys[hi]>mid do dec(hi);
if lo<=hi then begin
key:=keys[lo];
keys[lo]:=keys[hi];
keys[hi]:=key;
if multi then begin
v:=vLinks[lo];
vLinks[lo]:=vLinks[hi];
vLinks[hi]:=v;
end else begin
vr:=values[lo];
values[lo]:=values[hi];
values[hi]:=vr;
end;
inc(lo);
dec(hi);
end;
until lo>hi;
if hi>a then QuickSort(a,hi);
if lo<b then QuickSort(lo,b);
end;
begin
if count<2 then exit;
// 1. Sort keys
QuickSort(0,count-1);
// 2. Restore hashes
if not simplemode then BuildHash;
end;
// -------------------------------------------
// TSimpleHash
// -------------------------------------------
procedure TSimpleHash.Init(estimatedCount:integer);
var
i:integer;
begin
SetLength(keys,estimatedCount);
SetLength(values,estimatedCount);
SetLength(next,estimatedCount);
count:=0; fFree:=-1;
hMask:=$FFF;
while (hMask>estimatedCount) and (hMask>$1F) do hMask:=hMask shr 1;
SetLength(links,hMask+1);
for i:=0 to hMask do links[i]:=-1;
end;
procedure TSimpleHash.Put(key,value:integer);
var
h,i,n:integer;
begin
if fFree>=0 then begin
// берем элемент из списка свободных
i:=fFree; fFree:=next[fFree];
end else begin
// добавляем новый элемент
i:=count; inc(count);
if count>length(keys) then begin
n:=length(keys)*2+64;
SetLength(keys,n);
SetLength(values,n);
SetLength(next,n);
end;
end;
// Store data
keys[i]:=key;
values[i]:=value;
// Add to hash
h:=HashValue(key);
next[i]:=links[h];
links[h]:=i;
end;
function TSimpleHash.Get(key:integer):integer;
var
h,i:integer;
begin
h:=HashValue(key);
i:=links[h];
while (i>=0) and (keys[i]<>key) do i:=next[i];
if i>=0 then result:=values[i] else result:=-1;
end;
function TSimpleHash.HasValue(key:integer):boolean;
var
h,i:integer;
begin
h:=HashValue(key);
i:=links[h];
while (i>=0) and (keys[i]<>key) do i:=next[i];
if i>=0 then result:=true else result:=false;
end;
procedure TSimpleHash.Remove(key:integer);
var
h,i,prev:integer;
begin
h:=HashValue(key);
// Поиск по списку
i:=links[h]; prev:=-1;
while (i>=0) and (keys[i]<>key) do begin
prev:=i;
i:=next[i];
end;
if i>=0 then begin
// Удаление из односвязного списка
if prev>=0 then next[prev]:=next[i]
else links[h]:=next[i];
keys[i]:=-1; values[i]:=-1;
next[i]:=fFree;
fFree:=i;
end;
end;
function TSimpleHash.HashValue(const k:integer):integer;
begin
result:=(k+(k shr 11)+(k shr 23)) and hMask;
end;
// -------------------------------------------------------
// TBitStream
// -------------------------------------------------------
procedure TBitStream.Init;
begin
size:=0; readPos:=0;
SetLength(data,estimatedSize div 8);
capacity:=length(data)*8;
FillChar(data[0],length(data),0);
end;
procedure TBitStream.Put(var buf;count:integer); // write count bits to the stream (from curPos position)
var
pb:PByte;
i:integer;
b:byte;
begin
if size+count>capacity then begin
i:=length(data);
capacity:=(capacity+1024)*2;
SetLength(data,capacity div 8);
FillChar(data[i],length(data)-i,0); // zerofill
end;
pb:=@buf; b:=pb^;
// простая, неэффективная версия
for i:=0 to count-1 do begin
if b and 1>0 then
data[size shr 3]:=data[size shr 3] or (1 shl (i and 7));
b:=b shr 1;
inc(size);
if i and 7=7 then begin
inc(pb); b:=pb^;
end;
end;
end;
procedure TBitStream.Get(var buf;count:integer); // read count bits from the stream (from curPos position)
var
pb:PByte;
b:byte;
begin
// простая, неэффективная версия
end;
function TBitStream.SizeInBytes:integer; // return size of stream in bytes
begin
result:=(size+7) div 8;
end;
end.
|
unit ProductionAreaModel;
interface
uses connection, Ragna, System.JSON, 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.ConsoleUI.Wait, Data.DB,
FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize,
System.Classes, System.NetEncoding, Soap.EncdDecd;
Function save(productionAreaJson: String): TFDQuery;
Function findByProducer(id: integer): TFDQuery;
Function findByPk(id: integer): TFDQuery;
Function findAvatarByProducer(id_producer: integer; id_area: integer): TMemoryStream;
function update(id: integer; productionAreaJson: string ): TFDQuery;
function delete(id: integer ): boolean;
Function findByPkAndProducer(id: integer; id_producer: integer): TFDQuery;
implementation
Function findAvatarByProducer(id_producer: integer; id_area: integer): TMemoryStream;
begin
const fileStream = TMemoryStream.Create;
const DMConnection = TDMConnection.Create(nil);
var ProductionArea := DMConnection.Areas_Producao;
try
ProductionArea
.Where('id').Equals(id_area)
.&And('id_produtor').Equals(id_producer).OpenUp;
const img = ProductionArea.CreateBlobStream(
ProductionArea.FieldByName('foto'),
bmRead
);
fileStream.LoadFromStream(img);
result := fileStream;
except
on E:Exception do
Writeln(E.Message);
end;
end;
procedure saveFoto(base64: string; id:integer);
var
Buf: TBytes;
begin
DMConnection := TDMConnection.Create(DMConnection);
var ProductionArea := DMConnection.Areas_Producao;
const ss = TStringStream.Create(base64);
const ms = TMemoryStream.Create;
DecodeStream (ss, ms);
ms.Position := 0;
SetLength(Buf, ms.Size);
ms.ReadBuffer(Buf, ms.Size);
ProductionArea.close;
ProductionArea.SQL.Clear;
ProductionArea.SQL.Add('update areas_producao set foto=:foto where ');
ProductionArea.SQL.Add('id =:id');
ProductionArea.ParamByName('id').AsInteger := id;
ProductionArea.ParamByName('foto').LoadFromStream(ms, ftBlob);
ProductionArea.ExecSQL;
end;
Function save(productionAreaJson: String): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
var ProductionArea := DMConnection.Areas_Producao;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(productionAreaJson), 0) as TJSONObject;
const base64 = jsonObj.GetValue('foto').value;
jsonObj.RemovePair('foto');
ProductionArea.New(jsonObj).OpenUp;
const id = ProductionArea.FieldByName('id').AsInteger;
saveFoto(base64, id);
Result := ProductionArea;
end;
function update(id: integer; productionAreaJson: string ): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const ProductionArea = DMConnection.Areas_Producao;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(productionAreaJson), 0) as TJSONObject;
var base64 := '';
if jsonObj.TryGetValue('foto', base64) then
begin
base64 := jsonObj.GetValue('foto').value;
jsonObj.RemovePair('foto');
end;
ProductionArea.where('id').Equals(id).OpenUp;
ProductionArea.MergeFromJSONObject(jsonObj);
if base64 <> '' then
begin
const id_area = ProductionArea.FieldByName('id').AsInteger;
saveFoto(base64, id_area);
end;
Result := ProductionArea;
end;
Function findByPk(id: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
var ProductionArea := DMConnection.Areas_Producao;
ProductionArea.where('id').equals(id).OpenUp;
Result := ProductionArea;
end;
Function findByPkAndProducer(id: integer; id_producer: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
var ProductionArea := DMConnection.Areas_Producao;
ProductionArea
.where('id').equals(id)
.&And('id_produtor').Equals(id_producer)
.OpenUp;
Result := ProductionArea;
end;
Function findByProducer(id: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
var ProductionArea := DMConnection.Areas_Producao;
ProductionArea.where('id_produtor').equals(id).OpenUp;
Result := ProductionArea;
end;
function delete(id: integer ): boolean;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Area = DMConnection.Areas_Producao;
try
Area.Remove(Area.FieldByName('id'), id).OpenUp;
result:= true;
except
on E:Exception do
result:= false;
end;
end;
end.
|
unit Dmitry.Controls.WebLink;
interface
uses
Generics.Collections,
System.UITypes,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Winapi.Messages,
Vcl.Controls,
Vcl.Graphics,
Vcl.StdCtrls,
Vcl.Forms,
Vcl.Themes,
Vcl.ImgList,
Dmitry.Memory,
Dmitry.Utils.System,
Dmitry.Graphics.LayeredBitmap,
Dmitry.Controls.Base,
Dmitry.PathProviders;
type
TGetBackGroundProc = procedure(Sender: TObject; X, Y, W, H: Integer; Bitmap: TBitmap) of object;
type
TWebLink = class(TBaseWinControl)
private
{ Private declarations }
FCanvas: TCanvas;
FShowenBitmap: TBitmap;
FOnClick: TNotifyEvent;
Loading: Boolean;
FImageIndex: Integer;
FImageList: TCustomImageList;
FIcon: TIcon;
FIconStream: TMemoryStream;
FIconWidth: Integer;
FIconHeight: Integer;
FImage: TLayeredBitmap;
FEnterColor: TColor;
FEnterBould: Boolean;
FUseEnterColor: Boolean;
FTopIconIncrement: Integer;
FGetBackGround: TGetBackGroundProc;
FImageCanRegenerate: Boolean;
FIconChanged: Boolean;
FUseSpecIconSize: Boolean;
FIsHover: Boolean;
FHightliteImage: Boolean;
FFontStyles: TFontStyles;
FFontName: string;
FFontSize: Integer;
FFontColor: TColor;
FOnMouseEnter: TNotifyEvent;
FOnMouseLeave: TNotifyEvent;
FStretchImage: Boolean;
FCanClick: Boolean;
FIsGDIFree: Boolean;
FPainted: Boolean;
FUseEndEllipsis: Boolean;
procedure SetOnClick(const Value: TNotifyEvent);
procedure SetImageIndex(const Value: Integer);
procedure SetImageList(const Value: TCustomImageList);
procedure SetIcon(const Value: TIcon);
procedure SetIconWidth(const Value: Integer);
procedure SetIconHeight(const Value: Integer);
procedure SetEnterColor(const Value: TColor);
procedure SetEnterBould(const Value: Boolean);
procedure SetUseEnterColor(const Value: Boolean);
procedure SetTopIconIncrement(const Value: integer);
procedure SetGetBackGround(const Value: TGetBackGroundProc);
procedure SetHightliteImage(const Value: Boolean);
procedure SetStretchImage(const Value: Boolean);
function GetIcon: TIcon;
procedure SetUseEndEllipsis(const Value: Boolean);
protected
{ Protected declarations }
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMSize(var Message: TSize); message WM_SIZE;
procedure WMMouseDown(var Message: TMessage); message WM_LBUTTONDOWN;
procedure CMMouseLeave(var Message: TWMNoParams); message CM_MOUSELEAVE;
procedure CMMouseEnter(var Message: TWMNoParams); message CM_MOUSEENTER;
procedure CMFontChanged(var Message: TWMNoParams); message CM_FONTCHANGED;
procedure Erased(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CNCtlColorStatic(var Message: TWMCtlColorStatic); message CN_CTLCOLORSTATIC;
procedure IconChanged(Sender: TObject);
procedure Loaded; override;
procedure FreeGDI;
procedure LoadGDI;
procedure SaveIconToStream;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadFromHIcon(Icon: HIcon);
procedure LoadFromResource(ResourceName: string);
procedure RefreshBuffer(Force: Boolean = False);
procedure Refresh;
procedure SetDefault;
procedure LoadIconSize(Icon: TIcon; Width, Height: Integer);
procedure LoadBitmap(Bitmap: TBitmap);
procedure LoadFromPathImage(Image: TPathImage);
procedure CreateImageFromIcon;
procedure LoadImage;
procedure CalculateLinkSize;
procedure StartChanges;
property Canvas: TCanvas read FCanvas;
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property OnContextPopup;
property Font;
property PopupMenu;
property Color;
property ParentColor;
property Text;
property Hint;
property ShowHint;
property ParentShowHint;
property Visible;
property OnMouseDown;
property OnMouseUp;
property OnClick: TNotifyEvent read FOnClick write SetOnClick;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
property ImageList: TCustomImageList read FImageList write SetImageList;
property ImageIndex: Integer read FImageIndex write SetImageIndex;
property IconWidth: Integer read FIconWidth write SetIconWidth default 16;
property IconHeight: Integer read FIconHeight write SetIconHeight default 16;
property UseEnterColor: Boolean read FUseEnterColor write SetUseEnterColor;
property EnterColor: TColor read FEnterColor write SetEnterColor;
property EnterBould: Boolean read FEnterBould write SetEnterBould;
property TopIconIncrement: Integer read FTopIconIncrement write SetTopIconIncrement;
property GetBackGround: TGetBackGroundProc read FGetBackGround write SetGetBackGround;
property Icon: TIcon read GetIcon write SetIcon;
property UseSpecIconSize: Boolean read FUseSpecIconSize write FUseSpecIconSize;
property HightliteImage: Boolean read FHightliteImage write SetHightliteImage;
property StretchImage: Boolean read FStretchImage write SetStretchImage;
property CanClick: Boolean read FCanClick write FCanClick;
property UseEndEllipsis: Boolean read FUseEndEllipsis write SetUseEndEllipsis default false;
end;
type
TWebLinkManager = Class(TObject)
private
FLinks: TList<TWebLink>;
FUseList: TList<TWebLink>;
protected
procedure UsedLink(Link: TWebLink);
procedure RemoveLink(Link: TWebLink);
public
constructor Create;
destructor Destroy; override;
end;
const
LINK_IL_MAX_ITEMS = 200;
LINK_IL_ITEMS_TO_SWAP_AT_TIME = 20;
procedure Register;
implementation
var
FWebLinkList: TWebLinkManager = nil;
function WebLinkList: TWebLinkManager;
begin
if FWebLinkList = nil then
FWebLinkList := TWebLinkManager.Create;
Result := FWebLinkList;
end;
procedure Register;
begin
RegisterComponents('Dm', [TWebLink]);
end;
{ TWebLink }
procedure TWebLink.CMFONTCHANGED(var Message: TWMNoParams);
begin
LoadGDI;
FFontStyles := Font.Style;
FFontColor := Font.Color;
if IsStyleEnabled then
FFontColor := StyleServices.GetStyleFontColor(sfButtonTextFocused)
else
FFontColor := Font.Color;
FFontName := Font.Name;
FFontSize := Font.Size;
FShowenBitmap.Canvas.Font.Assign(Font);
RefreshBuffer;
end;
procedure TWebLink.CMMOUSEEnter(var Message: TWMNoParams);
begin
if not FCanClick then
Exit;
LoadGDI;
FIsHover := True;
if EnterBould then
FShowenBitmap.Canvas.Font.Style := FFontStyles + [fsUnderline, fsBold];
RefreshBuffer;
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
inherited;
end;
procedure TWebLink.CMMOUSELEAVE(var Message: TWMNoParams);
begin
LoadGDI;
FIsHover := False;
FShowenBitmap.Canvas.Font.Style := FFontStyles;
RefreshBuffer;
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self);
inherited;
end;
procedure TWebLink.CMTextChanged(var Message: TMessage);
begin
RefreshBuffer;
end;
procedure TWebLink.CNCtlColorStatic(var Message: TWMCtlColorStatic);
begin
with StyleServices do
if ThemeControl(Self) then
begin
if (Parent <> nil) and Parent.DoubleBuffered then
PerformEraseBackground(Self, Message.ChildDC)
else
DrawParentBackground(Handle, Message.ChildDC, nil, False);
{ Return an empty brush to prevent Windows from overpainting we just have created. }
Message.Result := GetStockObject(NULL_BRUSH);
end
else
inherited;
end;
constructor TWebLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPainted := False;
FIconStream := nil;
WebLinkList.UsedLink(Self);
FIsGDIFree := False;
FIconChanged := False;
FIsHover := False;
FImageCanRegenerate := False;
GetBackGround := nil;
FOnMouseEnter := nil;
FOnMouseLeave := nil;
ControlStyle := ControlStyle - [csDoubleClicks] + [csParentBackground];
Loading := True;
FUseEnterColor := False;
FIcon := TIcon.Create;
FIcon.OnChange := IconChanged;
UseSpecIconSize := True;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FImageList := nil;
FImage := TLayeredBitmap.Create;
FImage.IsLayered := True;
FIconWidth := 16;
FIconHeight := 16;
FTopIconIncrement := 0;
DoubleBuffered := True;
FShowenBitmap := TBitmap.Create;
FShowenBitmap.PixelFormat := pf24bit;
FEnterColor := 0;
FStretchImage := True;
FCanClick := True;
Loading := False;
FEnterBould := False;
Cursor := crHandPoint;
end;
destructor TWebLink.Destroy;
begin
WebLinkList.RemoveLink(Self);
F(FCanvas);
F(FIconStream);
F(FShowenBitmap);
F(FImage);
F(FIcon);
inherited;
end;
procedure TWebLink.Erased(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TWebLink.LoadFromHIcon(Icon: HIcon);
var
TempIcon: TIcon;
begin
if Icon = 0 then
Exit;
TempIcon := TIcon.Create;
try
TempIcon.Handle := CopyIcon(Icon);
LoadIconSize(TempIcon, FIconWidth, FIconHeight);
finally
F(TempIcon);
end;
end;
procedure TWebLink.LoadFromPathImage(Image: TPathImage);
begin
if Image.HIcon <> 0 then
LoadFromHIcon(Image.HIcon)
else if Image.Icon <> nil then
LoadIconSize(Image.Icon, Image.Icon.Width, Image.Icon.Height)
else if Image.Bitmap <> nil then
LoadBitmap(Image.Bitmap);
end;
procedure TWebLink.LoadFromResource(ResourceName: string);
var
Icon: HIcon;
begin
Icon := Winapi.Windows.LoadImage(HInstance, PChar(ResourceName), IMAGE_ICON, FIconWidth, FIconHeight, 0);
try
if Icon <> 0 then
LoadFromHIcon(Icon);
finally
DestroyIcon(Icon);
end;
end;
procedure TWebLink.FreeGDI;
begin
if FIsGDIFree then
Exit;
FShowenBitmap.Dormant;
FImage.Dormant;
F(FCanvas);
FIsGDIFree := True;
end;
function TWebLink.GetIcon: TIcon;
begin
LoadGDI;
Result := FIcon;
end;
procedure TWebLink.LoadGDI;
begin
if FIsGDIFree then
begin
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FShowenBitmap.Canvas.Font.Name := FFontName;
FShowenBitmap.Canvas.Font.Style := FFontStyles;
if IsStyleEnabled then
FShowenBitmap.Canvas.Font.Color := StyleServices.GetStyleFontColor(sfPanelTextNormal)
else
FShowenBitmap.Canvas.Font.Color := FFontColor;
FShowenBitmap.Canvas.Font.Size := FFontSize;
FIsGDIFree := False;
end;
if FIconStream <> nil then
begin
F(FIcon);
FIcon := TIcon.Create;
FIconStream.Seek(0, soFromBeginning);
try
FIcon.LoadFromStream(FIconStream);
except
//ignore possible deserealization errors
end;
F(FIconStream);
end;
WebLinkList.UsedLink(Self);
end;
procedure TWebLink.LoadIconSize(Icon: TIcon; Width, Height: Integer);
begin
LoadGDI;
FIcon.Assign(Icon);
FImage.LoadFromHIcon(FIcon.Handle, Width, Height);
SaveIconToStream;
RefreshBuffer;
end;
procedure TWebLink.LoadImage;
begin
RefreshBuffer(True);
end;
procedure TWebLink.WMPaint(var Message: TWMPaint);
var
DC: HDC;
PS: TPaintStruct;
begin
if not FPainted then
begin
FPainted := True;
RefreshBuffer(True);
end;
DC := BeginPaint(Handle, PS);
BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, FShowenBitmap.Canvas.Handle, 0, 0, SRCCOPY);
EndPaint(Handle, PS);
end;
procedure TWebLink.RefreshBuffer(Force: Boolean);
var
Drawrect: TRect;
L: Integer;
begin
if (csReading in ComponentState) then
Exit;
if (csLoading in ComponentState) then
Exit;
if not FPainted and not Force then
Exit;
if FIconChanged then
begin
FIconChanged := False;
CreateImageFromIcon;
end;
CalculateLinkSize;
if FPainted then
begin
if Assigned(FGetBackGround) then
FGetBackGround(Self, Left, Top, Width, Height, FShowenBitmap)
else
DrawBackground(FShowenBitmap.Canvas);
if FIsHover then
begin
FShowenBitmap.Canvas.Font.Style := FFontStyles + [fsUnderline];
if UseEnterColor or IsStyleEnabled then
begin
if IsStyleEnabled then
FShowenBitmap.Canvas.Font.Color := StyleServices.GetStyleFontColor(sfCheckBoxTextHot)
else
FShowenBitmap.Canvas.Font.Color := EnterColor;
end;
end else
begin
if IsStyleEnabled then
FShowenBitmap.Canvas.Font.Color := StyleServices.GetStyleFontColor(sfCheckBoxTextNormal)
else
FShowenBitmap.Canvas.Font.Color := FFontColor;
end;
FShowenBitmap.Canvas.Brush.Style := bsClear;
if ((FImageList = nil) or (ImageIndex = -1)) and (FIcon = nil) then
FShowenBitmap.Canvas.TextOut(0, Height div 2 - FShowenBitmap.Canvas.TextHeight(Text) div 2, Text)
else if (FImageList <> nil) and (ImageIndex <> -1) then
begin
FImageList.Draw(FShowenBitmap.Canvas, 0, 0, FImageIndex, dsTransparent, itImage, True);
FShowenBitmap.Canvas.TextOut(FImageList.Width + 5, Height div 2 - FShowenBitmap.Canvas.TextHeight(Text) div 2, Text);
end else if (FIcon <> nil) then
begin
if Enabled then
begin
if not FStretchImage then
FImage.DoDraw(IconHeight div 2 - FImage.Height div 2, FTopIconIncrement + IconWidth div 2 - FImage.Width div 2,
FShowenBitmap, FIsHover and HightliteImage)
else
FImage.DoStreachDraw(0, FTopIconIncrement + FShowenBitmap.Height div 2 - FImage.Height div 2, IconWidth, IconHeight, FShowenBitmap)
end else
begin
if (IconWidth = FImage.Width) and (IconHeight = FImage.Height) then
FImage.DoDrawGrayscale(0, FTopIconIncrement + FShowenBitmap.Height div 2 - FImage.Height div 2, FShowenBitmap)
else
FImage.DoStreachDrawGrayscale(0, FTopIconIncrement + FShowenBitmap.Height div 2 - FImage.Height div 2, IconWidth, IconHeight, FShowenBitmap);
end;
L := FIconWidth + IIF(IconWidth <> 0, 5, 0);
if Assigned(FGetBackGround) then
begin
DrawRect := Rect(L, Height div 2 - FShowenBitmap.Canvas.TextHeight(Text) div 2, Width, Height);
DrawText(FShowenBitmap.Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_NOCLIP or DT_CENTER or DT_VCENTER or IIF(UseEndEllipsis, DT_END_ELLIPSIS, 0));
end else
begin
DrawRect := Rect(L, Height div 2 - FShowenBitmap.Canvas.TextHeight(Text) div 2, Width, Height);
FShowenBitmap.Canvas.FillRect(DrawRect);
DrawText(FShowenBitmap.Canvas.Handle, PChar(Text), Length(Text), DrawRect, DT_NOCLIP or DT_VCENTER or IIF(UseEndEllipsis, DT_END_ELLIPSIS, 0));
end;
end;
Invalidate;
end;
end;
procedure TWebLink.Refresh;
begin
RefreshBuffer(True);
if not (csReadingState in ControlState) then
Invalidate;
end;
procedure TWebLink.SaveIconToStream;
begin
FIconStream := TMemoryStream.Create;
FIcon.SaveToStream(FIconStream);
F(FIcon);
end;
procedure TWebLink.SetDefault;
begin
LoadGDI;
if UseEnterColor then
FShowenBitmap.Canvas.Font.Color := EnterColor;
FShowenBitmap.Canvas.Font.Style := FFontStyles;
RefreshBuffer;
end;
procedure TWebLink.SetEnterBould(const Value: boolean);
begin
FEnterBould := Value;
end;
procedure TWebLink.SetEnterColor(const Value: TColor);
begin
FEnterColor := Value;
end;
procedure TWebLink.SetGetBackGround(const Value: TGetBackGroundProc);
begin
FGetBackGround := Value;
end;
procedure TWebLink.SetHightliteImage(const Value: Boolean);
begin
if FHightliteImage <> Value then
begin
FHightliteImage := Value;
RefreshBuffer;
end;
end;
procedure TWebLink.SetIcon(const Value: TIcon);
begin
LoadGDI;
FIcon.Assign(Value);
CreateImageFromIcon;
end;
procedure TWebLink.SetIconHeight(const Value: Integer);
begin
if FIconHeight <> Value then
begin
FIconHeight := Value;
RefreshBuffer;
end;
end;
procedure TWebLink.SetIconWidth(const Value: Integer);
begin
if FIconWidth <> Value then
begin
FIconWidth := Value;
RefreshBuffer;
end;
end;
procedure TWebLink.SetImageIndex(const Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
RefreshBuffer;
end;
end;
procedure TWebLink.SetImageList(const Value: TCustomImageList);
begin
if FImageList <> Value then
begin
FImageList := Value;
RefreshBuffer;
end;
end;
procedure TWebLink.SetOnClick(const Value: TNotifyEvent);
begin
FOnClick := Value;
end;
procedure TWebLink.SetStretchImage(const Value: Boolean);
begin
FStretchImage := Value;
RefreshBuffer;
end;
procedure TWebLink.SetTopIconIncrement(const Value: integer);
begin
FTopIconIncrement := Value;
end;
procedure TWebLink.SetUseEnterColor(const Value: boolean);
begin
FUseEnterColor := Value;
end;
procedure TWebLink.StartChanges;
begin
FPainted := False;
end;
procedure TWebLink.SetUseEndEllipsis(const Value: Boolean);
begin
FUseEndEllipsis := Value;
end;
procedure TWebLink.WMMouseDown(var Message: Tmessage);
begin
inherited;
if Enabled and FCanClick and Assigned(FOnClick) then
FOnClick(Self);
end;
procedure TWebLink.WMSize(var Message: TSize);
begin
if (Message.cx <> Width) or (Message.cy <> Height) then
RefreshBuffer;
end;
procedure TWebLink.IconChanged(Sender: TObject);
begin
if (csReading in ComponentState) or not FPainted then
FIconChanged := True
else
RefreshBuffer(True);
end;
procedure TWebLink.CreateImageFromIcon;
begin
LoadGDI;
if UseSpecIconSize then
FImage.LoadFromHIcon(FIcon.Handle, FIconWidth, FIconHeight)
else
FImage.LoadFromHIcon(FIcon.Handle);
SaveIconToStream;
end;
procedure TWebLink.LoadBitmap(Bitmap: TBitmap);
begin
LoadGDI;
FImage.LoadFromBitmap(Bitmap);
end;
procedure TWebLink.Loaded;
begin
inherited;
end;
procedure TWebLink.CalculateLinkSize;
begin
LoadGDI;
if (FIcon <> nil) then
begin
if not UseEndEllipsis then
Width := FShowenBitmap.Canvas.TextWidth(Text) + FIconWidth + IIF(FIconWidth > 0, 5, 0);
Height := Max(FShowenBitmap.Canvas.TextHeight(Text + ' '), FIconHeight);
end else if (FImageList <> nil) then
begin
if not UseEndEllipsis then
Width := FShowenBitmap.Canvas.TextWidth(Text);
Height := FShowenBitmap.Canvas.TextHeight(Text + ' ');
end else if (FImageList <> nil) and (ImageIndex <> -1) then
begin
if not UseEndEllipsis then
Width := FShowenBitmap.Canvas.TextWidth(Text) + FImageList.Width + 5;
Height := Max(FShowenBitmap.Canvas.TextHeight(Text + ' '), FImageList.Height);
end else
begin
if not UseEndEllipsis then
Width := FShowenBitmap.Canvas.TextWidth(Text) + 5;
Height := FShowenBitmap.Canvas.TextHeight(Text + ' ');
end;
FShowenBitmap.SetSize(Width, Height);
end;
procedure TWebLink.CMColorChanged(var Message: TMessage);
begin
LoadGDI;
FShowenBitmap.Canvas.Brush.Color := Color;
FShowenBitmap.Canvas.Pen.Color := Color;
RefreshBuffer;
end;
procedure TWebLink.CMEnabledChanged(var Message: TMessage);
begin
RefreshBuffer;
inherited;
end;
{ TWebLinkManager }
constructor TWebLinkManager.Create;
begin
FLinks := TList<TWebLink>.Create;
FUseList := TList<TWebLink>.Create;
end;
destructor TWebLinkManager.Destroy;
begin
F(FLinks);
F(FUseList);
inherited;
end;
procedure TWebLinkManager.RemoveLink(Link: TWebLink);
begin
FUseList.Remove(Link);
end;
procedure TWebLinkManager.UsedLink(Link: TWebLink);
var
I: Integer;
begin
RemoveLink(Link);
FUseList.Add(Link);
if FUseList.Count > LINK_IL_MAX_ITEMS then
begin
for I := LINK_IL_ITEMS_TO_SWAP_AT_TIME - 1 downto 0 do
begin
FUseList[I].FreeGDI;
FUseList.Delete(I);
end;
end;
end;
initialization
finalization
F(FWebLinkList);
end.
|
unit uSingleAppInstance;
interface
uses
Winapi.Windows;
function IsSingleInstance(MutexName : string; KeepMutex : boolean = true):boolean;
implementation
//Creates a mutex to see if the program is already running.
function IsSingleInstance(MutexName : string; KeepMutex : boolean = true):boolean;
const MUTEX_GLOBAL = 'Global\'; //Prefix to explicitly create the object in the global or session namespace. I.e. both client app (local user) and service (system account)
var MutexHandel : THandle;
SecurityDesc: TSecurityDescriptor;
SecurityAttr: TSecurityAttributes;
ErrCode : integer;
begin
// By default (lpMutexAttributes =nil) created mutexes are accessible only by
// the user running the process. We need our mutexes to be accessible to all
// users, so that the mutex detection can work across user sessions.
// I.e. both the current user account and the System (Service) account.
// To do this we use a security descriptor with a null DACL.
InitializeSecurityDescriptor(@SecurityDesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(@SecurityDesc, True, nil, False);
SecurityAttr.nLength:=SizeOf(SecurityAttr);
SecurityAttr.lpSecurityDescriptor:=@SecurityDesc;
SecurityAttr.bInheritHandle:=False;
// The mutex is created in the global name space which makes it possible to
// access across user sessions.
MutexHandel := CreateMutex(@SecurityAttr, True, PChar(MUTEX_GLOBAL + MutexName));
ErrCode := GetLastError;
// If the function fails, the return value is 0
// If the mutex is a named mutex and the object existed before this function
// call, the return value is a handle to the existing object, GetLastError
// returns ERROR_ALREADY_EXISTS.
if {(MutexHandel = 0) or }(ErrCode = ERROR_ALREADY_EXISTS) then
begin
result := false;
closeHandle(MutexHandel);
end
else
begin
// Mutex object has not yet been created, meaning that no previous
// instance has been created.
result := true;
if not KeepMutex then
CloseHandle(MutexHandel);
end;
// The Mutexhandle is not closed because we want it to exist during the
// lifetime of the application. The system closes the handle automatically
//when the process terminates.
end;
end.
|
unit fMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids;
// This was a comment that was edited
// Now adding this in Delphi - Richard Tully added this
// Line three
type
TForm6 = class(TForm)
Button1: TButton;
cds: TClientDataSet;
cdsSeqNo: TIntegerField;
cdsName: TStringField;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
Button2: TButton;
Button3: TButton;
cdsNum: TIntegerField;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DBGrid1TitleClick(Column: TColumn);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public // This is now OK IT IS
{ Public declarations }
end;
var
Form6: TForm6;
implementation
{$R *.dfm}
type //used in converting number to string
TNumberStr = string[13];
const
Numbers: array[1..19] of TNumberStr = ('One', 'Two', 'Three', 'Four',
'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve',
'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen',
'Nineteen');
Tenths: array[1..9] of TNumberStr = ('Ten', 'Twenty', 'Thirty', 'Forty',
'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
Min= 0; Max=10000000;
function RecurseNumber(N: LongWord): string;
begin
case N of
1..19: Result := Numbers[N];
20..99: Result := Tenths[N div 10] + ' ' + RecurseNumber(N mod 10);
100..999: Result := Numbers[N div 100] + ' Hundred ' + RecurseNumber(N mod 100);
1000..999999:Result := RecurseNumber(N div 1000) + ' Thousand ' +
RecurseNumber(N mod 1000);
1000000..999999999: Result := RecurseNumber(N div 1000000) + ' Million '
+ RecurseNumber(N mod 1000000);
1000000000..4294967295: Result := RecurseNumber(N div 1000000000) + ' Billion ' +
RecurseNumber(N mod 1000000000);
end;{Case N of}
end;{RecurseNumber}
function NumToLetters(Number: Real): string;
begin
if (Number >= Min) and (Number <= Max) then
begin
Result := RecurseNumber(Round(Int(Number)))+ ' Dollars';
{Added for cents in a currency value}
if not(Frac(Number) = 0.00) then
Result := Result + ' and ' + IntToStr(Round(Frac(Number) * 100)) + '/100'
else
Result := Result + ' and 0/100';
Result := StringReplace(Result, ' ', ' ', []);
end ;
//else
// raise ERangeError.CreateFmt('%g ' + ErrorString + ' %g..%g',[Number, Min, Max]);
end;{NumToLetters}
procedure TForm6.Button1Click(Sender: TObject);
var
i, n1,n2,n3,n4,n5,n6,n: Integer;
NStr: string;
begin
for i := 0 to 999999 do
begin
n1 := Random(10);
n2 := Random(10);
n3 := Random(10);
n4 := Random(10);
n5 := Random(10);
n6 := Random(10);
n := n1+N2*10+n3*100+n4*1000+n5*10000+n6*100000;
NStr := RecurseNumber(N);
cds.InsertRecord([i,n,NStr]);
end;
end;
procedure TForm6.Button2Click(Sender: TObject);
begin
cds.SaveToFile('Numbers.cds');
end;
procedure TForm6.Button3Click(Sender: TObject);
begin
cds.LoadFromFile('Numbers.cds');
end;
procedure TForm6.Button4Click(Sender: TObject);
begin
showmessage('This was a test 2');
end;
procedure TForm6.DBGrid1TitleClick(Column: TColumn);
begin
cds.IndexFieldNames := Column.FieldName;
end;
procedure TForm6.FormShow(Sender: TObject);
begin
cds.CreateDataSet;
end;
end.
|
unit docs.appointment;
interface
uses
Horse,
Horse.GBSwagger;
procedure registry();
implementation
uses schemas.classes;
procedure registry();
begin
Swagger
.Path('produtor/{id_produtor}/apontamento')
.Tag('Registro de produção')
.GET('listar todo o registro de produção com filtros ', 'listar todo o registro de produção com filtros')
.Description('o filtro de data será aplicado somente se data_fim e data_inicio forem preenchidos' +
'<br/> a paginação só será aplicada se os parametros page e limit forem inseridos')
.AddParamPath('id_produtor', 'id_produtor')
.Schema(SWAG_INTEGER)
.Required(true)
.&End
.AddParamQuery('page', 'page')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('limit', 'limit')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('area', 'area')
.Schema(SWAG_Integer)
.required(false)
.&end
.AddParamQuery('tp_prod', 'tp_prod')
.Schema(SWAG_STRING)
.required(false)
.&end
.AddParamQuery('data_inicio', 'data_inicio')
.Schema(SWAG_STRING)
.required(false)
.&end
.AddParamQuery('data_fim', 'data_fim')
.Schema(SWAG_STRING)
.required(false)
.&end
.AddResponse(200)
.Schema(TAppointmentPagination)
.isArray(true)
.&End
.AddResponse(404, 'produtor não encontrada')
.Schema(TMessage)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('produtor/{id_produtor}/apontamento')
.Tag('Registro de produção')
.Post('criar registro de produção', 'criar registro de produção')
.AddParamBody
.Schema(TAppointment)
.&End
.AddResponse(201)
.Schema(TAppointment)
.&End
.AddResponse(404, 'produtor não encontrado')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('produtor/{id_produtor}/apontamento/{id_apontamento}')
.Tag('Registro de produção')
.Put('alterar área de produção', 'alterar área de produção')
.AddParamPath('id_produtor', 'id_produtor')
.Schema(SWAG_INTEGER)
.&end
.AddParamPath('id_apontamento', 'id_apontamento')
.Schema(SWAG_INTEGER)
.&end
.AddParamBody
.Schema(TAppointment)
.&End
.AddResponse(200)
.Schema(TRegion)
.&End
.AddResponse(404, 'produtor não encontrada | apontamento não enctrado')
.Schema(TMessage)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('produtor/{id_produtor}/apontamento/{id_apontamento}')
.Tag('Registro de produção')
.Delete('deletar instituição', 'deletar uma instituição')
.AddParamPath('id_produtor', 'id_produtor')
.Schema(SWAG_INTEGER)
.&end
.AddParamPath('id_apontamento', 'id_apontamento')
.Schema(SWAG_INTEGER)
.&end
.AddResponse(200, 'registro de produção deletada com sucesso')
.Schema(TMessage)
.&End
.AddResponse(404, 'produtor não encontrada | registro de produção não encontrada')
.Schema(TMessage)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshchannel;
interface
uses wsocket, sshutil;
type
TSSHChannelOnData = procedure(Data: Pointer; Len: integer) of object;
TSSHChannel = class
protected
OutBuffer: TSSHBuffer;
Session: TObject;
FOnData: TSSHChannelOnData;
procedure DefOndata(Data: pointer; Len: integer);
function GetOnDataAvalible: TSSHChannelOnData;
procedure SetOnDataAvalible(const Value: TSSHChannelOnData);
public
constructor Create(Owner: TObject); virtual;
destructor Destroy; override;
property OnDataAvalible: TSSHChannelOnData
read GetOnDataAvalible write SetOnDataAvalible;
procedure Send(Data: Pointer; Len: integer); virtual;
procedure SendDefer(Data: Pointer; Len: integer); virtual;
procedure Flush; virtual;
end;
TSSH1Channel = class(TSSHChannel)
public
procedure Send(Data: Pointer; Len: integer); override;
procedure Flush; override;
end;
TSSH2Channel = class(TSSHChannel)
private
OnExtData: TSSHChannelOnData;
function GetOnExtDataAvalible: TSSHChannelOnData;
procedure SetOnExtDataAvalible(const Value: TSSHChannelOnData);
function TrySend: boolean;
public
RemoteWinSize: integer;
LocalWinSize: integer;
RemoteMaxPkt: integer;
LocalMaxPkt: integer;
LocalChannelID: integer;
RemoteChannelID: integer;
constructor Create(Owner: TObject); override;
property OnExtDataAvalible: TSSHChannelOnData
read GetOnExtDataAvalible write SetOnExtDataAvalible;
procedure Flush; override;
end;
implementation
uses sshsession, math, sshconst;
{ TSSHChannel }
constructor TSSHChannel.Create(Owner: TObject);
begin
Session := Owner;
FOnData := DefOnData;
OutBuffer := TSSHBuffer.Create(1000);
end;
{procedure TSSHChannel.DefOndata(Data: pointer; Len: integer);
begin
end;
}
procedure TSSHChannel.DefOndata(Data: pointer; Len: integer);
begin
end;
destructor TSSHChannel.Destroy;
begin
OutBuffer.Free;
inherited;
end;
procedure TSSHChannel.Flush;
begin
end;
function TSSHChannel.GetOnDataAvalible: TSSHChannelOnData;
begin
Result := FOnData;
end;
constructor TSSH2Channel.Create(Owner: TObject);
begin
inherited;
RemoteWinSize := 1000;
OnExtData := DefOnData;
end;
// SSH2 protocol does not allow full flush, we can only send as much as
// the remote server allows us do
procedure TSSH2Channel.Flush;
begin
TrySend;
end;
function TSSH2Channel.GetOnExtDataAvalible: TSSHChannelOnData;
begin
Result := OnExtData;
end;
procedure TSSHChannel.Send(Data: Pointer; Len: integer);
begin
SendDefer(Data, Len);
Flush;
end;
procedure TSSHChannel.SendDefer(Data: Pointer; Len: integer);
begin
OutBuffer.Add(Data, Len);
end;
procedure TSSHChannel.SetOnDataAvalible(const Value: TSSHChannelOnData);
begin
FOnData := Value;
end;
procedure TSSH2Channel.SetOnExtDataAvalible(const Value: TSSHChannelOnData);
begin
OnExtData := Value;
end;
function TSSH2Channel.TrySend: boolean;
var
ss: TSSH2Session;
len: integer;
begin
ss := TSSH2Session(Session);
while (OutBuffer.Length > 0) and (RemoteWinsize > 0) do
begin
len := min(RemoteWinSize, OutBuffer.Length);
len := min(len, RemoteMaxPkt);
ss.OutPacket.StartPacket(SSH2_MSG_CHANNEL_DATA);
ss.OutPacket.AddInteger(RemoteChannelId);
ss.OutPacket.AddInteger(len);
ss.OutPacket.AddBuffer(OutBuffer.Data, len);
ss.OutPacket.Write;
OutBuffer.Consume(len);
Dec(RemoteWinSize, len);
end;
Result := OutBuffer.Length <> 0;
OutBuffer.Shrink(OutBuffer.Length + 512);
end;
{ TSSH1Channel }
procedure TSSH1Channel.Flush;
var
ss: TSSH1Session;
len: integer;
begin
ss := TSSH1Session(Session);
while OutBuffer.Length > 0 do
begin
len := Min(SSH1MaxPkt, OutBuffer.Length);
ss.OutPacket.StartPacket(SSH1_CMSG_STDIN_DATA);
ss.OutPacket.AddInteger(len);
ss.OutPacket.AddBuffer(OutBuffer.Data, len);
ss.OutPacket.Write;
OutBuffer.Consume(len);
end;
OutBuffer.Shrink(4096);
end;
procedure TSSH1Channel.Send(Data: Pointer; Len: integer);
var
mylen: integer;
dat: PChar;
begin
dat := Data;
while len > 0 do
begin
mylen := min(len, ssh1maxpkt);
inherited Send(dat, mylen);
Inc(Dat, mylen);
Dec(len, mylen);
end;
end;
end.
|
{------------------------------------------------------------------------------
TDzNotepad component
Developed by Rodrigo Depine Dalpiaz (digao dalpiaz)
Non visual component to store TStrings at DFM file
https://github.com/digao-dalpiaz/DzNoteEditor
Please, read the documentation at GitHub link.
------------------------------------------------------------------------------}
unit DzNotepad;
interface
uses System.Classes;
type TDzNotepad = class(TComponent)
private
FAbout: string;
S: TStrings;
procedure SetLines(const Value: TStrings);
function GetCount: Integer;
function GetText: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Text: string read GetText;
property Count: Integer read GetCount;
procedure Add(const A: string);
procedure Sort;
procedure Clear;
function Has(const A: string): Boolean;
function AddIfNotEx(const A: string): Boolean;
published
property About: string read FAbout;
property Lines: TStrings read S write SetLines;
end;
implementation
const STR_VERSION = '1.7';
constructor TDzNotepad.Create(AOwner: TComponent);
begin
inherited;
FAbout := 'Digao Dalpiaz / Version '+STR_VERSION;
S := TStringList.Create;
end;
destructor TDzNotepad.Destroy;
begin
S.Free;
inherited;
end;
procedure TDzNotepad.SetLines(const Value: TStrings);
begin
S.Assign(Value);
end;
function TDzNotepad.GetCount: Integer;
begin
Result := S.Count;
end;
procedure TDzNotepad.Sort;
begin
TStringList(S).Sort;
end;
procedure TDzNotepad.Add(const A: string);
begin
S.Add(A);
end;
function TDzNotepad.GetText: string;
begin
Result := S.Text;
end;
procedure TDzNotepad.Clear;
begin
S.Clear;
end;
function TDzNotepad.Has(const A: string): Boolean;
begin
Result := ( S.IndexOf(A) <> (-1) );
end;
function TDzNotepad.AddIfNotEx(const A: string): Boolean;
begin
Result := not Has(A);
if Result then Add(A);
end;
end.
|
{$I-,Q-,R-,S-}
{Problem 8: Balanced Lineup [Coaches, 2004]
For the daily milking, Farmer John's N cows (1 <= N <= 50,000)
always line up in the same order. One day Farmer John decides to
organize a game of Ultimate Frisbee with some of the cows. To keep
things simple, he will take a contiguous range of cows from the
milking lineup to play the game. However, for all the cows to have
fun they should not differ too much in height.
Farmer John has made a list of Q (1 <= Q <= 200,000) potential
groups of cows and their heights (1 <= height <= 1,000,000). For
each group, he wants your help to determine the difference in height
between the shortest and the tallest cow in the group.
PROBLEM NAME: lineup
INPUT FORMAT:
* Line 1: Two space-separated integers, N and Q.
* Lines 2..N+1: Line i+1 contains a single integer that is the height
of cow i
* Lines N+2..N+Q+1: Two integers A and B (1 <= A <= B <= N),
representing the range of cows from A to B inclusive.
SAMPLE INPUT (file lineup.in):
6 3
1
7
3
4
2
5
1 5
4 6
2 2
OUTPUT FORMAT:
* Lines 1..Q: Each line contains a single integer that is a response
to a reply and indicates the difference in height between the
tallest and shortest cow in the range.
SAMPLE OUTPUT (file lineup.out):
6
3
0
}
const
mx = 50001;
var
fe,fs : text;
n,m : longint;
tab,nr,nl : array[1..mx] of longint;
procedure open;
var
i : longint;
begin
assign(fe,'lineup.in'); reset(fe);
assign(fs,'lineup.out'); rewrite(fs);
readln(fe,n,m);
for i:=1 to n do
readln(fe,tab[i]);
end;
procedure build;
var
i,k : longint;
begin
nl[n]:=0; nr[n]:=0;
for i:=n-1 downto 1 do { max }
begin
k:=i+1;
while tab[k] < tab[i] do
begin
k:=nr[k];
if k = 0 then
break;
end;
if k = 0 then
nr[i] := 0
else
nr[i]:=k;
end;
for i:=n-1 downto 1 do { min }
begin
k:=i+1;
while tab[k] > tab[i] do
begin
k:=nl[k];
if k = 0 then
break;
end;
if k = 0 then
nl[i] := 0
else
nl[i]:=k;
end;
end;
procedure work;
var
i,j,k,a,b,max,min : longint;
begin
build;
for i:=1 to m do
begin
readln(fe,a,b);
if a<b then
begin
k:=nr[a]; j:=a;
while (k<>0) and (k <= b) do
begin
j:=k;
k:=nr[k];
end;
max:=j;
k:=nl[a]; j:=a;
while (k<>0) and (k <= b) do
begin
j:=k;
k:=nl[k];
end;
min:=j;
writeln(fs,tab[max]-tab[min]);
end
else
writeln(fs,0);
end;
close(fe); close(fs);
end;
begin
open;
work;
end. |
unit BZK2_Actor;
interface
type
TBZK2Actor = class
private
Name : string;
Location : integer;
MyClass : string;
// I/O
procedure WriteName (var MyFile : System.Text);
procedure WriteLocation (var MyFile : System.Text);
procedure WriteClass (var MyFile : System.Text);
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
procedure WriteToFile (var MyFile : System.Text);
// Gets
function GetName : string;
function GetLocation : integer;
function GetClass : string;
// Sets
procedure SetName ( value : string);
procedure SetLocation ( value : integer);
procedure SetClass ( value : string);
// Assign
procedure Assign(const Actor : TBZK2Actor);
end;
implementation
// Constructors and Destructors
constructor TBZK2Actor.Create;
begin
Name := '';
Location := 1;
MyClass := 'DefaultClass';
end;
destructor TBZK2Actor.Destroy;
begin
Name := '';
MyClass := '';
inherited Destroy;
end;
// Gets
function TBZK2Actor.GetName : string;
begin
Result := Name;
end;
function TBZK2Actor.GetLocation : integer;
begin
Result := Location;
end;
function TBZK2Actor.GetClass : string;
begin
Result := MyClass;
end;
// Sets
procedure TBZK2Actor.SetName ( Value : string);
begin
Name := Value;
end;
procedure TBZK2Actor.SetLocation ( Value : integer);
begin
Location := Value;
end;
procedure TBZK2Actor.SetClass ( Value : string);
begin
MyClass := value;
end;
// I/O
procedure TBZK2Actor.WriteToFile (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Actor>');
WriteName(MyFile);
WriteLocation(MyFile);
WriteClass(MyFile);
WriteLn(MyFile,'</Actor>');
end;
procedure TBZK2Actor.WriteName (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Name>');
WriteLn(MyFile,Name);
WriteLn(MyFile,'</Name>');
end;
procedure TBZK2Actor.WriteLocation (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Location>');
WriteLn(MyFile,Location);
WriteLn(MyFile,'</Location>');
end;
procedure TBZK2Actor.WriteClass (var MyFile : System.Text);
begin
WriteLn(MyFile,'<Class>');
WriteLn(MyFile,MyClass);
WriteLn(MyFile,'</Class>');
end;
procedure TBZK2Actor.Assign(const Actor : TBZK2Actor);
begin
SetName(Actor.GetName);
SetLocation(Actor.GetLocation);
SetClass(Actor.GetClass);
end;
end.
|
Program BatailleNavale;
uses crt,sysutils;
CONST
NBBOAT=5; //nbr bateau max
CASEMAX=5; //nbr de case par bateau (MIN:3)
LINEMIN=1; //nbr ligne minimum de la map
LINEMAX=50; //nbr ligne maximum de la map
COLMIN=1; //nbr de colonne minimum
COLMAX=50; //nbr de colonne maximum
Type //énumérer
positionBoat=(enLigne,enColonne,enDiag);
etatBoat=(toucher,couler);
etatFlotte=(aFlot,aSombrer);
etatJoueur=(gagne,perd);
Type
cellule=record
ligne:Integer;
col:Integer;
END;
bateau=record
nCase:ARRAY [1..CASEMAX] OF cellule;
taille:Integer;
END;
flotte=record
nBoat:ARRAY [1..NBBOAT] OF bateau;
END;
//Fonction
Function tailleBoat(nBoat:bateau):Integer; //calcul la taille d'un bateau
VAR
i:Integer;
cpt:Integer;
BEGIN
cpt:=0;
FOR i:=1 TO CASEMAX DO
BEGIN
IF (nBoat.nCase[i].ligne<>0) OR (nBoat.nCase[i].col<>0) THEN
cpt:=cpt+1;
END;
tailleBoat:=cpt;
END;
Function etatBat(nBoat:bateau):etatBoat; //renvoi l'état du bateau si coulé
VAR
etat:Integer;
BEGIN
etat:=tailleBoat(nBoat);
IF (etat<nBoat.taille) AND (etat>0) THEN etatBat:=toucher
ELSE IF (etat=0) THEN etatBat:=couler;
END;
Function etatFlot(player:flotte):etatFlotte; //renvoi l'état de la flotte si sombré
VAR
i:Integer;
cpt:Integer;
BEGIN
cpt:=0;
FOR i:=1 TO NBBOAT DO
BEGIN
IF (etatBat(player.nBoat[i])=couler) THEN cpt:=cpt+1;
Delay(10);
END;
IF cpt=NBBOAT THEN etatFlot:=aSombrer
ELSE
etatFlot:=aFlot;
END;
Function cmpCase(nCellule,tCellule:cellule):boolean; //compare 2 cases
BEGIN
IF ((nCellule.col=tCellule.col) AND (nCellule.ligne=tCellule.ligne)) THEN
cmpCase:=true
ELSE
cmpCase:=False;
END;
Function createBateau(nCellule:cellule; taille:Integer):bateau; //initialise les valeur des bateaux
VAR
res:bateau;
posBateau:positionBoat;
i:Integer;
pos:Integer;
BEGIN
pos:=Random(3);
posBateau:=positionBoat(pos);
res.taille:=taille;
FOR i:=1 TO CASEMAX DO
BEGIN
IF (i<=taille) THEN
BEGIN
res.nCase[i].ligne:=nCellule.ligne;
res.nCase[i].col:=nCellule.col;
END
ELSE
BEGIN
res.nCase[i].ligne:=1;
res.nCase[i].col:=1;
END;
IF (posBateau=enLigne) THEN
nCellule.col:=nCellule.col+1
ELSE
IF (posBateau=enColonne) THEN
nCellule.ligne:=nCellule.ligne+1
ELSE
IF (posBateau=enDiag) THEN
BEGIN
nCellule.ligne:=nCellule.ligne+1;
nCellule.col:=nCellule.col+1;
END;
END;
createBateau:=res;
END;
//Procédure
Procedure CreateCase(l,c:Integer; VAR nCellule:cellule); //affecte les valeur x y a Pos
BEGIN
nCellule.ligne:=l;
nCellule.col:=c;
END;
Procedure fPlayer (VAR nBoat:bateau;VAR nCellule:cellule); //créer la flotte de chaque player
BEGIN
REPEAT
nBoat.taille:=Random(CASEMAX)+3;
UNTIL (nBoat.taille>2) AND (nBoat.taille<=CASEMAX);
REPEAT
CreateCase((Random(LINEMAX)+LINEMIN),(Random(COLMAX)+LINEMIN),nCellule);
UNTIL (nCellule.ligne>=LINEMIN) AND (nCellule.ligne<=LINEMAX-nBoat.taille) AND (nCellule.col>=COLMIN) AND (nCellule.col<=COLMAX-nBoat.taille);
nBoat:=createBateau(nCellule,nBoat.taille);
END;
Procedure initfPlayer(VAR player:flotte; nCellule:cellule); //initialisation des flottes
VAR
i,j:Integer;
BEGIN
FOR i:=1 TO NBBOAT DO
BEGIN
fPlayer(player.nBoat[i],nCellule);
FOR j:=1 TO CASEMAX DO
BEGIN
write(format('[%d,%d] ' , [player.nBoat[i].nCase[j].ligne,player.nBoat[i].nCase[j].col]));
END;
writeln;
END;
END;
Procedure attaquerBateau(VAR player:flotte); //gère les attaque entre les joueurs
VAR
nCellule:cellule;
test:boolean;
i,j:Integer;
BEGIN
REPEAT
writeln('Entrez la ligne [1-50]');
readln(nCellule.ligne);
IF (nCellule.ligne<1) OR (nCellule.ligne>50) THEN writeln('Erreur [1-50]');
UNTIL (nCellule.ligne>0) AND (nCellule.ligne<=50);
REPEAT
writeln('Entrez la colonne [1-50]');
readln(nCellule.col);
IF (nCellule.col<1) OR (nCellule.col>50) THEN writeln('Erreur [1-50]');
UNTIL (nCellule.col>0) AND (nCellule.col<=50);
FOR i:=1 TO NBBOAT DO
BEGIN
FOR j:=1 TO player.nBoat[i].taille DO
BEGIN
test:=False;
test:=cmpCase(nCellule,player.nBoat[i].nCase[j]);
IF test THEN
BEGIN
writeln('TOUCHER ! ');
CreateCase(0,0,player.nBoat[i].nCase[j]);
IF etatBat(player.nBoat[i])=couler THEN writeln('COULER ! ');
END;
END;
END;
END;
//Programme principal
VAR
nCellule:cellule;
i:Integer;
joueur1,joueur2:flotte;
etat1,etat2:etatJoueur;
etatfl1,etatfl2:etatFlotte;
BEGIN
clrscr;
randomize;
etat1:=gagne;
etat2:=gagne;
etatfl1:=aFlot;
etatfl2:=aFlot;
writeln('Initialisation des donnees du joueur 1.');
Delay(500);
initfPlayer(joueur1,nCellule);
writeln('Initialisation des donnees du joueur 2.');
Delay(500);
initfPlayer(joueur2,nCellule);
REPEAT
IF (etat1=gagne) AND (etat2=gagne) THEN
BEGIN
writeln('Joueur 1 : ');
attaquerBateau(joueur1);
END;
etatfl1:=etatFlot(joueur1);
IF etatfl1=aSombrer THEN
etat2:=perd;
IF (etat1=gagne) AND (etat2=gagne) THEN
BEGIN
writeln('Joueur 2 : ');
attaquerBateau(joueur2);
END;
etatfl2:=etatFlot(joueur2);
IF etatfl2=aSombrer THEN
etat1:=perd;
UNTIL ((etat1=perd) OR (etat2=perd)) AND ((etatfl1=aSombrer) OR (etatfl2=aSombrer));
IF etat1=perd THEN writeln('Joueur 2 remporte la partie')
ELSE writeln('Joueur 1 remporte la partie');
readln;
END. |
unit uExample;
interface
uses
Classes, SysUtils,
TestFrameWork;
type
TTestcaseTemplate = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestOnePlusOne;
end;
implementation
{ TTestCaseList }
//------------------------------------------------------------------------------
procedure TTestcaseTemplate.SetUp;
begin
end;
procedure TTestcaseTemplate.TearDown;
var
begin
end;
procedure TTestcaseTemplate.TestOnePlusOne;
begin
Check(2=1+1,'OnePlusOneNotEqualsTwo');
end;
initialization
RegisterTest('', TTestcaseTemplate.Suite);
end.
|
///////////////////////////////////////////////////////////////////////////////////////////////
//
// FileUtils.pas
// --------------------------
// Changed: 2002-12-31
// Maintain: Michael Vinther: meesoft.cjb.net || solo@meesoft.cjb.net
//
// Last change:
// GetDirList includes path from Search
//
unit FileUtils;
interface
uses Windows, SysUtils, Forms, ShellAPI, Classes, MemUtils, Controls, Messages;
var ProgramPath : string; // Path to program executable including '\'
// Append text line to file
procedure WriteLog(const FileName, LogLine: string);
// Execute file. Failure if Result<=32
function ExecuteFile(const FileName: string; const Params: string=''; const DefaultDir: string=''; ShowCmd: Integer=SW_SHOW): THandle;
// Return file name without extension
function RemoveFileExt(FileName: string): string;
// Return path name with a \ as the last character
function ForceBackslash(const PathName: string): string;
function RemoveBackslash(const PathName: string): string;
// Case sensitive compare with mask
const
SingleWildcard = '?';
MultiWildcard = '*';
function MaskCompare(Str,Mask: string): Boolean;
// Get size of file
function GetFileSize(FileName: string): Int64;
procedure GetDirList(const Search: string; List: TStrings);
// Delete file(s).
// Default is flags will recycle: FOF_ALLOWUNDO|FOF_NOCONFIRMATION|FOF_SILENT|FOF_NOERRORUI
// Multiple files can be seperated by #0, wildcards are allowed, full path must be specified
function DeleteFileEx(FileName: string; Flags: FILEOP_FLAGS=0): Boolean;
// Move file(s).
// Default is flags will recycle: FOF_NOCONFIRMMKDIR or FOF_NOCONFIRMATION or FOF_SILENT or FOF_NOERRORUI
// Multiple files can be seperated by #0, wildcards are allowed, full path must be specified
function MoveFile(Source,Dest: string; Flags: FILEOP_FLAGS=0): Boolean;
function MakeValidFileName(const Str: string): string;
// Show standard Windows dialogs
procedure ShowFileProperties(const FileName: string);
procedure ShowSearchDialog(const Directory: string);
function GetParameterFileName: string;
// Get file dropped by WM_DROPFILES
function GetDroppedFile(const Msg: TMessage; Index: Integer): string;
const
TabChar = #9;
implementation
function MakeValidFileName(const Str: string): string;
const
FileNameChars = ['A'..'Z','0'..'9','.','_','~','-','@'];
ReplaceChar = '_';
var
I : Integer;
begin
Result:=Str;
for I:=1 to Length(Result) do
if not (UpCase(Result[I]) in FileNameChars) then Result[I]:=ReplaceChar;
if Result='' then Result:='-';
if Result[1]='.' then Result:=ReplaceChar+Result;
if Length(Result)>255 then SetLength(Result,255);
end;
procedure GetDirList(const Search: string; List: TStrings);
var
SRec : TSearchRec;
E : Integer;
Path : string;
begin
Path:=ExtractFilePath(Search);
List.BeginUpdate;
E:=FindFirst(Search,faAnyFile,SRec);
try
while E=0 do
begin
if SRec.Attr and faDirectory<>0 then
begin
end
else if SRec.Attr and faVolumeID=0 then
begin
List.Add(Path+SRec.Name);
end;
E:=FindNext(SRec);
end;
finally
FindClose(SRec);
List.EndUpdate;
end;
end;
procedure WriteLog(const FileName, LogLine: string);
var Log : TextFile;
begin
try
Assign(Log,FileName);
{$I-} Append(Log); {$I+}
if IOResult<>0 then Rewrite(Log);
try
WriteLn(Log,LogLine);
finally
CloseFile(Log);
end;
except
end;
end;
// Execute file. ShowCmd is often SW_SHOW
function ExecuteFile(const FileName,Params,DefaultDir: string; ShowCmd: Integer): THandle;
begin
Result:=ShellExecute(Application.Handle,nil,
PChar(FileName),
PChar(Params),
PChar(DefaultDir),ShowCmd);
end;
function RemoveFileExt(FileName: string): string;
var P : Integer;
begin
for P:=Length(FileName) downto 1 do
if FileName[P]='\' then Break
else
if FileName[P]='.' then
begin
Result:=Copy(FileName,1,P-1);
Exit;
end;
Result:=FileName;
end;
function MaskCompare(Str,Mask: string): Boolean;
var
P : Integer;
begin
Result:=True;
for P:=1 to Length(Mask) do case Mask[P] of
SingleWildcard : if P>Length(Str) then
begin
Result:=False;
Exit;
end;
MultiWildcard : begin
if P=Length(Mask) then Exit;
Delete(Mask,1,P);
Delete(Str,1,P-1);
repeat
if MaskCompare(Str,Mask) then Exit; // Suitable substring found, return true
Delete(Str,1,1);
until Length(Str)=0;
Result:=False;
Exit;
end;
else if (P>Length(Str)) or (Str[P]<>Mask[P]) then
begin
Result:=False;
Exit;
end;
end;
if Length(Mask)<>Length(Str) then Result:=False;
end;
function ForceBackslash(const PathName: string): string;
begin
Result:=PathName;
if (PathName<>'') and (Result[Length(Result)]<>'\') then Result:=Result+'\';
end;
function RemoveBackslash(const PathName: string): string;
begin
Result:=PathName;
if (PathName<>'') and (Result[Length(Result)]='\') then SetLength(Result,Length(Result)-1);
end;
function GetFileSize(FileName: string): Int64;
var
Handle: THandle;
FindData: TWin32FindData;
begin
Result:=-1;
Handle:=FindFirstFile(PChar(FileName),FindData);
if Handle<>INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY)=0 then
begin
Result:=FindData.nFileSizeLow or (Int64(FindData.nFileSizeHigh) shl 32);
end;
end;
end;
function DeleteFileEx(FileName: string; Flags: FILEOP_FLAGS): Boolean;
var
fos : TSHFileOpStruct;
begin
if FileName='' then
begin
Result:=False;
Exit;
end;
if FileName[Length(FileName)]<>#0 then FileName:=FileName+#0;
ZeroMem(fos,SizeOf(fos));
with fos do
begin
Wnd:=Application.Handle;
wFunc:=FO_DELETE;
pFrom:=PChar(FileName);
if Flags=0 then fFlags:=FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT or FOF_NOERRORUI
else fFlags:=Flags;
end;
Result:=SHFileOperation(fos)=0;
end;
function MoveFile(Source,Dest: string; Flags: FILEOP_FLAGS=0): Boolean;
var
fos : TSHFileOpStruct;
begin
if (Source='') or (Dest='') then
begin
Result:=False;
Exit;
end;
if Source[Length(Source)]<>#0 then Source:=Source+#0;
if Dest[Length(Dest)]<>#0 then Dest:=Dest+#0;
ZeroMem(fos,SizeOf(fos));
with fos do
begin
Wnd:=Application.Handle;
wFunc:=FO_MOVE;
pFrom:=PChar(Source);
pTo:=PChar(Dest);
if Flags=0 then fFlags:=FOF_NOCONFIRMMKDIR or FOF_NOCONFIRMATION or FOF_SILENT or FOF_NOERRORUI
else fFlags:=Flags;
end;
Result:=SHFileOperation(fos)=0;
end;
function GetParameterFileName: string;
var
I : Integer;
begin
Result:=ParamStr(1);
for I:=2 to ParamCount do Result:=Result+' '+ParamStr(I);
end;
procedure ShowFileProperties(const FileName: string);
var
SEI : SHELLEXECUTEINFO;
begin
ZeroMem(SEI,SizeOf(SEI));
with SEI do
begin
cbSize:=SizeOf(SEI);
fMask:=SEE_MASK_NOCLOSEPROCESS or SEE_MASK_INVOKEIDLIST or SEE_MASK_FLAG_NO_UI;
Wnd:=Application.Handle;
lpVerb:='properties';
lpFile:=PChar(FileName);
end;
if not ShellExecuteEx(@SEI) then RaiseLastWin32Error;
end;
procedure ShowSearchDialog(const Directory: string);
var
SEI : SHELLEXECUTEINFO;
begin
ZeroMem(SEI,SizeOf(SEI));
with SEI do
begin
cbSize:=SizeOf(SEI);
fMask:=SEE_MASK_NOCLOSEPROCESS or SEE_MASK_INVOKEIDLIST or SEE_MASK_FLAG_NO_UI;
Wnd:=Application.Handle;
lpVerb:='find';
lpFile:=PChar(Directory);
end;
if not ShellExecuteEx(@SEI) then RaiseLastWin32Error;
end;
function GetDroppedFile(const Msg: TMessage; Index: Integer): string;
begin
SetLength(Result,DragQueryFile(Msg.wParam,Index,nil,0));
DragQueryFile(Msg.wParam,Index,@Result[1],Length(Result)+1);
end;
var P : Integer;
initialization
ProgramPath:=ParamStr(0); P:=Length(ProgramPath);
while (P>0) and (ProgramPath[P]<>'\') do Dec(P);
SetLength(ProgramPath,P);
end.
|
unit Material;
interface
uses dglOpenGL, BasicMathsTypes, TextureBank, TextureBankItem, ShaderBank, ShaderBankItem,
BasicFunctions, GlConstants, IntegerSet, SysUtils, Windows, Graphics,
Dialogs, Abstract2DImageData;
type
TMeshMaterial = class
private
procedure ClearTextures;
public
Ambient: TVector4f;
Diffuse: TVector4f;
Specular: TVector4f;
Shininess: Single;
Emission: TVector4f;
Shader: PShaderBankItem;
SrcAlphaBlend, DstAlphaBlend: GLINT;
Texture: array of PTextureBankItem;
// Constructors & Destructors
constructor Create(_ShaderBank: PShaderBank);
destructor Destroy; override;
// Gets
function GetTexture(_Type: integer):TBitmap;
procedure GetTextureData(_Type: integer; var _Image: TAbstract2DImageData);
function GetTextureID(_Type: integer):integer;
function GetLastTextureID: integer;
function GetNextTextureID: integer;
function GetTextureSize(_TextureID: integer): integer;
// Sets
procedure SetTextureNumMipmaps(_NumMipMaps, _Type: integer);
// Render
procedure Enable;
procedure Disable;
// Adds
procedure AddTexture(_TextureType: integer; const _Texture:PTextureBankItem);
procedure AddOrReplaceTexture(_TextureType: integer; const _Texture:PTextureBankItem);
// Copies
procedure Assign(const _MeshMaterial: TMeshMaterial);
// Misc
procedure ExportTextures(const _BaseDir, _Name, _Ext : string; var _UsedTextures : CIntegerSet; _previewTextures: boolean = false);
end;
PMeshMaterial = ^TMeshMaterial;
TAMeshMaterial = array of TMeshMaterial;
TSetShaderUniformFunc = procedure (const _Materials: TAMeshMaterial; _MaterialID,_TextureID: integer) of object;
implementation
uses GlobalVars;
// Constructors & Destructors
constructor TMeshMaterial.Create(_ShaderBank: PShaderBank);
begin
SetLength(Texture,0);
Ambient := SetVector4f(0.2,0.2,0.2,0.0);
Diffuse := SetVector4f(0.8,0.8,0.8,1.0);
Shininess := 0;
Specular := SetVector4f(0,0,0,1);
Emission := SetVector4f(0,0,0,1);
SrcAlphaBlend := GL_SRC_ALPHA;
DstAlphaBlend := GL_ONE_MINUS_SRC_ALPHA;
if _ShaderBank <> nil then
Shader := _ShaderBank^.Get(C_SHD_PHONG)
else
Shader := nil;
end;
destructor TMeshMaterial.Destroy;
begin
ClearTextures;
Shader := nil;
inherited Destroy;
end;
// Gets
function TMeshMaterial.GetTexture(_Type: integer):TBitmap;
var
tex: integer;
begin
for tex := Low(Texture) to High(Texture) do
begin
if Texture[tex] <> nil then
begin
if Texture[tex].TextureType = _Type then
begin
glActiveTexture(GL_TEXTURE0 + tex);
Result := Texture[tex]^.DownloadTexture(0);
glActiveTexture(GL_TEXTURE0);
exit;
end;
end;
end;
Result := nil;
end;
procedure TMeshMaterial.GetTextureData(_Type: integer; var _Image: TAbstract2DImageData);
var
tex: integer;
begin
for tex := Low(Texture) to High(Texture) do
begin
if Texture[tex] <> nil then
begin
if Texture[tex].TextureType = _Type then
begin
glActiveTexture(GL_TEXTURE0 + tex);
Texture[tex]^.DownloadTexture(0,_Image);
glActiveTexture(GL_TEXTURE0);
exit;
end;
end;
end;
end;
function TMeshMaterial.GetTextureID(_Type: integer):integer;
var
tex: integer;
begin
Result := -1;
for tex := Low(Texture) to High(Texture) do
begin
if Texture[tex] <> nil then
begin
if Texture[tex]^.TextureType = _Type then
begin
Result := tex;
exit;
end;
end;
end;
end;
function TMeshMaterial.GetLastTextureID: integer;
begin
Result := High(Texture);
end;
function TMeshMaterial.GetNextTextureID: integer;
begin
Result := High(Texture)+1;
end;
function TMeshMaterial.GetTextureSize(_TextureID: integer): integer;
begin
if (_TextureID >= 0) and (_TextureID <= High(Texture)) then
begin
Result := Texture[_TextureID]^.Size;
end
else
begin
Result := 0;
end;
end;
procedure TMeshMaterial.ClearTextures;
var
i: integer;
begin
for i := Low(Texture) to High(Texture) do
begin
if Texture[i] <> nil then
begin
GlobalVars.TextureBank.Delete(Texture[i]^.GetID);
Texture[i] := nil;
end;
end;
SetLength(Texture,0);
end;
// Sets
procedure TMeshMaterial.SetTextureNumMipmaps(_NumMipMaps, _Type: integer);
var
tex: integer;
begin
for tex := Low(Texture) to High(Texture) do
begin
if Texture[tex] <> nil then
begin
if Texture[tex]^.TextureType = _Type then
begin
Texture[tex]^.NumMipMaps := _NumMipMaps;
end;
end;
end;
end;
// Render
procedure TMeshMaterial.Enable;
begin
glEnable(GL_BLEND);
glBlendFunc(SrcAlphaBlend, DstAlphaBlend);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,PGLFloat(@(Ambient)));
glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,PGLFloat(@(Diffuse)));
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,PGLFloat(@(Specular)));
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,PGLFloat(@(Emission)));
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,Shininess);
if Shader <> nil then
begin
Shader^.UseProgram;
end;
end;
procedure TMeshMaterial.Disable;
begin
if Shader <> nil then
begin
Shader^.DeactivateProgram;
end;
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_BLEND);
end;
// Adds
procedure TMeshMaterial.AddTexture(_TextureType: integer; const _Texture:PTextureBankItem);
begin
SetLength(Texture,High(Texture)+2);
Texture[High(Texture)] := GlobalVars.TextureBank.Add(_Texture^.GetID);
Texture[High(Texture)]^.TextureType := _TextureType;
end;
procedure TMeshMaterial.AddOrReplaceTexture(_TextureType: integer; const _Texture:PTextureBankItem);
var
i: integer;
begin
for i := Low(Texture) to High(Texture) do
begin
if Texture[i] <> nil then
begin
if Texture[i]^.TextureType = _TextureType then
begin
// Texture[i]^.
exit;
end;
end;
end;
AddTexture(_TextureType, _Texture);
end;
// Copies
procedure TMeshMaterial.Assign(const _MeshMaterial: TMeshMaterial);
var
i : integer;
begin
ClearTextures;
SetLength(Texture,High(_MeshMaterial.Texture)+1);
for i := Low(Texture) to High(Texture) do
begin
if _MeshMaterial.Texture[i] <> nil then
begin
Texture[i] := GlobalVars.TextureBank.Clone(_MeshMaterial.Texture[i]^.GetID);
end
else
begin
Texture[i] := nil;
end;
end;
Ambient := SetVector4f(_MeshMaterial.Ambient.X,_MeshMaterial.Ambient.Y,_MeshMaterial.Ambient.Z,_MeshMaterial.Ambient.W);
Diffuse := SetVector4f(_MeshMaterial.Diffuse.X,_MeshMaterial.Diffuse.Y,_MeshMaterial.Diffuse.Z,_MeshMaterial.Diffuse.W);
Shininess := _MeshMaterial.Shininess;
Specular := SetVector4f(_MeshMaterial.Specular.X,_MeshMaterial.Specular.Y,_MeshMaterial.Specular.Z,_MeshMaterial.Specular.W);
Emission := SetVector4f(_MeshMaterial.Emission.X,_MeshMaterial.Emission.Y,_MeshMaterial.Emission.Z,_MeshMaterial.Emission.W);
Shader := _MeshMaterial.Shader;
end;
// Misc
procedure TMeshMaterial.ExportTextures(const _BaseDir, _Name, _Ext : string; var _UsedTextures : CIntegerSet; _previewTextures: boolean = false);
var
tex: integer;
begin
for tex := Low(Texture) to High(Texture) do
begin
if Texture[tex] <> nil then
begin
if _UsedTextures.Add(Texture[tex]^.GetID) then
begin
glActiveTexture(GL_TEXTURE0 + tex);
// Texture[tex]^.SaveTexture(_BaseDir + Name + '_' + IntToStr(ID) + '_' + IntToStr(mat) + '_' + IntToStr(tex) + '.' + _Ext);
Texture[tex]^.SaveTexture(_BaseDir + _Name + '_' + IntToStr(tex) + '.' + _Ext);
if (_previewTextures) then
begin
RunAProgram(_BaseDir + _Name + '_' + IntToStr(tex) + '.' + _Ext,'','');
end;
end;
end;
end;
end;
end.
|
unit uWizImportVendor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentWizImp, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, Provider, DBClient, ImgList, StdCtrls,
ExtCtrls, Grids, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
Buttons, ComCtrls, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, Mask, DateBox,
uParentWizExp, ADODB;
const
NAME_FILE_PO = '(PO)';
NAME_FILE_VENDORCODE = '(VC)';
NAME_FILE_ACCOUNT = '(ACC)';
INDEX_NAME_FILE_PO = 3;
INDEX_NAME_FILE_VENDORCODE = 4;
INDEX_NAME_FILE_ACCOUNT = 5;
HEADER_CONFIG_PO = '(PO)';
HEADER_CONFIG_VENDORNAME = '(VNA)';
INDEX_HEADER_CONFIG_PO = 3;
INDEX_HEADER_CONFIG_VENDORCODE = 4;
type
TWizImportVendor = class(TParentWizExp)
gbSupplier: TGroupBox;
Label11: TLabel;
edPONumber: TEdit;
btnClearList: TBitBtn;
Label4: TLabel;
Label21: TLabel;
procedure btnAddFormatClick(Sender: TObject);
procedure btnAddHeaderConfigClick(Sender: TObject);
procedure btnClearListClick(Sender: TObject);
private
IDFornecedor : Integer;
procedure RestoreFromRegistry;
procedure AddDefaultColumnsToListGrid;
procedure LoadVendorValues;
procedure SaveVendorValues;
protected
function TestBeforeNavigate:Boolean; override;
function OnAfterChangePage:Boolean; override;
function DoFinish:Integer; override;
function VerifyFieldsRequired: Boolean;
procedure SetFileName; override;
procedure SetHeaderConfig; override;
procedure ConfigFileFormatScreen; override;
procedure SaveFileName(Value: String); override;
function OnBeforeNextClick: Boolean; override;
public
{ Public declarations }
end;
implementation
uses uMsgBox, uDMGlobalNTier, uParamFunctions, uDMImportExport, uSystemConst, uNumericFunctions,
uParentWizard;
{$R *.dfm}
{==============================================================================}
{ Vendor controls
constructor TVendor.Create(IDPessoa : Variant);
begin
IDVendor := IDPessoa;
end;
procedure TWizImportVendor.AddComboVendor;
begin
//Limpar os Obetos Tvendor da Combo
ClearComboVendor;
DMImportExport.cdsLookupVendor.First;
while not DMImportExport.cdsLookupVendor.Eof do
begin
//cbVendorList.Items.Add(DMImportExport.cdsLookupVendor.Fields.FieldByName('Vendor').AsString);
cbVendorList.Items.AddObject(DMImportExport.cdsLookupVendor.Fields.FieldByName('Vendor').AsString,
TVendor.Create(DMImportExport.cdsLookupVendor.Fields.FieldByName('IDVendor').AsVariant));
DMImportExport.cdsLookupVendor.Next;
end;
end;
procedure TWizImportVendor.ClearComboVendor;
var
Vendor : TVendor;
begin
while cbVendorList.Items.Count > 0 do
begin
Vendor := TVendor(cbVendorList.Items.Objects[0]);
FreeAndNil(Vendor);
cbVendorList.Items.Delete(0);
end;
cbVendorList.Clear;
end;
{------------------------------------------------------------------------------}
{==============================================================================}
{ TWizImportVendor }
function TWizImportVendor.DoFinish: Integer;
begin
Result := inherited DoFinish;
end;
function TWizImportVendor.OnAfterChangePage: Boolean;
var
sError : string;
begin
Result := inherited OnAfterChangePage;
if pgOption.ActivePage.Name = 'tsList' then
begin
ScreenStatusWait;
grdFileTableView.DataController.DataSource := dtsFile;
cdsFile.Data := DMImportExport.ExportConn.AppServer.ExportPO(cdsFile.Data, edPONumber.Text, sError);
LogError.Text := sError;
fRegistryPath := MR_BRW_REG_PATH + 'MRImportExport\ExpPO\Vendor_' + cdsFile.FieldByName('IDVendor').AsString;
IDFornecedor := cdsFile.FieldByName('IDVendor').AsInteger;
if RegisterExists(fRegistryPath) then
begin
AddColumnsToListGrid;
if not (cdsFile.IsEmpty) then
RestoreFromRegistry;
end
else
AddDefaultColumnsToListGrid;
LoadVendorValues;
ScreenStatusOk;
end;
end;
function TWizImportVendor.OnBeforeNextClick: Boolean;
begin
if pgOption.ActivePage.Name = 'tsConfigFile' then
SaveVendorValues;
Result := True;
end;
procedure TWizImportVendor.RestoreFromRegistry;
begin
inherited;
end;
function TWizImportVendor.TestBeforeNavigate: Boolean;
begin
Result := inherited TestBeforeNavigate;
if pgOption.ActivePage.Name = 'tsSpecificConfig' then
begin
if not(VerifyFieldsRequired) then
begin
MsgBox('Field Required!', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
AddSpecificConfigList('PONumber',edPONumber.Text);
AddSpecificConfigList('IDUser', IntToStr(DMImportExport.FUser.ID));
end;
end;
function TWizImportVendor.VerifyFieldsRequired: Boolean;
begin
Result := True;
if (edPONumber.Text = '') then
Result := False;
end;
procedure TWizImportVendor.btnAddFormatClick(Sender: TObject);
var
OptionName : String;
begin
inherited;
case cbxFileFormat.ItemIndex of
INDEX_NAME_FILE_PO : OptionName := NAME_FILE_PO;
INDEX_NAME_FILE_VENDORCODE : OptionName := NAME_FILE_VENDORCODE;
INDEX_NAME_FILE_ACCOUNT : OptionName := NAME_FILE_ACCOUNT;
end;
if OptionName <> '' then
AddtoFileName(OptionName);
end;
procedure TWizImportVendor.SetFileName;
var
Year, Month, Day: String;
begin
inherited;
if edtFileFormat.text <> '' then
begin
Year := FormatDateTime('yyyy',Now);
Month := FormatDateTime('mm',Now);
Day := FormatDateTime('dd',Now);
fFileName := edtFileFormat.Text;
fFileName := StringReplace(fFileName, NAME_FILE_DAY, Day, [rfReplaceAll]);
fFileName := StringReplace(fFileName, NAME_FILE_MONTH, Month, [rfReplaceAll]);
fFileName := StringReplace(fFileName, NAME_FILE_YEAR, Year, [rfReplaceAll]);
fFileName := StringReplace(fFileName, NAME_FILE_PO, SpecificConfig.Values['PONumber'], [rfReplaceAll]);
fFileName := StringReplace(fFileName, NAME_FILE_VENDORCODE, cdsFile.FieldByName('Usercode').AsString, [rfReplaceAll]);
fFileNAme := StringReplace(fFileName, NAME_FILE_ACCOUNT, cdsFile.FieldByName('VendorAccount').AsString, [rfReplaceAll]);
end
else
fFileName := cdsFile.FieldByName('StoreName').AsString;
fFileName := RemoveInvalidCaracter(fFileName) + '.txt';
end;
procedure TWizImportVendor.btnAddHeaderConfigClick(Sender: TObject);
begin
case cbxHeaderConfig.ItemIndex of
INDEX_HEADER_CONFIG_ADDRESS : mHeaderConfig.Lines.Add(HEADER_CONFIG_ADDRESS);
INDEX_HEADER_CONFIG_CITY : mHeaderConfig.Lines.Add(HEADER_CONFIG_CITY);
INDEX_HEADER_CONFIG_CEP : mHeaderConfig.Lines.Add('(ZIP)');
INDEX_HEADER_CONFIG_PO : mHeaderConfig.Lines.Add(HEADER_CONFIG_PO);
INDEX_HEADER_CONFIG_VENDORCODE : mHeaderConfig.Lines.Add(HEADER_CONFIG_VENDORNAME);
else mHeaderConfig.Lines.Add(cbxHeaderConfig.Text);
end;
end;
procedure TWizImportVendor.SetHeaderConfig;
var
i : Integer;
Line : String;
begin
inherited;
for i :=0 to Pred(mHeaderConfig.Lines.Count) do
begin
Line := mHeaderConfig.Lines[i];
while Pos('(ADD)', Line) > 0 do
Line := StringReplace(Line, '(ADD)', cdsFile.FieldByName('Vendor').AsString, [rfReplaceAll]);
while Pos('(CTY)', Line) > 0 do
Line := StringReplace(Line, '(CTY)', cdsFile.FieldByName('City').AsString, [rfReplaceAll]);
while Pos('(ZIP)', Line) > 0 do
Line := StringReplace(Line, '(ZIP)', cdsFile.FieldByName('ZIP').AsString, [rfReplaceAll]);
while Pos('(PO)', Line) > 0 do
Line := StringReplace(Line, '(PO)', SpecificConfig.Values['PONumber'], [rfReplaceAll]);
while Pos('(VNA)', Line) > 0 do
Line := StringReplace(Line, '(VNA)', cdsFile.FieldByName('Vendor').AsString, [rfReplaceAll]);
mHeaderConfig.Lines[i] := Line;
end;
end;
procedure TWizImportVendor.ConfigFileFormatScreen;
begin
inherited;
lbInfo.Caption := 'Export Po File Format';
end;
procedure TWizImportVendor.SaveFileName(Value: String);
begin
inherited;
//
end;
procedure TWizImportVendor.AddDefaultColumnsToListGrid;
var
i: Integer;
NewColumn: TcxGridDBColumn;
begin
grdFileTableView.ClearItems;
for i := 0 to Pred(cdsFile.FieldDefs.Count) do
begin
NewColumn := grdFileTableView.CreateColumn;
with NewColumn do
begin
Caption := cdsFile.FieldDefs[i].DisplayName;
Name := 'grdFileTableViewDB' + cdsFile.FieldDefs[i].DisplayName;
DataBinding.FieldName := cdsFile.FieldDefs[i].Name;
if (cdsFile.FieldDefs[i].DisplayName <> 'Barcode') and
(cdsFile.FieldDefs[i].DisplayName <> 'Qty') and
(cdsFile.FieldDefs[i].DisplayName <> 'CaseQty') and
(cdsFile.FieldDefs[i].DisplayName <> 'VendorCode') and
(cdsFile.FieldDefs[i].DisplayName <> 'Model') then
Visible := False;
end;
end;
end;
procedure TWizImportVendor.LoadVendorValues;
var
sDelimiterSeparator, sDecimalSeparator, sHeaderConfig, sFileFormat, sError: String;
sHeaderFile: WordBool;
begin
sError := DMImportExport.GetConfigExport(
IDFornecedor,
EXPORT_TYPE_PO,
sDelimiterSeparator,
sDecimalSeparator,
sHeaderConfig,
sFileFormat,
sHeaderFile);
LogError.Text := sError;
if LogError.Text = '' then
begin
edtPath.Text := DMImportExport.GetAppProperty('ConfigExport_' + IntTostr(IDFornecedor), 'PO_FilePath');
edtDelimiter.Text := sDelimiterSeparator;
edtDecimalDelimiter.Text := sDecimalSeparator;
mHeaderConfig.Lines.CommaText := sHeaderConfig;
edtFileFormat.Text := sFileFormat;
cbxColumnsHeaderFile.Checked := sHeaderFile;
end
end;
procedure TWizImportVendor.SaveVendorValues;
var
sError : String;
begin
DMImportExport.SetAppProperty('ConfigExport_' + IntTostr(IDFornecedor), 'PO_FilePath', edtPath.Text);
sError := DMImportExport.InsertConfigExport(
IDFornecedor,
edtDelimiter.Text,
edtDecimalDelimiter.Text,
mHeaderConfig.Lines.CommaText,
edtFileFormat.Text,
cbxColumnsHeaderFile.Checked,
EXPORT_TYPE_PO);
LogError.Text := sError;
if LogError.Text <> '' then
begin
MsgBox(LogError.Text, vbCritical + vbOkOnly);
end;
end;
procedure TWizImportVendor.btnClearListClick(Sender: TObject);
begin
inherited;
mHeaderConfig.Clear;
end;
end.
|
// Portable Compiled Format
unit fi_pcf;
interface
implementation
uses
fi_common,
fi_info_reader,
fi_bdf,
classes,
math,
streamex,
sysutils;
const
PCF_FILE_VERSION = $70636601; // '\1pcf'
PCF_PROPERTIES = 1 shl 0;
PCF_FORMAT_MASK = $FFFFFF00;
PCF_BYTE_MASK = 1 shl 2;
PCF_DEFAULT_FORMAT = $00000000;
type
TPCFTOC = packed record
version,
count: LongWord;
end;
TPCFTOCRec = packed record
type_,
format,
size,
offset: LongWord;
end;
TPCFPropertyRec = packed record
nameOffset: LongInt;
isString: Byte;
value: LongInt;
end;
procedure ReadProperties(stream: TStream; var info: TFontInfo);
var
format,
numProperties,
i: LongInt;
bigEndian: Boolean;
readDw: function: LongWord of object;
properties: array of TPCFPropertyRec;
stringsLen: LongInt;
strings: array of AnsiChar;
dst: PString;
begin
format := stream.ReadDWordLE;
if format and PCF_FORMAT_MASK <> PCF_DEFAULT_FORMAT then
raise EStreamError.Create(
'The PCF properties table has a non-default format');
bigEndian := format and PCF_BYTE_MASK = PCF_BYTE_MASK;
if bigEndian then
readDw := @stream.ReadDWordBE
else
readDw := @stream.ReadDWordLE;
numProperties := readDw();
if numProperties <= 0 then
raise EStreamError.CreateFmt(
'The PCF properties table has a wrong number of properties (%d)',
[numProperties]);
SetLength(properties, numProperties);
stream.ReadBuffer(properties[0], numProperties * SizeOf(TPCFPropertyRec));
if numProperties and 3 <> 0 then
stream.Seek(4 - numProperties and 3, soCurrent);
stringsLen := readDw();
if stringsLen <= 0 then
raise EStreamError.CreateFmt(
'The PCF properties table has a wrong size of strings (%d)',
[stringsLen]);
SetLength(strings, stringsLen);
stream.ReadBuffer(strings[0], stringsLen);
strings[stringsLen - 1] := #0;
for i := 0 to numProperties - 1 do
begin
if properties[i].isString = 0 then
continue;
{$IFDEF ENDIAN_BIG}
if not bigEndian then
{$ELSE}
if bigEndian then
{$ENDIF}
with properties[i] do
begin
nameOffset := SwapEndian(nameOffset);
value := SwapEndian(value);
end;
if not InRange(properties[i].nameOffset, 0, stringsLen) then
raise EStreamError.CreateFmt(
'The PCF property %d name offset is out of bounds [0..%d]',
[i + 1, stringsLen]);
if not InRange(properties[i].value, 0, stringsLen) then
raise EStreamError.CreateFmt(
'The PCF property %d ("%s") value offset is out of bounds [0..%d]',
[i + 1, PAnsiChar(@strings[properties[i].nameOffset]), stringsLen]);
case String(PAnsiChar(@strings[properties[i].nameOffset])) of
BDF_COPYRIGHT: dst := @info.copyright;
BDF_FAMILY_NAME: dst := @info.family;
BDF_FONT: dst := @info.psName;
BDF_FONT_VERSION: dst := @info.version;
BDF_FOUNDRY: dst := @info.manufacturer;
BDF_FULL_NAME, BDF_FACE_NAME: dst := @info.fullName;
BDF_WEIGHT_NAME: dst := @info.style;
else
continue;
end;
dst^ := String(PAnsiChar(@strings[properties[i].value]));
end;
end;
procedure ReadPCFInfo(stream: TStream; var info: TFontInfo);
var
toc: TPCFTOC;
tocRec: TPCFTOCRec;
i: LongWord;
begin
stream.ReadBuffer(toc, SizeOf(toc));
{$IFDEF ENDIAN_BIG}
with toc do
begin
version := SwapEndian(version);
count := SwapEndian(count);
end;
{$ENDIF}
if toc.version <> PCF_FILE_VERSION then
raise EStreamError.Create('Not a PCF file');
if toc.count = 0 then
raise EStreamError.Create('PCF has no tables');
for i := 0 to toc.count - 1 do
begin
stream.ReadBuffer(tocRec, SizeOf(tocRec));
{$IFDEF ENDIAN_BIG}
with tocRec do
begin
type_ := SwapEndian(type_);
format := SwapEndian(format);
size := SwapEndian(size);
ofset := SwapEndian(ofset);
end;
{$ENDIF}
if tocRec.type_ = PCF_PROPERTIES then
begin
if tocRec.format and PCF_FORMAT_MASK <> PCF_DEFAULT_FORMAT then
raise EStreamError.Create(
'The PCF TOC has a non-default format for the properties table');
stream.Seek(tocRec.offset, soBeginning);
ReadProperties(stream, info);
break;
end;
end;
BDF_FillEmpty(info);
info.format := 'PCF';
end;
initialization
RegisterReader(@ReadPCFInfo, ['.pcf']);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.