//{$DEFINE CADImport6}
unit U_ImportDXF;

interface

uses windows, Dialogs, PowerCad, SysUtils, U_Cad, DrawObjects, Clipbrd, Classes, PCTypesUtils, Math, ShellApi, tlhelp32, forms,
  FastStrings, Messages, Graphics, Controls, StdCtrls, ExtDlgs, ExtCtrls,
  {$IF Defined(CADImport6)}
    DXFImage_EXP, ExtData, sgFunction, sgTools,
  {$ELSE}
    DXF, sgFunction, ExtData, sgTools,
  {$IFEND}
  DXFConv, Extrusion, U_DXFEngineSCS, PCDrawing,
  DWG, HPGL2, SVG, CGM,
  sgConsts, MVFont, U_SCSLists, {Tolik} SGLines, SGLists;

  procedure LoadDXFFile(aPCad: TPowerCad);
  procedure LoadDXFFileNew(aPCad: TPowerCad; aTitle, aFilter: string; aFile: String=''; aAllowScale: Boolean=true);
  procedure LoadDXFFileWithName(aPCad: TPowerCad; aFName: string);

  function ImportDXF(aFileName: string): Boolean;

  function ConvertDWGToDXF(aDWGFileName: string): string;
  function DxfColorToColor(aColor: Integer): Longint;
  function GetImportLayerNbr(aCad: TPCDrawing; aDxfLayer: TsgDXFLayer): Integer;

  // NEW
  function ModificatePoint(aP: TFPoint): TFPoint;
  function PointToString(const P: TFPoint): string;
  function ImportTextFont(Sender: TObject): string;
  function GetDXFBlock(aID: Integer): TBlock;
  function CheckAnyText(aStr: string): Boolean;
  //Tolik
 // Function ConvUtf8ToStr(aString: string): string;
  function utf16decode(encodeIn: string):string;
type
  TF_Import = class(TMyObject)
    FEntitiesCount: Integer;
    // Tolik --06/01/2016
    FBlockCount: integer;
    //
    FTextPrevPt: TFPoint;
    FTextUsePrevPt: Boolean;

    function ImportText(Sender: TObject): TFigure;
    function ImportSolid(Sender: TObject): TFigure;
    function ImportLine(Sender: TObject): TFigure;
    function ImportPoint(Sender: TObject): TFigure;
    function ImportEllipse(Sender: TObject): TFigure;
    function ImportArc(Sender: TObject): TFigure;
    function ImportCircle(Sender: TObject): TFigure;
    function ImportPolyLine(Sender: TObject): TFigure;
    // Tolik
    // function ImportLWPolyLine(Sender: TObject): TFigure;
    //
    function ImportAttdef(Sender: TObject): TFigure;
    function ImportSpline(Sender: TObject): TFigure;
    function ImportLeader(Sender: TObject): TFigure;
    function ImportHatch(Sender: TObject): TList;//TFigure;
    function ImportViewPortBegin(Sender: TObject): TFigure;
    function ImportViewPortEnd(Sender: TObject): TFigure;
    function ReadCADEntities(Entity: TsgDXFEntity): Integer;
    function FinishReadCADEntities(Entity: TsgDXFEntity): Integer;
    // Tolik -- 03/01/2016 --
    Procedure SimpleReadCADEntities(Entity: TsgDXFEntity);
    //05/01/2016
    function CheckIsLoaded(Entity: TsgDXFEntity): Boolean;
    //
    constructor Create;
  end;
  // ***

var
  F_Import: TF_Import;
  IsModelExist: Boolean = False;
  IsBlockInBlockExist: Boolean = False;
  TxtFile: TStringList;
  FCADParams: TsgCADIterate;
  FDXFObjectsList: TList;
  FDXFBlocksList: TList;
  // Tolik
  HandleList: TStringList;
  //
  // Formats
  {$IF Defined(CADImport6)}
    ImgDXF: TsgDXFImage;
  {$ELSE}
    ImgDXF: TsgCADDXFImage;
  {$IFEND}
  ImgDWG: TsgDWGImage;
  ImgSVG: TsgSVGImage;
  ImgHPGL: TsgHPGLImage;
  NumberOfPartsInSpline: Integer = 10;
  LimitDXFPolyCount: integer = 500;
  // Tolik
  ReadedEntCount: Integer = 0;
implementation

uses U_ProtectionCommon, {LoadDXF, }USCS_Main, U_Common, U_BaseCommon, PCDrawBox, U_Constants, U_Layers,
  CADImage;
//Tolik
// перепроверить try..except.
function utf16decode(encodeIn: string):string;
var
  presult,psource:PChar;
  s:string;
  buf,code:Integer;
  encode: string;
  tmpch: Char;
begin
  if (Pos('\U+', encodeIn) = 0) and (Pos('_U+', encodeIn) = 0) then
    Result := encodeIn
  else
  begin
    try
      //encode := FastReplace(encodein, '\U+', '\x', True);
      encode := encodeIn;
      SetLength(result, length(encode));
      presult:=pchar(result);
      psource:=pchar(encode);

      while psource^<>#0 do
      begin
        if (psource^='\') or (psource^='_') then
        begin
          tmpch := psource^;
          inc(psource);
          if psource^='U' then
          begin
            inc(psource);
            if psource^='+' then
            begin
              //inc(psource);
              //psource^:='x';
              SetString(s,psource,5);
              s[1] := 'x';
              Val(s,buf,code);
              if buf>=$100 then
              begin

                s:=WideChar(buf);
                presult^:=s[1];
              end
              else
                presult^:=chr(buf);
              Inc(psource,5);
            end
            else
            begin
              presult^ := tmpch;
              inc(presult);
              presult^ := 'U';  //  '\'
            end
          end
          else
            presult^ := tmpch;  //  '\'
         end
        else
        begin
          presult^:=psource^;
          Inc(psource);
        end;
        Inc(presult);
      end;
      SetLength(result, presult - pchar(Result));
    except
      result:='error';
    end;
  end;
end;

 //  Если юзать, то переработать на посимвольную обработку
{function ConvUtf8ToStr(aString: String): String;
Var
  Prefix: string;
  ss, sss: string;
  w: UTF8String;
  ww: WideString;
  i, j: Integer;
  ch: PWideChar;
  p: Pointer;
  currPos : integer;
  wChar: WideChar;
  Delagain: Boolean;
  simbolCode: Integer;
  StringChanged: Boolean;


  function HexToInt(h: string): integer;
  var
    i, c: integer;
  begin
    val('$'+h, i, c);
    if c > 0 then HexToInt := -1
    else HexToInt := i;
  end;
begin
  j := Pos('\U+', aString);
  if j = 0 then
    Result := aString
  else
  begin
    // Define Prefix
    Prefix := '';
    if j > 1 then
    begin
      j := j - 1;
      for i := 1 to j do
      begin
        Prefix := Prefix + aString[i];
      end;
    end;
    j := Length(Prefix);
    ss := aString;
    // get string without Prefix
    Delete(ss, Pos(Prefix, ss),j);
    // Deleting Delimiters
    delAgain := true;
    While DelAgain do
    begin
      DelAgain := False;
      if Pos('\U+', ss) <> 0 then
      begin
        DelAgain := True;
        Delete(ss,Pos('\U+', ss),3);
      end;
    end;
    //
    Result := '';
    ww := '';
    sss := '';
    i := 1;
    While i <= Length(ss) do
    begin
      if ss[i] <> ' ' then
      begin
        sss := '';
        for j := 1 to 4 do
        begin
          sss := sss + ss[i];
          Inc(i);
        end;
        simbolCode := HexToInt(sss);

        wChar := WideChar(simbolCode);
        ww := ww+wChar;
        Result := AnsiString(ww);
      end
      else
      begin
        ww := ww + ' ';
        Inc(i);
      end;
    end;
    Result := Prefix + AnsiString(ww);
  end;
end;  }

function GetColor(Sender: TObject): integer;
var
  C: TColor;
  CBack: TColor;
begin
  result := clBlack;
  CBack := GCadForm.PCad.PageColor;
  //C := TsgDXFPolyLine(Sender).Color;
  //Poly.Color := EntColor(TsgDXFSolid(Sender), nil);
  C := EntColor(TsgDXFEntity(Sender), FCADParams.Insert);
  if C = clNone then
  begin
    if (GetBValue(CBack) < 56) and (GetRValue(CBack) < 56) and (GetGValue(CBack) < 56) then
      C := clWhite;
    if (GetBValue(CBack) > 200) and (GetRValue(CBack) > 200) and (GetGValue(CBack) > 200) then
      C := clBlack;
  end;
  Result := C;
end;

function ConvertDWGToDXF(aDWGFileName: string): string;
var
  ProgStr: string;
  ParamStr: string;
  fromDir, outDir: string;
  SCSTmpDir: string;

  c1: Cardinal;
  pe: TProcessEntry32;
  s1: string;
  x: integer;
  FContinue: boolean;
begin
  try
    Result := '';
    ProgStr := GetEXEDir + '\DWG\DWG.exe';
    SCSTmpDir := GetPathToSCSTmpDir;
    if DirectoryExists(SCSTmpDir + '\DWG') then
      FullRemoveDir(SCSTmpDir + '\DWG', true, true);
    CreateDir(SCSTmpDir + '\DWG');
    CreateDir(SCSTmpDir + '\DWG\OUT');
    fromDir := SCSTmpDir + '\DWG';
    outDir := SCSTmpDir + '\DWG\OUT';
    CopyFile(PChar(aDWGFileName), PChar(fromDir + '\temp.dwg'), False);
    ParamStr := fromDir + ' ' + outDir + ' ' + '"ACAD12" "DXF" "0" "0"';
    ShellExecute(FSCS_Main.Handle, 0, PChar(ProgStr), PChar(ParamStr), 0, SW_HIDE);
    Result := outDir + '\temp.dxf';

    repeat
    X := 0;
    FContinue := True;
    c1 := CreateToolHelp32Snapshot(TH32CS_SnapProcess, 0);
    try
      pe.dwSize := sizeof(pe);
      if Process32First(c1, pe) then
      repeat
        s1 := ExtractFileName(pe.szExeFile);
        if s1 = 'DWG.exe' then
        begin
          inc(x);
          FContinue := False;
        end;
      until not Process32Next(c1, pe);
    finally
      CloseHandle(c1);
    end;
    until FContinue;
  except
    on E: Exception do AddExceptionToLogEx('U_ImportDXF.ConvertDWGToDXF', E.Message);
  end;
end;


procedure LoadDXFFile(aPCad: TPowerCad);
var
  i, Count: Integer;
  OpenDXF: TOpenDialog;
  tempstr: string;
  DXFObject: TFigureGrp;
  Bnd: TDoubleRect;
  Cad_X, Cad_Y, Cad_CenterX, Cad_CenterY: Double;
  Dxf_X, Dxf_Y, Dxf_CenterX, Dxf_CenterY: Double;
  ScaleDelta: Double;
  fContinue: Boolean;
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  buffer: PChar;
  TempStream: TMemoryStream;
  mess: string;
  vLayer: TLayer;
  DXFFileName, DWGFileName, TXTFileName: string;
begin
  OpenDXF := TOpenDialog.Create(nil);
  with OpenDXF do
  begin
    InitialDir := GetEXEDir + '\DXF';
    Title := cImport_Mes4;
    Filter := cImport_Mes5;
    DefaultExt := '*.dxf, *.dwg';
    FileName := '';
    Options := [ofReadOnly,ofHideReadOnly,ofPathMustExist,ofFileMustExist];
  end;

  if OpenDXF.Execute then
  begin
    try
      BeginProgress;
      tempstr := AnsiLowerCase(OpenDXF.FileName);
      GCadForm.CurrentLayer := 1;
      if pos('.wmf', OpenDXF.FileName) <> 0 then
        aPCad.ImportWMF(1, OpenDXF.FileName, False)
      else
      begin
        DXFFileName := OpenDXF.FileName;
        // ****************** DWG - DXF **************************************
        if pos('.dwg', OpenDXF.FileName) <> 0 then
        begin
          DWGFileName := OpenDXF.FileName;
          DXFFileName := ConvertDWGToDXF(DWGFileName);
        end;
        // ****************** DWG - DXF **************************************
        aPCad.DeselectAll(0);
        fContinue := False;
        try
          iFileLength := 0;
          iFileHandle := FileOpen(DXFFileName, fmShareDenyNone);
          if iFileHandle > 0 then
          begin
            iFileLength := FileSeek(iFileHandle,0,2);
            if iFileLength > 0 then
            begin
              FileSeek(iFileHandle,0,0);
              Buffer := PChar(AllocMem(iFileLength + 1));
              iBytesRead := FileRead(iFileHandle, Buffer^, iFileLength);
              if iBytesRead = iFileLength then
              begin
                try
                  TempStream := TMemoryStream.Create;
                  TempStream.WriteBuffer(Buffer^, iBytesRead);
                  DeleteFile(GetTempDir + '\temp~.dxf~');
                  TempStream.SaveToFile(GetTempDir + '\temp~.dxf~');
                  fContinue := True;
                finally
                  TempStream.Free;
                end;
              end;
            end;
          end;
        finally
          FileClose(iFileHandle);
          if iFileLength > 0 then
            FreeMem(Buffer);
        end;
        if Not fContinue then
        begin
          ShowMessage(cImport_Mes1 + DXFFileName);
        end
        else
        begin
          // удалить старый
          DeleteDxfLayers(aPCad);
          FDXFObjectsList := TList.create;
          aPCad.SCSImportDXF(GetTempDir + '\temp~.dxf~', False, True);

          // Обновить менеджер слоев
          if F_LayersDialog.Showing then
            F_LayersDialog.UpdateLayersList;

          // выделить обьекты на дхф слоях
          aPCad.DeselectAll(0);
          for i := 10 to aPCad.Layers.Count - 1 do
            if TLayer(aPCad.Layers[i]).IsDxf then
              aPCad.SelectAll(i);
          aPCad.GroupSelection;
          if aPCad.Selection.Count > 0 then
          begin
            DXFObject := TFigureGrp(aPCad.Selection[0]);
            Cad_X := aPCad.WorkWidth - 20 - 5;
            Cad_Y := aPCad.WorkHeight - 5 - 5;
            Cad_CenterX := aPCad.WorkWidth / 2 + 7.5;
            Cad_CenterY := aPCad.WorkHeight / 2;
            Bnd := DXFObject.GetBoundRect;
            Dxf_X := abs(Bnd.Right - Bnd.Left);
            Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
            if Dxf_X < 0.01 then
              Dxf_X := 0.01;
            if Dxf_Y < 0.01 then
              Dxf_Y := 0.01;
            // SCALE
            ScaleDelta := Min(Cad_X / Dxf_X, Cad_Y / Dxf_Y);
            if ScaleDelta <> 1 then
            begin
              mess := cImport_Mes3;
              if MessageBox(FSCS_Main.Handle, PAnsiChar(mess), cImport_Mes2, MB_YESNO) = IDYes then
              begin
                if ScaleDelta > 0.001 then
                  DXFObject.Scale(ScaleDelta, ScaleDelta);
              end;
            end;
            Bnd := DXFObject.GetBoundRect;
            Dxf_X := abs(Bnd.Right - Bnd.Left);
            Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
            Dxf_CenterX := DXFObject.CenterPoint.x;
            Dxf_CenterY := DXFObject.CenterPoint.y;
            if ScaleDelta > 0.001 then
              DXFObject.move(Cad_CenterX - Dxf_CenterX, Cad_CenterY - Dxf_CenterY);
          end;
          aPCad.SetHScrollPosition(0, True);
        end;
        if pos('.dwg', OpenDXF.FileName) <> 0 then
        begin
          if DirectoryExists(GetPathToSCSTmpDir + '\DWG') then
            FullRemoveDir(GetPathToSCSTmpDir + '\DWG', true, true);
        end;
      end;
    except
      on E: Exception do AddExceptionToLogEx('U_ImportDXF.LoadDXFFile', E.Message);
    end;
    EndProgress;
  end;
  FreeAndNil(OpenDXF);
end;

procedure LoadDXFFileNew(aPCad: TPowerCad; aTitle, aFilter: string; aFile: String=''; aAllowScale: Boolean=true);
var
  i, Count: Integer;
  OpenDXF: TOpenDialog;
  tempstr: string;
  DXFObject: TFigureGrp;
  Bnd: TDoubleRect;
  Cad_X, Cad_Y, Cad_CenterX, Cad_CenterY: Double;
  Dxf_X, Dxf_Y, Dxf_CenterX, Dxf_CenterY: Double;
  ScaleDelta: Double;
  fContinue: Boolean;
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  buffer: PChar;
  TempStream: TMemoryStream;
  mess: string;
  vLayer: TLayer;
  DXFFileName, DWGFileName, TXTFileName: string;
  vDxfFigure: TFigure;
  LHandle: Integer;
  //Tolik
  vDxfObject: TObject;
  Block: TBlock;
begin
  OpenDXF := TOpenDialog.Create(nil);
  if aFile = '' then
  begin
    with OpenDXF do
    begin
      InitialDir := ExtractDirByCategoryType(dctDXF);//ExtractSaveDirForCategory('DXF');//GetEXEDir + '\DXF';
      Title := aTitle;
      Filter := aFilter;
      DefaultExt := '*.dxf, *.dwg, *.svg, *.prn, *.plt';
      FileName := '';
      Options := [ofReadOnly,ofHideReadOnly,ofPathMustExist,ofFileMustExist];
    end;

    if OpenDXF.Execute then
      aFile := OpenDXF.FileName;
  end;

  if aFile <> '' then
  begin
    try
    //  BeginProgress;
      tempstr := AnsiLowerCase(aFile);
      GCadForm.CurrentLayer := 1;
      if pos('.wmf', aFile) <> 0 then
      begin
        try
          aPCad.ImportWMF(1, aFile, False);
        except
        end;
      end
      else
      begin
        DXFFileName := aFile;

        // ****************** DWG - DXF **************************************
        if pos('.dwg', aFile) <> 0 then
        begin
//          DWGFileName := aFile;
//          DXFFileName := ConvertDWGToDXF(DWGFileName);
        end;
        // ****************** DWG - DXF **************************************

        aPCad.DeselectAll(0);
        fContinue := False;
        try
          iFileLength := 0;
          iFileHandle := FileOpen(DXFFileName, fmShareDenyNone);
          if iFileHandle > 0 then
          begin
            iFileLength := FileSeek(iFileHandle,0,2);
            if iFileLength > 0 then
            begin
              FileSeek(iFileHandle,0,0);
              Buffer := PChar(AllocMem(iFileLength + 1));
              iBytesRead := FileRead(iFileHandle, Buffer^, iFileLength);
              if iBytesRead = iFileLength then
              begin
                try
                  TempStream := TMemoryStream.Create;
                  TempStream.WriteBuffer(Buffer^, iBytesRead);
                  DeleteFile(GetTempDir + '\temp~.dxf~');
                  TempStream.SaveToFile(GetTempDir + '\temp~.dxf~');
                  fContinue := True;
                finally
                  TempStream.Free;
                end;
              end;
            end;
          end;
        finally
          FileClose(iFileHandle);
          if iFileLength > 0 then
            FreeMem(Buffer);
        end;
        if Not fContinue then
        begin
          ShowMessage(cImport_Mes1 + DXFFileName);
        end
        else
        begin
          // удалить старый
          DeleteDxfLayers(aPCad);
          FDXFObjectsList := TList.create;
          FDXFBlocksList := TList.Create;
          if ImportDXF(DXFFileName) then
          begin
            // Обновить менеджер слоев
            if F_LayersDialog.Showing then
              F_LayersDialog.UpdateLayersList;

            // выделить обьекты на дхф слоях
            LHandle := aPCad.GetLayerHandle(1);
            DXFObject := TFigureGrp.create(LHandle, aPCad);

            for i := 0 to FDXFObjectsList.Count - 1 do
            begin
              vDxfFigure := TFigure(FDXFObjectsList[i]);
              if vDxfFigure.Cname = 'TText' then
              begin
                Block := TBlock(FDXFObjectsList[i]);
                vDxfFigure := TFigure(BLock);
              end;
              DXFObject.AddToGrp(vDxfFigure); //28.04.2011 DXFObject.InFigures.Add(vDxfFigure);
            end;

            FreeAndNil(FDXFObjectsList);
            FreeAndNil(FDXFBlocksList);

            Cad_X := aPCad.WorkWidth - 20 - 5;
            Cad_Y := aPCad.WorkHeight - 5 - 5;
            Cad_CenterX := aPCad.WorkWidth / 2 + 7.5;
            Cad_CenterY := aPCad.WorkHeight / 2;
            Bnd := DXFObject.GetBoundRect;
            Dxf_X := abs(Bnd.Right - Bnd.Left);
            Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
            if Dxf_X < 0.01 then
              Dxf_X := 0.01;
            if Dxf_Y < 0.01 then
              Dxf_Y := 0.01;
            // SCALE
            if aAllowScale then
            begin
              ScaleDelta := Min(Cad_X / Dxf_X, Cad_Y / Dxf_Y);
              if ScaleDelta <> 1 then
              begin
                mess := cImport_Mes3;
                if MessageBox(FSCS_Main.Handle, PAnsiChar(mess), cImport_Mes2, MB_YESNO) = IDYes then
                begin
                  DXFObject.Scale(ScaleDelta, ScaleDelta);
                end;
              end;
            end;
            Bnd := DXFObject.GetBoundRect;
            Dxf_X := abs(Bnd.Right - Bnd.Left);
            Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
            Dxf_CenterX := DXFObject.CenterPoint.x;
            Dxf_CenterY := DXFObject.CenterPoint.y;
            DXFObject.move(Cad_CenterX - Dxf_CenterX, Cad_CenterY - Dxf_CenterY);

            aPCad.AddCustomFigure(1, DXFObject, False);

            aPCad.SetHScrollPosition(0, True);
          end;
        end;
        if pos('.dwg', aFile) <> 0 then
        begin
          if DirectoryExists(GetPathToSCSTmpDir + '\DWG') then
            FullRemoveDir(GetPathToSCSTmpDir + '\DWG', true, true);
        end;
      end;
    except
      on E: Exception do AddExceptionToLogEx('U_ImportDXF.LoadDXFFileNew', E.Message);
    end;
    //EndProgress;
  end;
  FreeAndNil(OpenDXF);
end;

procedure LoadDXFFileWithName(aPCad: TPowerCad; aFName: string);
var
  i, Count: Integer;
  tempstr: string;
  DXFObject: TFigureGrp;
  Bnd: TDoubleRect;
  Cad_X, Cad_Y, Cad_CenterX, Cad_CenterY: Double;
  Dxf_X, Dxf_Y, Dxf_CenterX, Dxf_CenterY: Double;
  ScaleDelta: Double;
  fContinue: Boolean;
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  buffer: PChar;
  TempStream: TMemoryStream;
  mess: string;
  vLayer: TLayer;
  DXFFileName, DWGFileName, TXTFileName: string;
  vDxfFigure: TFigure;
  LHandle: Integer;
begin
  try
    BeginProgress;
    DXFFileName := aFName;
    tempstr := AnsiLowerCase(DXFFileName);
    GCadForm.CurrentLayer := 1;

    aPCad.DeselectAll(0);
    fContinue := False;
    try
      iFileLength := 0;
      iFileHandle := FileOpen(DXFFileName, fmShareDenyNone);
      if iFileHandle > 0 then
      begin
        iFileLength := FileSeek(iFileHandle,0,2);
        if iFileLength > 0 then
        begin
          FileSeek(iFileHandle,0,0);
          Buffer := PChar(AllocMem(iFileLength + 1));
          iBytesRead := FileRead(iFileHandle, Buffer^, iFileLength);
          if iBytesRead = iFileLength then
          begin
            try
              TempStream := TMemoryStream.Create;
              TempStream.WriteBuffer(Buffer^, iBytesRead);
              DeleteFile(GetTempDir + '\temp~.dxf~');
              TempStream.SaveToFile(GetTempDir + '\temp~.dxf~');
              fContinue := True;
            finally
              TempStream.Free;
            end;
          end;
        end;
      end;
    finally
      FileClose(iFileHandle);
      if iFileLength > 0 then
        FreeMem(Buffer);
    end;
    if Not fContinue then
    begin
      ShowMessage(cImport_Mes1 + DXFFileName);
    end
    else
    begin
      // удалить старый
      DeleteDxfLayers(aPCad);
      FDXFObjectsList := TList.create;
      FDXFBlocksList := TList.Create;
      if ImportDXF(DXFFileName) then
      begin
        // Обновить менеджер слоев
        if F_LayersDialog.Showing then
          F_LayersDialog.UpdateLayersList;

        // выделить обьекты на дхф слоях
        LHandle := aPCad.GetLayerHandle(1);
        DXFObject := TFigureGrp.create(LHandle, aPCad);

        for i := 0 to FDXFObjectsList.Count - 1 do
        begin
          vDxfFigure := TFigure(FDXFObjectsList[i]);
          DXFObject.AddToGrp(vDxfFigure); //28.04.2011 DXFObject.InFigures.Add(vDxfFigure);
        end;

        FreeAndNil(FDXFObjectsList);
        FreeAndNil(FDXFBlocksList);

        Cad_X := aPCad.WorkWidth - 20 - 5;
        Cad_Y := aPCad.WorkHeight - 5 - 5;
        Cad_CenterX := aPCad.WorkWidth / 2 + 7.5;
        Cad_CenterY := aPCad.WorkHeight / 2;
        Bnd := DXFObject.GetBoundRect;
        Dxf_X := abs(Bnd.Right - Bnd.Left);
        Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
        if Dxf_X < 0.01 then
          Dxf_X := 0.01;
        if Dxf_Y < 0.01 then
          Dxf_Y := 0.01;
        // SCALE
        ScaleDelta := Min(Cad_X / Dxf_X, Cad_Y / Dxf_Y);
        if ScaleDelta <> 1 then
        begin
          mess := cImport_Mes3;
          if MessageBox(FSCS_Main.Handle, PAnsiChar(mess), cImport_Mes2, MB_YESNO) = IDYes then
          begin
            DXFObject.Scale(ScaleDelta, ScaleDelta);
          end;
        end;
        Bnd := DXFObject.GetBoundRect;
        Dxf_X := abs(Bnd.Right - Bnd.Left);
        Dxf_Y := abs(Bnd.Bottom - Bnd.Top);
        Dxf_CenterX := DXFObject.CenterPoint.x;
        Dxf_CenterY := DXFObject.CenterPoint.y;
        DXFObject.move(Cad_CenterX - Dxf_CenterX, Cad_CenterY - Dxf_CenterY);

        aPCad.AddCustomFigure(1, DXFObject, False);

        aPCad.SetHScrollPosition(0, True);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('U_ImportDXF.LoadDXFFileWithName', E.Message);
  end;
  EndProgress;
end;


function DxfColorToColor(aColor: Integer): Longint;
const
	AcadColorTable: array [0..255] of Longint = (
		$0,$FF,$FFFF,$FF00,$FFFF00,$FF0000,$FF00FF,$0,$4C4C4C,$A5A5A5,$FF,$7F7FFF,$A5,
		$5252A5,$7F,$3F3F7F,$4C,$26264C,$26,$131326,$3FFF,$7F9FFF,$29A5,$5267A5,$1F7F,
		$3F4F7F,$134C,$262F4C,$926,$131726,$7FFF,$7FBFFF,$52A5,$527CA5,$3F7F,$3F5F7F,
		$264C,$26394C,$1326,$131C26,$BFFF,$7FDFFF,$7CA5,$5291A5,$5F7F,$3F6F7F,$394C,
		$26424C,$1C26,$132126,$FFFF,$7FFFFF,$A5A5,$52A5A5,$7F7F,$3F7F7F,$4C4C,$264C4C,
		$2626,$132626,$FFBF,$7FFFDF,$A57C,$52A591,$7F5F,$3F7F6F,$4C39,$264C42,$261C,
		$132621,$FF7F,$7FFFBF,$A552,$52A57C,$7F3F,$3F7F5F,$4C26,$264C39,$2613,$13261C,
		$FF3F,$7FFF9F,$A529,$52A567,$7F1F,$3F7F4F,$4C13,$264C2F,$2609,$132617,$FF00,
		$7FFF7F,$A500,$52A552,$7F00,$3F7F3F,$4C00,$264C26,$2600,$132613,$3FFF00,$9FFF7F,
		$29A500,$67A552,$1F7F00,$4F7F3F,$134C00,$2F4C26,$92600,$172613,$7FFF00,$BFFF7F,
		$52A500,$7CA552,$3F7F00,$5F7F3F,$264C00,$394C26,$132600,$1C2613,$BFFF00,$DFFF7F,
		$7CA500,$91A552,$5F7F00,$6F7F3F,$394C00,$424C26,$1C2600,$212613,$FFFF00,$FFFF7F,
		$A5A500,$A5A552,$7F7F00,$7F7F3F,$4C4C00,$4C4C26,$262600,$262613,$FFBF00,$FFDF7F,
		$A57C00,$A59152,$7F5F00,$7F6F3F,$4C3900,$4C4226,$261C00,$262113,$FF7F00,$FFBF7F,
		$A55200,$A57C52,$7F3F00,$7F5F3F,$4C2600,$4C3926,$261300,$261C13,$FF3F00,$FF9F7F,
		$A52900,$A56752,$7F1F00,$7F4F3F,$4C1300,$4C2F26,$260900,$261713,$FF0000,$FF7F7F,
		$A50000,$A55252,$7F0000,$7F3F3F,$4C0000,$4C2626,$260000,$261313,$FF003F,$FF7F9F,
		$A50029,$A55267,$7F001F,$7F3F4F,$4C0013,$4C262F,$260009,$261317,$FF007F,$FF7FBF,
		$A50052,$A5527C,$7F003F,$7F3F5F,$4C0026,$4C2639,$260013,$26131C,$FF00BF,$FF7FDF,
		$A5007C,$A55291,$7F005F,$7F3F6F,$4C0039,$4C2642,$26001C,$261321,$FF00FF,$FF7FFF,
		$A500A5,$A552A5,$7F007F,$7F3F7F,$4C004C,$4C264C,$260026,$261326,$BF00FF,$DF7FFF,
		$7C00A5,$9152A5,$5F007F,$6F3F7F,$39004C,$42264C,$1C0026,$211326,$7F00FF,$BF7FFF,
		$5200A5,$7C52A5,$3F007F,$5F3F7F,$26004C,$39264C,$130026,$1C1326,$3F00FF,$9F7FFF,
		$2900A5,$6752A5,$1F007F,$4F3F7F,$13004C,$2F264C,$90026,$171326,$545454,$767676,
		$989898,$BABABA,$DCDCDC,$FFFFFF);
begin
  try
  	Result := AcadColorTable[abs(aColor) mod 256];
  except
    on E: Exception do AddExceptionToLogEx('', E.Message);
  end;
end;

function PointToString(const P: TFPoint): string;
begin
  Result := ' X='+ FloatToStr(P.X)+ ' Y='+ FloatToStr(P.Y)+ ' Z='+ FloatToStr(P.Z);
end;

constructor TF_Import.Create;
begin
  ZeroMemory(@FTextPrevPt, SizeOf(TFPoint));
  FTextUsePrevPt := false;
end;

function IsRectInRect(rect1, rect2 : TFRect) : boolean;
begin
  if ((((rect1.left>=rect2.left)and(rect1.left<=rect2.right)) or
       ((rect1.left<=rect2.left)and(rect1.right>=rect2.left)) ) and
     ( ((rect1.top>=rect2.top)and(rect1.top<=rect2.bottom)) or
       ((rect1.top<=rect2.top)and(rect1.bottom>=rect2.top)) ) ) then
  Result:=true else Result:=false;
end;

function TF_Import.ReadCADEntities(Entity: TsgDXFEntity): Integer;
const
  PS: array[psSolid..psDashDot] of string =
    ('psSolid','psDash','psDot','psDashDot');
var
  S: string;
  L: TsgDXFLayer;
  C: TColor;
  St: TPenStyle;
  a: single;
  ResEntity: TFigure;
  Blk: TBlock;
  Cad: TPCDrawing;
  inBox: boolean;
  MaxBlockSize: double;

  //Tolik
  FiguresList: TList;
  k: Integer;
{  ss, sss: string;
  w: UTF8String;
  ww: WideString;
  i, j: Integer;
  ch: PWideChar;
  p: Pointer;
  currPos : integer;
  wChar: WideChar;
  Delagain: Boolean;
  simbolCode: Integer;
  StringChanged: Boolean; }


  function HexToInt(h: string): integer;
  var
    i, c: integer;
  begin
    val('$'+h, i, c);
    if c > 0 then HexToInt := -1
    else HexToInt := i;
  end;

  // Tolik
  Procedure AddEntity(rEntity: TFigure);
  begin
    if REntity <> nil then
    begin
      // фигура не в блоке
      if FCADParams.Insert = nil then
      begin
        //Tolik
        if Entity.EntType = ceCurvePolygon then
          FDXFObjectsList.Insert(0,REntity)
        else
        //
          FDXFObjectsList.Add(REntity);
      end
      else
      // фигура в блоке
      begin
        Cad := TPCDrawing(GCadForm.PCad);
        Blk := GetDXFBlock(FCADParams.Insert.Handle);
        // такой блок уже есть, внести фигуру в него
        if Blk <> nil then
        begin
          // 16.01.2014
          //Blk.AddFigure(ResEntity);
          Blk.AddFigure(REntity, False);
        end
        else
        // блока нет, создать и внести в него фигуру
        begin
          if FCADParams.Insert.Visible then
          begin
            inc(FBlockCount);
            Blk := TBlock.Create(REntity.LayerHandle, Cad);
            Blk.AddFigure(REntity);
            Blk.ID := FCADParams.Insert.Handle;
            // Tolik
            if Entity.EntType = ceCurvePolygon then
            begin
              FDXFBlocksList.Insert(0, Blk);
              FDXFObjectsList.Insert(0, Blk);
            end
            //
            else
            begin
              FDXFBlocksList.Add(Blk);
              FDXFObjectsList.Add(Blk);
            end;
          end
          else
            dec(FEntitiesCount);
        end;
      end;
    end;
  end;

begin
  try
    Result := 0;

    Inc(FEntitiesCount); //29.10.2012

    S := #13#10'ClassName=' + Entity.ClassName + '; Entity name=' + utf16decode(Entity.EntName);

    DoScale2D(FCADParams); // calculates 2d scale and rotation
    // layer
    L := EntLayer(Entity, FCADParams.Insert);
    if L <> nil then S := S + ' layer = ' + L.Name;
    // color
    S := S + ' style = ' + PS[EntStyle(Entity)];
    C := EntColor(Entity, FCADParams.Insert);
    St := EntStyle(Entity);
    if C = clNone then
      S := S + ' color=black/white'
    else
      S := S + ' color = ' +  IntToHex(C, -6) + ' (' + ColorToString(C) + ')';
    // particular properties
    TxtFile.Add(S);
    // Такое лучше не делать - сбивается оригинальный цвет иногда
    //Entity.Color := C;
    inBox := True;
    //так криво получается - нужно еще смотреть как обойти ситуации как файлах: "D:\WORK\СКС\! DWG_TESTS\"  "A-203 FIRST FLOOR PLAN.dwg" Drawing5.dwg
    //if FCADParams.Insert <> nil then
    //begin
    //  if FCADParams.Insert.Block <> nil then
    //  begin
    //    if Not IsRectInRect(FCADParams.Insert.Block.Box, Entity.Box) then
    //      inBox := False;
    //  end;
    //end;

    ResEntity := nil;
    if inBox then
    begin
      case Entity.EntType of
        ceLine:
            ResEntity := ImportLine(Entity);
        cePoint:
            ResEntity := ImportPoint(Entity);

        ceCircle:
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFCircle(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFCircle(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFCircle(Entity).ZThick := $FFFFFF;
                end;
              end;

              //if FCADParams.Insert.Owner <> nil then
              //if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
              //   and (FCADParams.Insert.Count > 0) then
              //begin
              //  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
              //  TsgDXFCircle(Entity).ZThick := $FFFFFF;
              //end;
              //if FCADParams.Insert.Count > 0 then
              //begin
              //  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
              //  TsgDXFCircle(Entity).ZThick := $FFFFFF;
              //end;
            end;
          end;
          ResEntity := ImportCircle(Entity);
        end;
    

        ceArc:
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFArc(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFArc(Entity).Radius := TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFArc(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFArc(Entity).Radius := TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFArc(Entity).ZThick := $FFFFFF;
                end;
              end;
            end;
          end;
          ResEntity := ImportArc(Entity);
        end;


        ceEllipse: 
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFEllipse(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFEllipse(Entity).Radius := TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFEllipse(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFEllipse(Entity).Radius := TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFEllipse(Entity).ZThick := $FFFFFF;
                end;
              end;
            end;
          end;
          ResEntity := ImportEllipse(Entity);
        end;
        cePolyline, cePath:
          ResEntity := ImportPolyLine(Entity);
        ceLWPolyline:
          // Tolik --18/01/2016 --
          ResEntity := ImportPolyLine(Entity);
          // ResEntity := ImportLWPolyLine(Entity);
          //
        ceSpline:
          ResEntity := ImportSpline(Entity);
        ceLeader:
          ResEntity := ImportLeader(Entity);
        // Tolik -- 02/01/2016
        ceText:
          ResEntity := ImportText(Entity);
        {ceText:
          begin
            if FCADParams.Insert <> nil then
              ResEntity := ImportText(Entity);
          end;}
        //
        ceAttdef, ceAttrib:
          ResEntity := ImportAttdef(Entity);
        ceSolid, ce3dFace:
          ResEntity := ImportSolid(Entity);
        cePolyPolygon, ceGradient, ceGradientPolygon, ceCurvePolygon, ceHatch:
        // Tolik
         // if FCADParams.Insert <> nil then
          // Tolik
          begin
            FiguresList := ImportHatch(Entity);
            for k := 0 to FiguresList.Count - 1 do
            begin
              AddEntity(TFigure(FiguresList[k]));
            end;
            FreeAndNil(FiguresList);
          end;
        ceViewport:
          begin
            Result := 1;
            ResEntity := ImportViewPortBegin(Entity);    //ViewPort - see dxfimage.pas TsgDXFImage.DrawViewPort
          end;
        ceEntity:
          ;
        // Tolik -- 02/01/2016 -- это все мы пока не обрабатываем, (А ОНО ЕСТЬ!)
        ceTrace :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceTRACE) ');
        ceHelix :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceHELIX) ');
        ceInsert :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceINSERT) ');
        ceDimension :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceDIMENTION) ');
        ceTolerance :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceTOLERANCE) ');

        ceShape :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceSHAPE) ');
        ceImageEnt :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceImageEnt) ');
        ceRegion :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceRegion) ');
        ceBody :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceBody) ');
        cePattern :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (cePattern) ');
        ceOle2Frame :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceOle2Frame) ');
        ceACADTable :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceACADTable) ');
        ceFlatPoly :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceFlatPoly) ');
        ceFlatHatch :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceFlatHatch) ');
        ceXRef :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceXRef) ');
        ceProxy :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceProxy) ');
        ceWipeOut :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceWipeOut) ');
        ceMLine :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceMLine) ');
        ceMPolygon :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceMPolygon) ');
        ceSurface :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceSurface) ');
       { ceTable :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceTABLE) ');}
        //
        ce3DSolid:
        begin

        end
         // ;//ResEntity := ImportSolid(Entity);
        // Tolik 30/12/2015 -- скинуть константы в лог тех объектов, классы которых не определены в обработчике
      // скину в ЛОГ, чтоб хотя бы понимать, что не обрабатываем
        else
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! Entity.EntType = ' + IntToStr(Ord(Entity.EntType)));
      //
      end

    end;
    if ResEntity <> nil then
    begin
      AddEntity(ResEntity);
      inc(ReadedEntCount);
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ReadCADEntities', E.Message);
  end;
end;

Procedure TF_Import.SimpleReadCADEntities(Entity: TsgDXFEntity);
const
  PS: array[psSolid..psDashDot] of string =
    ('psSolid','psDash','psDot','psDashDot');
var
  S: string;
  L: TsgDXFLayer;
  C: TColor;
  St: TPenStyle;
  a: single;
  ResEntity: TFigure;
  Blk: TBlock;
  Cad: TPCDrawing;
  inBox: boolean;
  MaxBlockSize: double;

  //Tolik
  FiguresList: TList;
  i,j, k: Integer;
{  ss, sss: string;
  w: UTF8String;
  ww: WideString;
  i, j: Integer;
  ch: PWideChar;
  p: Pointer;
  currPos : integer;
  wChar: WideChar;
  Delagain: Boolean;
  simbolCode: Integer;
  StringChanged: Boolean; }


  function HexToInt(h: string): integer;
  var
    i, c: integer;
  begin
    val('$'+h, i, c);
    if c > 0 then HexToInt := -1
    else HexToInt := i;
  end;

  // Tolik
  Procedure AddEntity(rEntity: TFigure);
  begin
    if REntity <> nil then
    begin
      // фигура не в блоке
      if FCADParams.Insert = nil then
      begin
        //Tolik
        if Entity.EntType = ceCurvePolygon then
          FDXFObjectsList.Insert(0,REntity)
        else
        //
          FDXFObjectsList.Add(REntity);
      end
      else
      // фигура в блоке
      begin
        Cad := TPCDrawing(GCadForm.PCad);
        Blk := GetDXFBlock(FCADParams.Insert.Handle);
        // такой блок уже есть, внести фигуру в него
        if Blk <> nil then
        begin
          // 16.01.2014
          //Blk.AddFigure(ResEntity);
          Blk.AddFigure(REntity, False);
        end
        else
        // блока нет, создать и внести в него фигуру
        begin
          Blk := TBlock.Create(REntity.LayerHandle, Cad);
          Blk.AddFigure(REntity);
          Blk.ID := FCADParams.Insert.Handle;
          // Tolik
          if Entity.EntType = ceCurvePolygon then
          begin
            FDXFBlocksList.Insert(0, Blk);
            FDXFObjectsList.Insert(0, Blk);
          end
          //
          else
          begin
            FDXFBlocksList.Add(Blk);
            FDXFObjectsList.Add(Blk);
          end;
        end;
      end;
    end;
  end;

begin
  try
//    Result := 0;

    Inc(FEntitiesCount); //29.10.2012

    S := #13#10'ClassName=' + Entity.ClassName + '; Entity name=' + utf16decode(Entity.EntName);

    DoScale2D(FCADParams); // calculates 2d scale and rotation
    // layer
    L := EntLayer(Entity, FCADParams.Insert);
    if L <> nil then S := S + ' layer = ' + L.Name;
    // color
    S := S + ' style = ' + PS[EntStyle(Entity)];
    C := EntColor(Entity, FCADParams.Insert);
    St := EntStyle(Entity);
    if C = clNone then
      S := S + ' color=black/white'
    else
      S := S + ' color = ' +  IntToHex(C, -6) + ' (' + ColorToString(C) + ')';
    // particular properties
    TxtFile.Add(S);
    // Такое лучше не делать - сбивается оригинальный цвет иногда
    //Entity.Color := C;
    inBox := True;
    //так криво получается - нужно еще смотреть как обойти ситуации как файлах: "D:\WORK\СКС\! DWG_TESTS\"  "A-203 FIRST FLOOR PLAN.dwg" Drawing5.dwg
    //if FCADParams.Insert <> nil then
    //begin
    //  if FCADParams.Insert.Block <> nil then
    //  begin
    //    if Not IsRectInRect(FCADParams.Insert.Block.Box, Entity.Box) then
    //      inBox := False;
    //  end;
    //end;

    ResEntity := nil;
    if inBox then
    begin
      case Entity.EntType of
        ceLine:
            ResEntity := ImportLine(Entity);
        cePoint:
            ResEntity := ImportPoint(Entity);
        ceCircle:
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFCircle(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFCircle(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFCircle(Entity).ZThick := $FFFFFF;
                end;
              end;

              //if FCADParams.Insert.Owner <> nil then
              //if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
              //   and (FCADParams.Insert.Count > 0) then
              //begin
              //  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
              //  TsgDXFCircle(Entity).ZThick := $FFFFFF;
              //end;
              //if FCADParams.Insert.Count > 0 then
              //begin
              //  TsgDXFCircle(Entity).Radius := TsgDXFCircle(Entity).Radius * abs(FCADParams.Insert.Scale.X);
              //  TsgDXFCircle(Entity).ZThick := $FFFFFF;
              //end;
            end;
          end;
          ResEntity := ImportCircle(Entity);
        end;

        ceArc:
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFArc(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFArc(Entity).Radius := TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFArc(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFArc(Entity).Radius := TsgDXFArc(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFArc(Entity).ZThick := $FFFFFF;
                end;
              end;
            end;
          end;
          ResEntity := ImportArc(Entity);
        end;

        ceEllipse:
        begin
          if FCADParams.Insert <> nil then
          begin
            if TsgDXFEllipse(Entity).ZThick <> $FFFFFF then
            begin
              if (FCADParams.Insert.Count > 0) or
                 (FCADParams.Insert.Owner <> nil) {or
                 ((FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0))}
                 then
              begin
                if (FCADParams.Insert.Block <> nil) and (FCADParams.Insert.Block.IndexOfEntity(Entity) >= 0)
                  and (abs(FCADParams.Insert.Scale.X) > 1) then
                begin
                  //if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left) then
                  //if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) <
                  //  abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left) then
                  MaxBlockSize := 0;
                  if FCADParams.Insert.Count = 1 then
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Box.Right - FCADParams.Insert.Box.left);
                    if abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Box.Top - FCADParams.Insert.Box.Bottom);
                  end
                  else
                  begin
                    MaxBlockSize := abs(FCADParams.Insert.Block.Box.Right - FCADParams.Insert.Block.Box.left);
                    if abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom) > MaxBlockSize then
                      MaxBlockSize := abs(FCADParams.Insert.Block.Box.Top - FCADParams.Insert.Block.Box.Bottom);
                  end;
                  if (TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X)) < MaxBlockSize then
                  begin
                    TsgDXFEllipse(Entity).Radius := TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                    TsgDXFEllipse(Entity).ZThick := $FFFFFF;
                  end;
                end
                else
                begin
                  TsgDXFEllipse(Entity).Radius := TsgDXFEllipse(Entity).Radius * abs(FCADParams.Insert.Scale.X);
                  TsgDXFEllipse(Entity).ZThick := $FFFFFF;
                end;
              end;
            end;
          end;
          ResEntity := ImportEllipse(Entity);
        end;
        cePolyline, cePath:
          ResEntity := ImportPolyLine(Entity);
        ceLWPolyline:
          ResEntity := ImportPolyLine(Entity);
        ceSpline:
          ResEntity := ImportSpline(Entity);
        ceLeader:
          ResEntity := ImportLeader(Entity);
        // Tolik -- 02/01/2016
        ceText:
          ResEntity := ImportText(Entity);
        {ceText:
          begin
            if FCADParams.Insert <> nil then
              ResEntity := ImportText(Entity);
          end;}
        //
        ceAttdef, ceAttrib:
          ResEntity := ImportAttdef(Entity);
        ceSolid, ce3dFace:
          ResEntity := ImportSolid(Entity);
        cePolyPolygon, ceGradient, ceGradientPolygon, ceCurvePolygon, ceHatch:
        // Tolik
          if FCADParams.Insert <> nil then
          // Tolik
          begin
            FiguresList := ImportHatch(Entity);
            for k := 0 to FiguresList.Count - 1 do
            begin
              AddEntity(TFigure(FiguresList[k]));
            end;
            FreeAndNil(FiguresList);
          end;
        ceViewport:
          begin
            //Result := 1;
            ResEntity := ImportViewPortBegin(Entity);    //ViewPort - see dxfimage.pas TsgDXFImage.DrawViewPort
          end;
        ceEntity:
          ;
        // Tolik -- 02/01/2016 -- это все мы пока не обрабатываем, (А ОНО ЕСТЬ!)
        ceTrace :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceTRACE) ');
        ceHelix :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceHELIX) ');
        ceInsert :
        begin
          for i := 0 to TsgDxfInsert(Entity).Count - 1 do
            SimpleReadCADEntities(TsgDXFEntity(TsgDxfInsert(Entity).Entities[i]));
          inc(FBlockCount);
          //AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceINSERT) ');
        end;
        ceDimension :
        begin
          for i := 0 to TsgDxfDimension(Entity).Count - 1 do
            SimpleReadCADEntities(TsgDXFEntity(TsgDxfDimension(Entity).Entities[i]));
             AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceDIMENTION) ');
        end;     
        ceTolerance :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceTOLERANCE) ');
        ceMText :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceMTEXT) ');
        ceShape :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceSHAPE) ');
        ceImageEnt :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceImageEnt) ');
        ceRegion :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceRegion) ');
        ceBody :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceBody) ');
        cePattern :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (cePattern) ');
        ceOle2Frame :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceOle2Frame) ');
        ceACADTable :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceACADTable) ');
        ceFlatPoly :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceFlatPoly) ');
        ceFlatHatch :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceFlatHatch) ');
        ceXRef :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceXRef) ');
        ceProxy :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceProxy) ');
        ceWipeOut :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceWipeOut) ');
        ceMLine :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceMLine) ');
        ceMPolygon :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceMPolygon) ');
        ceSurface :
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! (ceSurface) ');

        //
        ce3DSolid:
        begin

        end
         // ;//ResEntity := ImportSolid(Entity);
        // Tolik 30/12/2015 -- скинуть константы в лог тех объектов, классы которых не определены в обработчике
      // скину в ЛОГ, чтоб хотя бы понимать, что не обрабатываем
        else
          AddExceptionToLogSilent('TF_Import.ReadCADEntities : Объект не обработан! Entity.EntType = ' + IntToStr(Ord(Entity.EntType)));
      //
      end

    end;
    if ResEntity <> nil then
    begin
      AddEntity(ResEntity);
      inc(ReadedEntCount);
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ReadCADEntities', E.Message);
  end;
end;
function TF_Import.CheckIsLoaded(Entity: TsgDXFEntity): Boolean;
begin
  Result := False;
  if HandleList.IndexOf(inttostr(Entity.Handle)) = -1 then
    Result := True;
end;
//

function TF_Import.FinishReadCADEntities(Entity: TsgDXFEntity): Integer;
begin
  case Entity.EntType of
    ceViewport:
      begin
        Result := 1;
        ImportViewPortEnd(Entity);
      end;
  else
    Result := 0;
  end;
end;

//procedure cbLayoutsChange(Sender: TObject);
//begin
//  if cbLayouts.Items.Objects[cbLayouts.ItemIndex] <> nil then
//    TsgDXFImage(Image1.Picture.Graphic).CurrentLayout := TsgDXFImage(Image1.Picture.Graphic).Layouts[cbLayouts.ItemIndex];
//end;

function TF_Import.ImportSolid(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
  Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;
  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;

begin
  try
    Result := nil;
    // Tolik -- 05/01/2016
    if not TsgDXFSolid(Sender).Visible then
      Exit;
    //
    SetLength(points, 4);
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFSolid(Sender).Point, FCADParams.Matrix);
    {$ELSE}
      // Ещдлш -- 30/12/2015 --
      P := FPointXMat(TsgDXFSolid(Sender).Point, FCADParams.Matrix);
     // P := TsgDXFSolid(Sender).Point;
      //DoExtrusion(P, TsgDXFSolid(Sender).Extrusion);
    //  P := FPointXMat(P, FCADParams.Matrix);
      //
    {$IFEND}
    S := S + ' P1: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10;
    P := ModificatePoint(P);
    points[0].x := P.x;
    points[0].y := P.y;
    points[0].z := P.z;

    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFSolid(Sender).Point1, FCADParams.Matrix);
    {$ELSE}
      // Tolik 30/12/2015 --
       P := FPointXMat(TsgDXFSolid(Sender).Point1, FCADParams.Matrix);
     {
      P := TsgDXFSolid(Sender).Point1;
      DoExtrusion(P, TsgDXFSolid(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);
     }
      //
    {$IFEND}
    S := S + ' P2: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10;
    P := ModificatePoint(P);
    points[1].x := P.x;
    points[1].y := P.y;
    points[1].z := P.z;

    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFSolid(Sender).Point3, FCADParams.Matrix);
    {$ELSE}
      // Tolik 30/12/2015 --
      P := FPointXMat(TsgDXFSolid(Sender).Point3, FCADParams.Matrix);
      {
      P := TsgDXFSolid(Sender).Point3;
      DoExtrusion(P, TsgDXFSolid(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);
      }
      //
    {$IFEND}
    S := S + ' P3: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10;
    P := ModificatePoint(P);
    points[2].x := P.x;
    points[2].y := P.y;
    points[2].z := P.z;

    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFSolid(Sender).Point2, FCADParams.Matrix);
    {$ELSE}
      // Tolik -- 30/12/2015
      P := FPointXMat(TsgDXFSolid(Sender).Point2, FCADParams.Matrix);
      {
      P := TsgDXFSolid(Sender).Point2;
      DoExtrusion(P, TsgDXFSolid(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);
      }
      //
    {$IFEND}
    S := S + ' P4: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    P := ModificatePoint(P);
    points[3].x := P.x;
    points[3].y := P.y;
    points[3].z := P.z;

    TxtFile.Add(S);
    if not TsgDXFSolid(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    ///
    //**************************************************************************//

    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFSolid(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, True, LHandle, mydsNormal, Cad);

    {$IF Defined(CADImport6)}
      Poly.Color := TsgDXFSolid(Sender).Pen.Color;
      Poly.Width := TsgDXFSolid(Sender).Pen.Width;
    {$ELSE}
      Poly.color := GetColor(Sender);
      if RoundUp(TsgDXFSolid(Sender).LineWeight) >= 0 then
        Poly.Width := RoundUp(TsgDXFSolid(Sender).LineWeight)
      else
        Poly.Width := 1;
    {$IFEND}

    Poly.Style := ord(entstyle(TsgDXFSolid(Sender)));
    Result := Poly;
    //Tolik
    SetLength(Points, 0);
    //
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportSolid', E.Message);
  end;
end;

function TF_Import.ImportLine(Sender: TObject): TFigure;
var
  P1, P2: TFPoint;
  S: string;
  Cad: TPCDrawing;
  Line: TLine;
  LayerNbr, LHandle: Integer;
  C: Integer;
  // Tolik
  f: TextFile;
  //
begin
  try
    Result := nil;
    // Tolik -- 05/01/2016
    if not TsgDXFLine(Sender).Visible then
      Exit;
    //
    S := ' LineWeight=' + FloatToStr(TsgDXFLine(Sender).LineWeight) + '; ';
    S := S + ' LineTypeScale=' + FloatToStr(TsgDXFLine(Sender).LineTypeScale) + '; ';
    S := S + ' ZThick=' + FloatToStr(TsgDXFLine(Sender).ZThick) + '; ';
    S := S + #13#10;
    {$IF Defined(CADImport6)}
      P1 := PtXMat(TsgDXFLine(Sender).Point, FCADParams.Matrix);
    {$ELSE}
      // Tolik 30/12/2015 --
      P1 := FPointXMat(TsgDXFLine(Sender).Point, FCADParams.Matrix);
     { P1 := TsgDXFLine(Sender).Point;
      DoExtrusion(P1, TsgDXFLine(Sender).Extrusion);
      P1 := FPointXMat(P1, FCADParams.Matrix);}
      //
    {$IFEND}
    S := S + ' Begin point: ';
    S := S + #13#10;
    S := S + ' X=' + FloatToStr(P1.X);
    S := S + ' Y=' + FloatToStr(P1.Y);
    S := S + ' Z=' + FloatToStr(P1.Z);
    S := S + #13#10;
    {$IF Defined(CADImport6)}
      P2 := PtXMat(TsgDXFLine(Sender).Point1, FCADParams.Matrix);
    {$ELSE}
      // Tolik -- 30/12/2015 --
      P2 := FPointXMat(TsgDXFLine(Sender).Point1, FCADParams.Matrix);
     { P2 := TsgDXFLine(Sender).Point1;
      DoExtrusion(P2, TsgDXFLine(Sender).Extrusion);
      P2 := FPointXMat(P2, FCADParams.Matrix);}
      //
    {$IFEND}
    S := S + ' End point: ';
    S := S + #13#10;
    S := S + ' X=' + FloatToStr(P2.X);
    S := S + ' Y=' + FloatToStr(P2.Y);
    S := S + ' Z=' + FloatToStr(P2.Z);
    TxtFile.Add(S);
    if not TsgDXFLine(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    Cad := TPCDrawing(GCadForm.PCad);
    P1 := ModificatePoint(P1);
    P2 := ModificatePoint(P2);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
  //  Line := TLine(Cad.Line(LayerNbr, P1.X, P1.Y, P2.x, P2.y, 1, 0, 0, 0, False));
    Line := TLine.create(P1.X, P1.Y, P2.x, P2.y, 1, 0, 0, 0, LHandle, mydsNormal, Cad);

    {$IF Defined(CADImport6)}
      Line.color := TsgDXFLine(Sender).Color;
      Line.Width := TsgDXFLine(Sender).Pen.Width;
    {$ELSE}
      Line.color := GetColor(Sender);
      //Tolik -- 30/12/2015 -- бываю отрицательные числа - почти всегда
      //Line.Width := RoundUp(TsgDXFLine(Sender).LineWeight);
      Line.Width := RoundUp(TsgDXFLine(Sender).LineWeight);
      //
      if Line.width < 1 then
        Line.width := 1;
    {$IFEND}
    // Tolik  -- для посмотреть
    {
    s:='';
    S := S + ' Line.Point1: ';
    S := S + ' X= ' + IntToStr(Round(P1.X));
    S := S + ' Y= ' + IntToStr(Round(P1.Y));
    S := S + ' Z= ' + IntToStr(Round(P1.Z));
    S := S + #13#10' Line.Point2: ';
    S := S + ' X= ' + IntToStr(Round(P2.X));
    S := S + ' Y= ' + IntToStr(Round(P2.Y));
    S := S + ' Z= ' + IntToStr(Round(P2.Z));

    AssignFile(f, 'd:\Tolik\ARC.txt');
    reset(f);
    append(f);
    writeln(f,s);
    close(f);
    }
    //
    Line.Style := ord(entstyle(TsgDXFLine(Sender)));

    Result := Line;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportLine', E.Message);
  end;
end;

(*
// -- TEST
function TF_Import.ImportLine(Sender: TObject): TFigure;
var
  P1, P2: TFPoint;
  S: string;
  Cad: TPCDrawing;
  Line: TLine;
  LayerNbr, LHandle: Integer;
  C: Integer;
  // Tolik
  f: TextFile;

  function GetExtruded(const ALine: TsgDXFLine; APoint: TFPoint): TFPoint;
  begin
    Result := APoint;
    DoPreExtrusion(Result, ALine.Extrusion);
    Result.Z := Result.Z + ALine.ZThick;
    DoExtrusion(Result, ALine.Extrusion);
  end;
  //
begin
  try
    Result := nil;
    // Tolik -- 05/01/2016
    if not TsgDXFLine(Sender).Visible then
      Exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //
    {$IF Defined(CADImport6)}
      P1 := PtXMat(TsgDXFLine(Sender).Point, FCADParams.Matrix);
      P2 := PtXMat(TsgDXFLine(Sender).Point1, FCADParams.Matrix);
    {$ELSE}
      if TsgDXFLine(Sender).ZThick <> 0 then
      begin
        P1 := FPointXMat(TsgDXFLine(Sender).Point, FCADParams.Matrix);
        P2 := FPointXMat(TsgDXFLine(Sender).Point1, FCADParams.Matrix);

        if Extruded(TsgDXFLine(Sender).Extrusion) then
        begin
          P1 := (GetExtruded(TsgDXFLine(Sender), P1));
          P2 := (GetExtruded(TsgDXFLine(Sender), P2));
        end;
      end
      else
      begin
        P1.Z := P1.Z + TsgDXFLine(Sender).ZThick;
        P2.z := P2.Z + TsgDXFLine(Sender).ZThick;
      end;
    {$IFEND}

    //**************************************************************************//

    Cad := TPCDrawing(GCadForm.PCad);
    P1 := ModificatePoint(P1);
    P2 := ModificatePoint(P2);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Line := TLine.create(P1.X, P1.Y, P2.x, P2.y, 1, 0, 0, 0, LHandle, mydsNormal, Cad);
    {$IF Defined(CADImport6)}
      Line.color := TsgDXFLine(Sender).Color;
      Line.Width := TsgDXFLine(Sender).Pen.Width;
    {$ELSE}
      Line.color := GetColor(Sender);
      Line.Width := RoundUp(TsgDXFLine(Sender).LineWeight);
      //
      if Line.width < 1 then
        Line.width := 1;
    {$IFEND}
    Line.Style := ord(entstyle(TsgDXFLine(Sender)));
    Result := Line;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportLine', E.Message);
  end;
end;   *)
// =========================================================================================================

function TF_Import.ImportPoint(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  Point: TVertex;
  Cad: TPCdrawing;
  LayerNbr, LHandle: Integer;
  // Tolik
  f: TextFile;
  //
begin
  try
    Result := nil;
    // Tolik 05/01/2015
    if not TsgDXFPoint(Sender).Visible then
      Exit;
    //
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFPoint(Sender).Point, FCADParams.Matrix);
    {$ELSE}
      // Tolik -- 30/12/2015 --
      P := FPointXMat(TsgDXFPoint(Sender).Point, FCADParams.Matrix);
      {
      P := TsgDXFPoint(Sender).Point;
      DoExtrusion(P, TsgDXFPoint(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);
      }
      //
    {$IFEND}
    S := ' Point: ' + #13#10 + PointToString(P);
    S := S + #13#10;
    if not TsgDXFPoint(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    ////
    Cad := TPCDrawing(GCadForm.PCad);
    P := ModificatePoint(P);
    // Tolik -- для посмотреть --
    s:='';
    S := S + ' Point: ';
    S := S + ' X= ' + FloatToStr(P.X);
    S := S + ' Y= ' + FloatToStr(P.Y);
    S := S + ' Z= ' + FloatToStr(P.Z);
    AssignFile(f, 'd:\Tolik\ARC.txt');
    {reset(f);
    append(f);
    writeln(f,s);
    close(f);}
    //
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFPoint(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
  //  Point := TVertex(Cad.Vertex(LayerNbr, P.X, P.y, false));
    Point := TVertex.create(P.X, P.y, LHandle, mydsNormal, Cad);
    Point.Color := GetColor(Sender);
    Result := Point;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPoint', E.Message);
  end;
end;

function TF_Import.ImportEllipse(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  Ellipse: TEllipse;
  ElpArc: TElpArc;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  Radx, rady: double;
  a1, a2, a, blk_ang, ta: double;
  Poly: TPolyline;
  P1: TDoublePoint;
  z: double;
  R: TFRect;
  Aaa: TsgArc;
 // P11, P22: TPoint;
  P11, P22: TDoublePoint;
  summ: Double;
  TempPoint: TFPoint;
  modscalex, modscaley: double;
  // Tolik
  f: TextFile;
begin
  Result := nil;
  // Tolik 05/01/2016
  if not TsgDXFEllipse(Sender).Visible then
    Exit;
  //
  try
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFEllipse(Sender).Point, FCADParams.Matrix);
      z := round(TsgDXFEllipse(Sender).Extrusion.z);
      if z < 0 then
      begin
        TempPoint := TsgDXFEllipse(Sender).Point;
        TempPoint.X := - (TsgDXFEllipse(Sender).Point.X);
        P := PtXMat(TempPoint, FCADParams.Matrix);
      end;
    {$ELSE}
      // Tolik -- 30/12/2015 --
      P := FPointXMat(TsgDXFEllipse(Sender).Point, FCADParams.Matrix);
      //P := TsgDXFEllipse(Sender).Point;
      //DoExtrusion(P, TsgDXFEllipse(Sender).Extrusion);
      //P := FPointXMat(P, FCADParams.Matrix);         
      z := round(TsgDXFEllipse(Sender).Extrusion.z);

      if z < 0 then
      begin
        TempPoint := TsgDXFEllipse(Sender).Point;
        TempPoint.X := - (TsgDXFEllipse(Sender).Point.X);
        P := FPointXMat(TempPoint, FCADParams.Matrix);
      end;
    {$IFEND}
    S := S + ' Center point: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10;
    S := S + ' Start Angle: ' + FloatToStr(TsgDXFEllipse(Sender).StartAngle);
    S := S + #13#10;
    S := S + ' End Angle: ' + FloatToStr(TsgDXFEllipse(Sender).EndAngle);
    S := S + #13#10;
    S := S + ' Rx: ' + FloatToStr(TsgDXFEllipse(Sender).Radius);
    S := S + ' Ry: ' + FloatToStr(TsgDXFEllipse(Sender).Radius * TsgDXFEllipse(Sender).Ratio);
    TxtFile.Add(S);
    if not TsgDXFEllipse(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    Aaa := EntArc(TsgDXFArc(Sender), FCADParams);
    R.Left := Round(Aaa.Rect.Left);
    R.Top := Round(Aaa.Rect.Top);
    R.Right := Round(Aaa.Rect.Right);
    R.Bottom := Round(Aaa.Rect.Bottom);

    P11.X := Round(Aaa.Point1.X);
    P11.Y := Round(Aaa.Point1.Y);
    P22.X := Round(Aaa.Point2.X);
    P22.Y := Round(Aaa.Point2.Y);

    summ := P11.x + P11.Y + P22.X + P22.y;
    if DoubleCMP(summ, P11.X) or DoubleCMP(summ, P22.X) or DoubleCMP(summ, P11.Y) or DoubleCMP(summ, P22.Y)then
    begin
      if z = 0 then
        exit;
    end;

    if (P11.X = P22.X) and (P11.Y = P22.Y) then
    begin
      if z = 0 then
        exit;
    end;
    if (P11.X = 0) AND (P22.X = 0) and (P11.Y = 0) AND (P22.Y = 0) then
    begin
      if z = 0 then
        exit;
    end;

    {TODO} // изначально было P.x := - P.X; - но оно тут по ходу не всегда нужно
    // возможно будут файлы для которых нужно такое преобразование - по правильному сделано через TempPoint
    //if z < 0 then
    //  P.x := - P.X;

    Cad := TPCDrawing(GCadForm.PCad);
    P := ModificatePoint(P);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFEllipse(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Radx := TsgDXFEllipse(Sender).Radius;
    Rady := TsgDXFEllipse(Sender).Radius * TsgDXFEllipse(Sender).Ratio;
    // Tolik -- добавить скейлы, если есть вхождение блока
    if FCadParams.Insert <> nil then
    begin
      // Radx := Radx * ABS(FCadParams.Insert.Scale.X);
      // Rady := Rady * ABS(FCadParams.Insert.Scale.Y);
    end;
    //
    blk_ang := FCADParams.Angle;
//    blk_ang := FCADParams.Insert.Angle;
    a := TsgDXFEllipse(Sender).Angle;
    a1 := TsgDXFEllipse(Sender).StartAngle;
    a2 := TsgDXFEllipse(Sender).EndAngle;

    if (TsgDXFEllipse(Sender).StartAngle = 180) and (TsgDXFEllipse(Sender).EndAngle = 540) then
      beep;
    while  Round(a1) >= 360 do
      a1 := a1 - 360;
    while Round(a2) >= 360 do
      a2 := a2 - 360;

    blk_ang := DegToRad(FCADParams.Angle);
//    blk_ang := DegToRad(FCADParams.Insert.Angle);
    a1 := DegToRad(a1);
    a2 := DegToRad(a2);


    // ЭТО ЭЛЛИПС
    if DoubleCMP(a1, a2) then
    begin
      if ord(Cad.VerticalZero) = 1 then
        if ord(Cad.HorizontalZero) = 0 then
          a := 2 * pi - (a + blk_ang);
  //    Ellipse := TEllipse(Cad.Ellipse(LayerNbr, P.X, P.Y, Radx, Rady, a, 1, 0, 0, ord(bsClear), 0, False));
      Ellipse := TEllipse.create(P.X, P.Y, Radx, Rady, a, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Ellipse.color := TsgDXFEllipse(Sender).Color;
        Ellipse.Width := TsgDXFEllipse(Sender).Pen.Width;
      {$ELSE}
        Ellipse.color := GetColor(Sender);
        Ellipse.Width := RoundUp(TsgDXFEllipse(Sender).LineWeight);
        if Ellipse.width < 0 then
          Ellipse.width := 1;
      {$IFEND}

      Ellipse.Style := ord(entstyle(TsgDXFEllipse(Sender)));;
      Result := Ellipse;
    end
    else
    // ЭТО ЭЛЛИПТИЧЕСКАЯ АРКА
    begin
      // корректировать с учетом системы PowerCad
      if ord(Cad.VerticalZero) = 1 then
      begin
        if ord(Cad.HorizontalZero) = 0 then
        begin
          a1 := 2 * pi - a1;
          a2 := 2 * pi - a2;
          ta := a1;
          a1 := a2;
          a2 := ta;
          // IGOR 22.10.2013 - Нашелся DWG в котором так не нужно делать
          // возможно по аналогии с арками нужно дорулить...
          //a := 2 * pi - (a + blk_ang);
        end;
      end;

      if z < 0 then
      begin
        a1 := pi - a1;
        a2 := pi - a2;
        ta := a1;
        a1 := a2;
        a2 := ta;
      end;

      if FCADParams.XScale < 0 then
      begin
        // IGOR 22.10.2013 - Нашелся DWG в котором так не нужно делать
        // возможно по аналогии с арками нужно дорулить...
        //a := a - pi;
      end;

//////// IGOR 22.10.2013 - Добавим изменения на подобие как делается в арках:

    // SCALE ОБЫЧНЫЕ !!!
    modscalex := abs(FCADParams.XScale);
    modscaley := abs(FCADParams.YScale);
    //// IGOR 22.10.2013 - В данном случае не зависимо от скейлов:
    //if (DoubleCMP(modscalex, 1) and DoubleCMP(modscaley, 1)) then
    begin
      a1 := a1 + (pi * 2 - blk_ang);
      a2 := a2 + (pi * 2 - blk_ang);
      if FCADParams.XScale < 0 then
      begin
        a1 := a1 + 2 * (pi - a1);
        a2 := a2 + 2 * (pi - a2);
        ta := a2;
        a2 := a1;
        a1 := ta;
        a1 := a1 + (2 * pi  - 2 * blk_ang);
        a2 := a2 + (2 * pi  - 2 * blk_ang);
      end;
      // здесь было создание просто арки
    end;

    //else
    (*
    begin
      a := 2 * pi - blk_ang;
      if FCADParams.XScale < 0 then
      begin
        a := a - pi;
      end;
    //  а здесь было создание арки а затем с нее кривой бизье
    end;
    *)

////////////

     ElpArc := TElpArc.create(P.X, P.Y, Radx, Rady, a1, a2, a, 1, 0, 0, ord(bsClear), 0, ord(asOpen), LHandle, mydsNormal, Cad);
      ElpArc.Draw(Cad.DEngine, False);
      {$IF Defined(CADImport6)}
        ElpArc.color := TsgDXFEllipse(Sender).Color;
        ElpArc.Width := TsgDXFEllipse(Sender).Pen.Width;
      {$ELSE}
        ElpArc.color := GetColor(Sender);
        ElpArc.Width := RoundUp(TsgDXFEllipse(Sender).LineWeight);
        if ElpArc.width < 0 then
          ElpArc.width := 1;
      {$IFEND}

      ElpArc.Style := ord(entstyle(TsgDXFEllipse(Sender)));
      P1.x := P.x;
      P1.y := P.y;
      P1.z := P.z;
      Poly := TPolyline(ElpArc.DuplicateAsBezier);
  //    Cad.AddCustomFigure(LayerNbr, Poly, False);
  //    Cad.Figures.Remove(ElpArc);
      FreeAndNil(ElpArc);
      Poly.Rotate(a, P1);
      Result := Poly;
    end;
   { s := '';
    S := S + ' Center point: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10' RxX: ' + FloatToStr(Radx);
    S := S + #13#10' RxY: ' + FloatToStr(Rady);

    AssignFile(f, 'd:\Tolik\ARC.txt');
    reset(f);
    append(f);
    writeln(f,s);
    close(f);}
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportEllipse', E.Message);
  end;   
end;
// Tolik -- 28/12/2015 -- старая закомменчена (смю ниже) здесь выполнен сброс углов до пределов одного круга(360)
// и снято округление границ, т.к. при малых величинах получается точка вместо прямоугольника

function TF_Import.ImportArc(Sender: TObject): TFigure;
var
  P: TFPoint;
  P1: TDoublePoint;
  S: string;
  Arc: TArc;
  ElpArc: TElpArc;
  Ellipse: TEllipse;
  Poly: TPolyline;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  Rad, Rad1: double;
  a, a1, a2, ta: double;
  modscalex, modscaley: double;
  blk_ang: double;
  RP: TDoublePoint;
  da: double;
  z: double;
  b: boolean;
  Aaa: TsgArc;
  R: TFRect;
  // Tolik -- 28/12/2015 --
  //P11, P22: TPoint;
  P11, P22: TDoublePoint;
  f: TextFile;
  ArcVals: string;
  //
  summ: Double;
  vName: string;
  TempPoint: TFPoint;
  MaxX, MaxY,MinX, MinY: double;

  function CheckEllipse: Boolean;
  var i: Integer;
  begin
    Result := True;
    if TsgDxfArc(Sender).PolyPoints.Count > 5 then
    begin
      MaxX := TsgDxfArc(Sender).Points[0].X;
      MaxY := TsgDxfArc(Sender).Points[0].Y;
      MinX := TsgDxfArc(Sender).Points[0].X;
      MinY := TsgDxfArc(Sender).Points[0].Y;
      // Get Bounds
      for i := 1 to TsgDxfArc(Sender).PolyPoints.Count - 1 do
      begin
        if MaxX < TsgDxfArc(Sender).Points[i].X then
          MaxX := TsgDxfArc(Sender).Points[i].X;
        if MaxY < TsgDxfArc(Sender).Points[i].Y then
          MaxY := TsgDxfArc(Sender).Points[i].Y;
        if MinX > TsgDxfArc(Sender).Points[i].X then
          MinX := TsgDxfArc(Sender).Points[i].X;
        if MinY > TsgDxfArc(Sender).Points[i].Y then
          MinY := TsgDxfArc(Sender).Points[i].Y;
      end;
      // check the CenterPoint + Radius
      if ((P.X >= MinX) and (P.X <=MaxX) and (P.Y >= MinY) and (P.Y <= MaxY)) then
      // if Right CenterPoint - check with Radius
      begin
        if (((P.X - Abs(TsgDxfArc(Sender).Radius)) >= MinX) and ((P.X + Abs(TsgDxfArc(Sender).Radius)) <=MaxX) and
           ((P.Y - Abs(TsgDxfArc(Sender).Radius)) >= MinY) and ((P.Y + Abs(TsgDxfArc(Sender).Radius)) <= MaxY)) then
          Result := True
        else
          Result := False;
      end
      else
        Result := False;
    end;
  end;
begin
  try
    Result := nil;
    // Tolik 05/01/2016
    if not TsgDXFArc(Sender).Visible then
      Exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFArc(Sender).Point, FCADParams.Matrix);
      z := Round(TsgDXFArc(Sender).Extrusion.z);
      if z < 0 then
      begin
        TempPoint := TsgDXFArc(Sender).Point;
        TempPoint.X := - (TsgDXFArc(Sender).Point.X);
        P := PtXMat(TempPoint, FCADParams.Matrix);
      end;
    {$ELSE}

      //P := TsgDXFArc(Sender).Point;
      // DoExtrusion(P, TsgDXFArc(Sender).Extrusion);
      //P := FPointXMat(P, FCADParams.Matrix);
     //  P := FPointXMat(TsgDXFArc(Sender).Point, FCADParams.Matrix);
      //Tolik -- 18/01/2016 -- невидимые объекты - не грузим
      {if not TsgDXFArc(Sender).Visible then
        beep;}

      //
      z := Round(TsgDXFArc(Sender).Extrusion.z);
      //Tolik -- 29/12/2015
      {ArcVals := 'P.X = ' + FormatFloat('0.00', P.X);
      ArcVals := ArcVals + '  P.Y = ' + FormatFloat('0.00', P.Y);
      ArcVals := ArcVals + '  P.Z = ' + FormatFloat('0.00', P.Z);
      ArcVals := ArcVals + '  z = ' + FormatFloat('0.00', z);

      AssignFile(f, 'd:\Tolik\ARC.txt');
      Append(f);
      Writeln(f, ArcVals);
      CloseFile(f); }
      //if p.x < 0 then
      //begin
      //  if (TsgDXFArc(Sender).Point.X > TsgDXFArc(Sender).StartPoint.X) and
      //    (TsgDXFArc(Sender).Point.X > TsgDXFArc(Sender).EndPoint.X) then
      //  begin
      //    TempPoint := TsgDXFArc(Sender).Point;
      //    TempPoint.X := - (TsgDXFArc(Sender).Point.X);
      //    P := FPointXMat(TempPoint, FCADParams.Matrix);
      //  end;
      //end;

      // ВОТ ТАК ПРАВИЛЬНО ПО ХОДУ ДЕЛАТЬ ВЕЗДЕ!
      // Tolik -- ссылка от Игоря, подыбать, може чем помогеть:
      { http://cadsofttools.com/forum/viewtopic.php?f=15&t=1344&p=2816&hilit=arc+matrix#p2816}
      if z < 0 then
      begin
        TempPoint := TsgDXFArc(Sender).Point;
        TempPoint.X := - (TsgDXFArc(Sender).Point.X);
        //DoExtrusion(TempPoint, TsgDXFArc(Sender).Extrusion);
        P := FPointXMat(TempPoint, FCADParams.Matrix);
      end;
    {$IFEND}
    S := S + ' Center point: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10' Start Angle: ' + FloatToStr(TsgDXFArc(Sender).StartAngle);
    S := S + #13#10' End Angle: ' + FloatToStr(TsgDXFArc(Sender).EndAngle);
    S := S + #13#10' Rx: ' + FloatToStr(TsgDXFArc(Sender).Radius);
    TxtFile.Add(S);


    //**************************************************************************//
    Aaa := EntArc(TsgDXFArc(Sender), FCADParams);

    R.Left := Round(Aaa.Rect.Left);
    R.Top := Round(Aaa.Rect.Top);
    R.Right := Round(Aaa.Rect.Right);
    R.Bottom := Round(Aaa.Rect.Bottom);
    {
    P11.X := Round(Aaa.Point1.X);
    P11.Y := Round(Aaa.Point1.Y);
    P22.X := Round(Aaa.Point2.X);
    P22.Y := Round(Aaa.Point2.Y);
    }

    { R.Left := (Aaa.Rect.Left);
    R.Top := (Aaa.Rect.Top);
    R.Right := (Aaa.Rect.Right);
    R.Bottom := (Aaa.Rect.Bottom);}
   //
    P11.X := (Aaa.Point1.X);
    P11.Y := (Aaa.Point1.Y);
    P22.X := (Aaa.Point2.X);
    P22.Y := (Aaa.Point2.Y);
    //
    summ := P11.x + P11.Y + P22.X + P22.y;
    if DoubleCMP(summ, P11.X) or DoubleCMP(summ, P22.X) or DoubleCMP(summ, P11.Y) or DoubleCMP(summ, P22.Y)then
    begin
      if z = 0 then
        exit;
    end;

    if (P11.X = P22.X) and (P11.Y = P22.Y) then
    begin
      if z = 0 then
        exit;
    end;
    if (P11.X = 0) AND (P22.X = 0) and (P11.Y = 0) AND (P22.Y = 0) then
    begin
      if z = 0 then
        exit;
    end;

    Cad := TPCDrawing(GCadForm.PCad);
    P := ModificatePoint(P);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFArc(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Rad := TsgDXFArc(Sender).Radius;
    // Tolik
    Rad1 := TsgDXFArc(Sender).Radius;
    if FCadParams.Insert <> nil then
    begin
     { Rad := TsgDXFArc(Sender).Radius * ABS(FCadParams.Insert.Scale.X);
      Rad1 := TsgDXFArc(Sender).Radius * ABS(FCadParams.Insert.Scale.Y);
      if FCadParams.Insert.Scale.X < 0 then
        p.x := p.x * (-1);
      if FCadParams.Insert.Scale.Y < 0 then
        p.y := p.y* (-1);}
    end;
    //
    a1 := TsgDXFArc(Sender).StartAngle;
    a2 := TsgDXFArc(Sender).EndAngle;
    while Round(a1) >= 360 do
      a1 := a1 - 360;
    while Round(a2) >= 360 do
      a2 := a2 - 360;

    blk_ang := DegToRad(FCADParams.Angle);
    a1 := DegToRad(a1);
    a2 := DegToRad(a2);

    // это очень круглый элипс
    if DoubleCMP(a1, a2) then
    begin
      a := blk_ang;
      if ord(Cad.VerticalZero) = 1 then
        if ord(Cad.HorizontalZero) = 0 then
          a := 2 * pi - (a + blk_ang);
  //    Ellipse := TEllipse(Cad.Ellipse(LayerNbr, P.X, P.Y, Radx, Rady, a, 1, 0, 0, ord(bsClear), 0, False));
      // Tolik -- 16/01/2016
      if CheckEllipse then
        Ellipse := TEllipse.create(P.X, P.Y, Rad, Rad1, a, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad)
      else
      begin
        Rad := (MaxX  - MinX ) / 2;
        Rad1 := (MaxY - MinY) / 2;
        P.X := (MinX + MaxX) / 2;
        P.Y := (MinY + MaxY) / 2;
        P.Z := 0;
        P.V[0] := P.X;
        P.V[1] := P.y;
        P.V[2] := 1;
        P := FPointXMat(P, FCADParams.Matrix);
        P := ModificatePoint(P);
        Ellipse := TEllipse.create(P.X, P.Y, Rad, Rad1, a, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);

       { s := '';
        S := S + ' Center point: ';
        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
        S := S + #13#10' Start Angle: ' + FloatToStr(TsgDXFArc(Sender).StartAngle);
        S := S + #13#10' End Angle: ' + FloatToStr(TsgDXFArc(Sender).EndAngle);
        S := S + #13#10' Rx: ' + FloatToStr(Rad);
        S := S + #13#10' Rx1: ' + FloatToStr(Rad1);

        AssignFile(f, 'd:\Tolik\ARC.txt');
        reset(f);
        append(f);
        writeln(f,s);
        close(f);  }
      end;

      {$IF Defined(CADImport6)}
        Ellipse.color := TsgDXFEllipse(Sender).Color;
        Ellipse.Width := TsgDXFEllipse(Sender).Pen.Width;
      {$ELSE}
        Ellipse.color := GetColor(Sender);
        Ellipse.Width := RoundUp(TsgDXFEllipse(Sender).LineWeight);
        if Ellipse.width < 0 then
          Ellipse.width := 1;
      {$IFEND}

      Ellipse.Style := ord(entstyle(TsgDXFEllipse(Sender)));;
      Result := Ellipse;
    end
    else
    // ЭТО АРКА
    begin
      // корректировать с учетом системы PowerCad
      if ord(Cad.VerticalZero) = 1 then
      begin
        if ord(Cad.HorizontalZero) = 0 then
        begin
          a1 := 2 * pi - a1;
          a2 := 2 * pi - a2;
          ta := a1;
          a1 := a2;
          a2 := ta;
        end;
      end;

      if z < 0 then
      begin
        {TODO} // изначально было P.x := - P.X; - но оно тут по ходу не всегда нужно
        // возможно будут файлы для которых нужно такое преобразование - по правильному сделано через TempPoint
        //P.x := - P.X;
        a1 := pi - a1;
        a2 := pi - a2;
        ta := a1;
        a1 := a2;
        a2 := ta;
      end;

      // SCALE ОБЫЧНЫЕ !!!
      modscalex := abs(FCADParams.XScale);
      modscaley := abs(FCADParams.YScale);
      if (DoubleCMP(modscalex, 1) and DoubleCMP(modscaley, 1)) then
      begin
        a1 := a1 + (pi * 2 - blk_ang);
        a2 := a2 + (pi * 2 - blk_ang);
        if FCADParams.XScale < 0 then
        begin
          a1 := a1 + 2 * (pi - a1);
          a2 := a2 + 2 * (pi - a2);
          ta := a2;
          a2 := a1;
          a1 := ta;
          a1 := a1 + (2 * pi  - 2 * blk_ang);
          a2 := a2 + (2 * pi  - 2 * blk_ang);
        end;
        // Tolik -- 28/12/2015

        While ((Comparevalue(a1, (pi*2)) = 1) or (Comparevalue(a1, (pi*2)) = 0)) do
          a1 := a1 - (pi*2);
        While ((Comparevalue(a2, (pi*2)) = 1) or (Comparevalue(a2, (pi*2)) = 0)) do
          a2 := a2 - (pi*2);
        //сбросить в ноль (при 0 в дабле может быть мусор - типа, мелкое число, но никак не 0, а потом
        // при создании арки с "не ноль" получится херня кака-то)
        if ((RoundTo(a1, -10) = 0) or (RoundTo(a1, -10) = -0)) then
          a1 := 0;
        if ((RoundTo(a2, -10) = 0) or (RoundTo(a2, -10) = -0)) then
          a2 := 0;
        

        //Tolik -- 28/12/2015
        {ArcVals := 'P.X = ' + FormatFloat('0.00', P.X);
        ArcVals := ArcVals + '  P.Y = ' + FormatFloat('0.00', P.Y);
        ArcVals := ArcVals + '  Rad = ' + FormatFloat('0.00', Rad);
        ArcVals := ArcVals + '  a1 = ' + FormatFloat('0.00', a1);
        ArcVals := ArcVals + '  a2 = ' + FormatFloat('0.00', a2);
        ArcVals := ArcVals + '  a = ' + FormatFloat('0.00', a);
        //
        AssignFile(f, 'd:\Tolik\ARC.txt');
        Append(f);
        Writeln(f, ArcVals);
        CloseFile(f); }
        //
    //    Arc := TArc(Cad.Arc(LayerNbr, P.X, P.Y, Rad, a1, a2, 1, 0, 0, 0, 0, 0, False));
        Arc := TArc.create(P.X, P.Y, Rad, a1, a2, 1, 0, 0, 0, 0, 0, LHandle, mydsNormal, Cad);

        {$IF Defined(CADImport6)}
          Arc.color := TsgDXFArc(Sender).Color;
          Arc.Width := TsgDXFArc(Sender).Pen.Width;
        {$ELSE}
          Arc.color := GetColor(Sender);
          Arc.Width := RoundUp(TsgDXFArc(Sender).LineWeight);
          if Arc.width < 0 then
            Arc.width := 1;
        {$IFEND}

        Arc.Style := ord(entstyle(TsgDXFArc(Sender)));
        Result := Arc;
      end
      else
      begin
        a := 2 * pi - blk_ang;
        if FCADParams.XScale < 0 then
        begin
          a := a - pi;
        end;
        //Tolik -- 28/12/2015 -- игрушка для посмотреть на то, что получилось  --
       { ArcVals := 'P.X = ' + FormatFloat('0.00', P.X);
        ArcVals := ArcVals + '  P.Y = ' + FormatFloat('0.00', P.Y);
        ArcVals := ArcVals + '  Rad = ' + FormatFloat('0.00', Rad);
        ArcVals := ArcVals + '  a1 = ' + FormatFloat('0.00', a1);
        ArcVals := ArcVals + '  a2 = ' + FormatFloat('0.00', a2);
        ArcVals := ArcVals + '  a = ' + FormatFloat('0.00', a);
        //
        AssignFile(f, 'd:\Tolik\ARC.txt');
        Append(f);
        Writeln(f, ArcVals);
        CloseFile(f); }

    //    ElpArc := TElpArc(Cad.ElpArc(LayerNbr, P.X, P.Y, Rad, Rad, a, a1, a2, 1, 0, 0, ord(bsClear), 0, ord(asOpen), False));
        ElpArc := TElpArc.create(P.X, P.Y, Rad, Rad, a1, a2, a, 1, 0, 0, ord(bsClear), 0, ord(asOpen), LHandle, mydsNormal, Cad);
        ElpArc.Draw(Cad.DEngine, False);

        {$IF Defined(CADImport6)}
          ElpArc.color := TsgDXFArc(Sender).Color;
          ElpArc.Width := TsgDXFArc(Sender).Pen.Width;
        {$ELSE}
          ElpArc.color := GetColor(Sender);
          ElpArc.Width := RoundUp(TsgDXFArc(Sender).LineWeight);
          if ElpArc.width < 0 then
            ElpArc.width := 1;
        {$IFEND}

        ElpArc.Style := ord(entstyle(TsgDXFArc(Sender)));
        P1.x := P.x;
        P1.y := P.y;
        P1.z := P.z;
        Poly := TPolyline(ElpArc.DuplicateAsBezier);
    //    Cad.AddCustomFigure(LayerNbr, Poly, False);
    //    Cad.Figures.Remove(ElpArc);
        FreeAndNil(ElpArc);
        Poly.scale(FCADParams.XScale, FCADParams.YScale, P1);
        Poly.Rotate(a, P1);
        Result := Poly;
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportArc', E.Message);
  end;
end;
(*
function TF_Import.ImportArc(Sender: TObject): TFigure;
var
  P: TFPoint;
  P1: TDoublePoint;
  S: string;
  Arc: TArc;
  ElpArc: TElpArc;
  Ellipse: TEllipse;
  Poly: TPolyline;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  Rad: double;
  a, a1, a2, ta: double;
  modscalex, modscaley: double;
  blk_ang: double;
  RP: TDoublePoint;
  da: double;
  z: double;
  b: boolean;
  Aaa: TsgArc;
  R: TFRect;
  P11, P22: TPoint;
  summ: Double;
  vName: string;
  TempPoint: TFPoint;
begin
  try
    Result := nil;
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFArc(Sender).Point, FCADParams.Matrix);
      z := Round(TsgDXFArc(Sender).Extrusion.z);
      if z < 0 then
      begin
        TempPoint := TsgDXFArc(Sender).Point;
        TempPoint.X := - (TsgDXFArc(Sender).Point.X);
        P := PtXMat(TempPoint, FCADParams.Matrix);
      end;
    {$ELSE}
      P := FPointXMat(TsgDXFArc(Sender).Point, FCADParams.Matrix);
      z := Round(TsgDXFArc(Sender).Extrusion.z);
      //if p.x < 0 then
      //begin
      //  if (TsgDXFArc(Sender).Point.X > TsgDXFArc(Sender).StartPoint.X) and
      //    (TsgDXFArc(Sender).Point.X > TsgDXFArc(Sender).EndPoint.X) then
      //  begin
      //    TempPoint := TsgDXFArc(Sender).Point;
      //    TempPoint.X := - (TsgDXFArc(Sender).Point.X);
      //    P := FPointXMat(TempPoint, FCADParams.Matrix);
      //  end;
      //end;
      // ВОТ ТАК ПРАВИЛЬНО ПО ХОДУ ДЕЛАТЬ ВЕЗДЕ!
      if z < 0 then
      begin
        TempPoint := TsgDXFArc(Sender).Point;
        TempPoint.X := - (TsgDXFArc(Sender).Point.X);
        P := FPointXMat(TempPoint, FCADParams.Matrix);
      end;
    {$IFEND}
    S := S + ' Center point: ';
    S := S + ' X=' + FloatToStr(P.X);
    S := S + ' Y=' + FloatToStr(P.Y);
    S := S + ' Z=' + FloatToStr(P.Z);
    S := S + #13#10' Start Angle: ' + FloatToStr(TsgDXFArc(Sender).StartAngle);
    S := S + #13#10' End Angle: ' + FloatToStr(TsgDXFArc(Sender).EndAngle);
    S := S + #13#10' Rx: ' + FloatToStr(TsgDXFArc(Sender).Radius);
    TxtFile.Add(S);
    if not TsgDXFArc(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    Aaa := EntArc(TsgDXFArc(Sender), FCADParams);
    R.Left := Round(Aaa.Rect.Left);
    R.Top := Round(Aaa.Rect.Top);
    R.Right := Round(Aaa.Rect.Right);
    R.Bottom := Round(Aaa.Rect.Bottom);

    P11.X := Round(Aaa.Point1.X);
    P11.Y := Round(Aaa.Point1.Y);
    P22.X := Round(Aaa.Point2.X);
    P22.Y := Round(Aaa.Point2.Y);

    summ := P11.x + P11.Y + P22.X + P22.y;
    if DoubleCMP(summ, P11.X) or DoubleCMP(summ, P22.X) or DoubleCMP(summ, P11.Y) or DoubleCMP(summ, P22.Y)then
    begin
      if z = 0 then
        exit;
    end;

    if (P11.X = P22.X) and (P11.Y = P22.Y) then
    begin
      if z = 0 then
        exit;
    end;
    if (P11.X = 0) AND (P22.X = 0) and (P11.Y = 0) AND (P22.Y = 0) then
    begin
      if z = 0 then
        exit;
    end;

    Cad := TPCDrawing(GCadForm.PCad);
    P := ModificatePoint(P);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFArc(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Rad := TsgDXFArc(Sender).Radius;
    a1 := TsgDXFArc(Sender).StartAngle;
    a2 := TsgDXFArc(Sender).EndAngle;
    while Round(a1) >= 360 do
      a1 := a1 - 360;
    while Round(a2) >= 360 do
      a2 := a2 - 360;

    blk_ang := DegToRad(FCADParams.Angle);
    a1 := DegToRad(a1);
    a2 := DegToRad(a2);

    // это очень круглый элипс
    if DoubleCMP(a1, a2) then
    begin
      a := blk_ang;
      if ord(Cad.VerticalZero) = 1 then
        if ord(Cad.HorizontalZero) = 0 then
          a := 2 * pi - (a + blk_ang);
  //    Ellipse := TEllipse(Cad.Ellipse(LayerNbr, P.X, P.Y, Radx, Rady, a, 1, 0, 0, ord(bsClear), 0, False));
      Ellipse := TEllipse.create(P.X, P.Y, Rad, Rad, a, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Ellipse.color := TsgDXFEllipse(Sender).Color;
        Ellipse.Width := TsgDXFEllipse(Sender).Pen.Width;
      {$ELSE}
        Ellipse.color := GetColor(Sender);
        Ellipse.Width := RoundUp(TsgDXFEllipse(Sender).LineWeight);
        if Ellipse.width < 0 then
          Ellipse.width := 1;
      {$IFEND}

      Ellipse.Style := ord(entstyle(TsgDXFEllipse(Sender)));;
      Result := Ellipse;
    end
    else
    // ЭТО АРКА
    begin
      // корректировать с учетом системы PowerCad
      if ord(Cad.VerticalZero) = 1 then
      begin
        if ord(Cad.HorizontalZero) = 0 then
        begin
          a1 := 2 * pi - a1;
          a2 := 2 * pi - a2;
          ta := a1;
          a1 := a2;
          a2 := ta;
        end;
      end;

      if z < 0 then
      begin
        {TODO} // изначально было P.x := - P.X; - но оно тут по ходу не всегда нужно
        // возможно будут файлы для которых нужно такое преобразование - по правильному сделано через TempPoint
        //P.x := - P.X;
        a1 := pi - a1;
        a2 := pi - a2;
        ta := a1;
        a1 := a2;
        a2 := ta;
      end;

      // SCALE ОБЫЧНЫЕ !!!
      modscalex := abs(FCADParams.XScale);
      modscaley := abs(FCADParams.YScale);
      if (DoubleCMP(modscalex, 1) and DoubleCMP(modscaley, 1)) then
      begin
        a1 := a1 + (pi * 2 - blk_ang);
        a2 := a2 + (pi * 2 - blk_ang);
        if FCADParams.XScale < 0 then
        begin
          a1 := a1 + 2 * (pi - a1);
          a2 := a2 + 2 * (pi - a2);
          ta := a2;
          a2 := a1;
          a1 := ta;
          a1 := a1 + (2 * pi  - 2 * blk_ang);
          a2 := a2 + (2 * pi  - 2 * blk_ang);
        end;

    //    Arc := TArc(Cad.Arc(LayerNbr, P.X, P.Y, Rad, a1, a2, 1, 0, 0, 0, 0, 0, False));
        Arc := TArc.create(P.X, P.Y, Rad, a1, a2, 1, 0, 0, 0, 0, 0, LHandle, mydsNormal, Cad);

        {$IF Defined(CADImport6)}
          Arc.color := TsgDXFArc(Sender).Color;
          Arc.Width := TsgDXFArc(Sender).Pen.Width;
        {$ELSE}
          Arc.color := GetColor(Sender);
          Arc.Width := RoundUp(TsgDXFArc(Sender).LineWeight);
          if Arc.width < 0 then
            Arc.width := 1;
        {$IFEND}

        Arc.Style := ord(entstyle(TsgDXFArc(Sender)));
        Result := Arc;
      end
      else
      begin
        a := 2 * pi - blk_ang;
        if FCADParams.XScale < 0 then
        begin
          a := a - pi;
        end;
    //    ElpArc := TElpArc(Cad.ElpArc(LayerNbr, P.X, P.Y, Rad, Rad, a, a1, a2, 1, 0, 0, ord(bsClear), 0, ord(asOpen), False));
        ElpArc := TElpArc.create(P.X, P.Y, Rad, Rad, a1, a2, a, 1, 0, 0, ord(bsClear), 0, ord(asOpen), LHandle, mydsNormal, Cad);
        ElpArc.Draw(Cad.DEngine, False);

        {$IF Defined(CADImport6)}
          ElpArc.color := TsgDXFArc(Sender).Color;
          ElpArc.Width := TsgDXFArc(Sender).Pen.Width;
        {$ELSE}
          ElpArc.color := GetColor(Sender);
          ElpArc.Width := RoundUp(TsgDXFArc(Sender).LineWeight);
          if ElpArc.width < 0 then
            ElpArc.width := 1;
        {$IFEND}

        ElpArc.Style := ord(entstyle(TsgDXFArc(Sender)));
        P1.x := P.x;
        P1.y := P.y;
        P1.z := P.z;
        Poly := TPolyline(ElpArc.DuplicateAsBezier);
    //    Cad.AddCustomFigure(LayerNbr, Poly, False);
    //    Cad.Figures.Remove(ElpArc);
        FreeAndNil(ElpArc);
        Poly.scale(FCADParams.XScale, FCADParams.YScale, P1);
        Poly.Rotate(a, P1);
        Result := Poly;
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportArc', E.Message);
  end;
end; *)

function TF_Import.ImportCircle(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  Circle: TCircle;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  z : double;
  R: TFRect;
  Aaa: TsgArc;
  P11, P22: TPoint;
  summ: double;
  TempPoint: TFPoint;
  // Tolik
  CRadius, CRadius1: double;
  LoadCircle: Boolean;
  Ellipse: TEllipse;
  f: TextFile;
  //

begin
  Result := nil;
  // Tolik 05/01/2016
  if not TsgDXFCircle(Sender).Visible then
    Exit;
  //
  try
     // Tolik -- если масштабы по осям будут разные, то вместо круга будем иимпортировать эллипс
     LoadCircle := True;
     //
    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFCircle(Sender).Point, FCADParams.Matrix);
      z := round(TsgDXFCircle(Sender).Extrusion.z);
      if z < 0 then
      begin
        TempPoint := TsgDXFCircle(Sender).Point;
        TempPoint.X := - (TsgDXFCircle(Sender).Point.X);
        P := PtXMat(TempPoint, FCADParams.Matrix);
      end;
    {$ELSE}
      // Tolik -- 30/12/2015
      // P := FPointXMat(TsgDXFCircle(Sender).Point, FCADParams.Matrix);
      P := TsgDXFCircle(Sender).Point;
      DoExtrusion(P, TsgDXFCircle(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);

      // Tolik
      if FCADParams.Insert <> nil then
      begin
       { LoadCircle := (FCADParams.Insert.Scale.x = FCADParams.Insert.Scale.y);
        if LoadCircle then
          CRadius := TsgDXFCircle(Sender).Radius * Abs(FCADParams.Insert.Scale.x)
        else
        begin
          CRadius := TsgDXFCircle(Sender).Radius * Abs(FCADParams.Insert.Scale.x);
          CRadius1 := TsgDXFCircle(Sender).Radius * Abs(FCADParams.Insert.Scale.y);
        end;
        }
      end
      else
      // Tolik -- если нет вхождения в блок -- берем тот радиус, что пришел
      CRadius := TsgDXFCircle(Sender).Radius;
      CRadius1 := TsgDXFCircle(Sender).Radius;
      //
      if LoadCircle then
      begin
        z := round(TsgDXFCircle(Sender).Extrusion.z);

        if z < 0 then
        begin
          TempPoint := TsgDXFCircle(Sender).Point;
          TempPoint.X := - (TsgDXFCircle(Sender).Point.X);
          // Tolik
           DoExtrusion(TempPoint, TsgDXFCircle(Sender).Extrusion);
          //
          P := FPointXMat(TempPoint, FCADParams.Matrix);
        end;

        {$IFEND}
        S := S + ' Center point: ';
        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
        S := S + #13#10' Rx: ' + FloatToStr(TsgDXFCircle(Sender).Radius);
        TxtFile.Add(S);
        if not TsgDXFCircle(Sender).Visible then
          exit;
        if FCADParams.Insert <> nil then
          if not FCADParams.Insert.Visible then
            exit;
        AssignFile(f, 'd:\Tolik\ARC.txt');
        reset(f);
        append(f);
        writeln(f,s);
        close(f);
        //**************************************************************************//
        Aaa := EntArc(TsgDXFArc(Sender), FCADParams);
        R.Left := Round(Aaa.Rect.Left);
        R.Top := Round(Aaa.Rect.Top);
        R.Right := Round(Aaa.Rect.Right);
        R.Bottom := Round(Aaa.Rect.Bottom);

        P11.X := Round(Aaa.Point1.X);
        P11.Y := Round(Aaa.Point1.Y);
        P22.X := Round(Aaa.Point2.X);
        P22.Y := Round(Aaa.Point2.Y);

        summ := P11.x + P11.Y + P22.X + P22.y;
        if DoubleCMP(summ, P11.X) or DoubleCMP(summ, P22.X) or DoubleCMP(summ, P11.Y) or DoubleCMP(summ, P22.Y)then
        begin
          if z = 0 then
            exit;
        end;
        if (P11.X = P22.X) and (P11.Y = P22.Y) then
        begin
          if z = 0 then
            exit;
        end;
        if (P11.X = 0) AND (P22.X = 0) and (P11.Y = 0) AND (P22.Y = 0) then
        begin
          if z = 0 then
            exit;
        end;

        {TODO} // изначально было P.x := - P.X; - но оно тут по ходу не всегда нужно
        // возможно будут файлы для которых нужно такое преобразование - по правильному сделано через TempPoint
        //if z < 0 then
        //  P.x := - P.X;

        Cad := TPCDrawing(GCadForm.PCad);
        P := ModificatePoint(P);
        LayerNbr := GetImportLayerNbr(Cad, TsgDXFCircle(Sender).Layer);
        LHandle := Cad.GetLayerHandle(LayerNbr);
        //  Circle := TCircle(Cad.Circle(LayerNbr, P.X, P.Y, TsgDXFCircle(Sender).Radius, 1, 0, 0, ord(bsClear), 0, False));
        // Tolik -- 12/01/2016 --
        // Circle := TCircle.create(P.X, P.Y, TsgDXFCircle(Sender).Radius, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);
        Circle := TCircle.create(P.X, P.Y, CRadius, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);
        //

        {$IF Defined(CADImport6)}
          Circle.color := TsgDXFCircle(Sender).Color;
          Circle.Width := TsgDXFCircle(Sender).Pen.Width;
        {$ELSE}
          Circle.color := GetColor(Sender);
          Circle.Width := RoundUp(TsgDXFCircle(Sender).LineWeight);
          if Circle.width < 0 then
            Circle.width := 1;
        {$IFEND}

        Circle.Style := ord(entstyle(TsgDXFCircle(Sender)));
        Result := Circle;
      end
    // Tolik -- 12/01/2016 -- если скейлы разные по осям, то импортируем эллипс
      else
      begin
        P := ModificatePoint(P);
        Cad := TPCDrawing(GCadForm.PCad);
        LayerNbr := GetImportLayerNbr(Cad, TsgDXFCircle(Sender).Layer);
        LHandle := Cad.GetLayerHandle(LayerNbr);
        if z < 0 then
        begin
          TempPoint := TsgDXFCircle(Sender).Point;
          TempPoint.X := - (TsgDXFCircle(Sender).Point.X);
          // Tolik
          // DoExtrusion(TempPoint, TsgDXFCircle(Sender).Extrusion);
          //
          P := FPointXMat(TempPoint, FCADParams.Matrix);
        end;
        Ellipse := TEllipse.create(P.X, P.Y, CRadius1, CRadius, 0, 1, 0, 0, ord(bsClear), 0, LHandle, mydsNormal, Cad);

        {$IF Defined(CADImport6)}
          Ellipse.color := TsgDXFCircle(Sender).Color;
          Ellipse.Width := TsgDXFCircle(Sender).Pen.Width;
        {$ELSE}
          Ellipse.color := GetColor(Sender);
          Ellipse.Width := RoundUp(TsgDXFCircle(Sender).LineWeight);
          if Ellipse.width < 0 then
            Ellipse.width := 1;
        {$IFEND}

        Ellipse.Style := ord(entstyle(TsgDXFCircle(Sender)));
        Result := Ellipse;
      end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportCircle', E.Message);
  end;
end;

{ //Tolik
function TF_Import.ImportPolyLine(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
  Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;
  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;
  Count, j, k: Integer;
  xLine : TsgDXFPolyline;

begin
  try
    Result := nil;
    xLine := TsgDXFPolyline(Sender);
    j := 0;

   SetLength(points,0);

    for i := 0 to xLine.PolyPoints.Count - 1 do
    begin
      P := xLine.PolyPoints[i];

      {$IF Defined(CADImport6)
      P := PtXMat(P, FCADParams.Matrix);
      {$ELSE
      P := FPointXMat(P, FCADParams.Matrix);
      {$IFEND
      SetLength(points, j + 1);
      P := ModificatePoint(P);
      points[j].x := P.x;
      points[j].y := P.y;
      points[j].z := P.z;
      inc(j);
    end;

    if not TsgDXFPolyline(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    if TsgDXFPolyLine(Sender).Count = 0 then
      exit;

    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);

    Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, TsgDXFPolyLine(Sender).Closed, LHandle, mydsNormal, Cad);

    {$IF Defined(CADImport6)
    Poly.Color := TsgDXFPolyLine(Sender).Pen.Color;
    Poly.Width := TsgDXFPolyLine(Sender).Pen.Width;
    {$ELSE
    Poly.Color := GetColor(Sender);
    Poly.Width := RoundUp(TsgDXFPolyLine(Sender).LineWeight);

    if Poly.width < 0 then
      Poly.width := 1;
    {$IFEND
    Poly.Style := ord(entstyle(TsgDXFPolyline(Sender)));
    Result := Poly;

  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPolyLine', E.Message);
  end;
end;       }

  {
function TF_Import.ImportPolyLine(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
  Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;
  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;
  Count, j, k: Integer;
  xLine : TsgDXFPolyline;
  Figure: TFigure;
  LineType: TsgCADEntities;

begin
  try
    Result := nil;
    xLine := TsgDXFPolyline(Sender);
    LineType := xLine.EntType;
    Figure := TFigure(xLine);  }
   { if LineType = ceLWPolyLine then
    begin
      S := S + ' Vertexes: ';
      j := 0;

      SetLength(points,0);


      k := xLine.Count;
      k := xLine.PolyPoints.Count;
      k := xLine.PointCount;
      k := xLine.Arrows.Count;

      for i := 0 to xLine.PolyPoints.Count - 1 do
      begin
        P := xLine.PolyPoints[i];// PolyPoints[i];

        {$IF Defined(CADImport6)
        P := PtXMat(P, FCADParams.Matrix);
        {$ELSE
        P := FPointXMat(P, FCADParams.Matrix);
        {$IFEND
        SetLength(points, j + 1);
        P := ModificatePoint(P);
        points[j].x := P.x;
        points[j].y := P.y;
        points[j].z := P.z;
        inc(j);
      end;

      if not TsgDXFPolyline(Sender).Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;
      //**************************************************************************//
      if TsgDXFPolyLine(Sender).Count = 0 then
        exit;
      Cad := TPCDrawing(GCadForm.PCad);
      LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
    //  Poly := TPolyline(Cad.PolyLine(LayerNbr, points, 1, ord(psSolid), clBlack, 0, ord(bsClear), clBlack, TsgDXFPolyLine(Sender).Closed, False));
      Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, TsgDXFPolyLine(Sender).Closed, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)
        Poly.Color := TsgDXFPolyLine(Sender).Pen.Color;
        Poly.Width := TsgDXFPolyLine(Sender).Pen.Width;
      {$ELSE
        Poly.Color := GetColor(Sender);
        Poly.Width := RoundUp(TsgDXFPolyLine(Sender).LineWeight);

        if Poly.width < 0 then
          Poly.width := 1;
      {$IFEND
      Poly.Style := ord(entstyle(TsgDXFPolyline(Sender)));
    end
    else     }
 {   begin
      S := S + ' Vertexes: ';
      Count := TsgDXFPolyLine(Sender).Count;
  //    SetLength(points, Count);
      j := 0;
      for I := 0 to TsgDXFPolyLine(Sender).Count - 1 do
      begin
        S := S + #13#10;
        S := S + ' P' + IntToStr(I + 1) + ': ';
        Vertex := TsgDXFVertex(TsgDXFPolyLine(Sender).Entities[I]);
        //31.10.2012   P := PtXMat(Vertex.Point, FCADParams.Matrix);
        P := TsgDXFPolyLine(Sender).Points[I];

        {$IF Defined(CADImport6)
          P := PtXMat(P, FCADParams.Matrix);
        {$ELSE
          P := FPointXMat(P, FCADParams.Matrix);
        {$IFEND

        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
        if not ((P.x = 0) and (P.y = 0) and (P.z = 0)) then
        begin
          SetLength(points, j + 1);
          P := ModificatePoint(P);
          points[j].x := P.x;
          points[j].y := P.y;
          points[j].z := P.z;
          inc(j);
        end;
      end;
      TxtFile.Add(S);

      if not TsgDXFPolyline(Sender).Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;
      //**************************************************************************//
      if TsgDXFPolyLine(Sender).Count = 0 then
        exit;
      Cad := TPCDrawing(GCadForm.PCad);
      LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
    //  Poly := TPolyline(Cad.PolyLine(LayerNbr, points, 1, ord(psSolid), clBlack, 0, ord(bsClear), clBlack, TsgDXFPolyLine(Sender).Closed, False));
      Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, TsgDXFPolyLine(Sender).Closed, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)
        Poly.Color := TsgDXFPolyLine(Sender).Pen.Color;
        Poly.Width := TsgDXFPolyLine(Sender).Pen.Width;
      {$ELSE
        Poly.Color := GetColor(Sender);
        Poly.Width := RoundUp(TsgDXFPolyLine(Sender).LineWeight);
        if Poly.width < 0 then
          Poly.width := 1;
      {$IFEND

      Poly.Style := ord(entstyle(TsgDXFPolyline(Sender)));
    end;

    Result := Poly;

  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPolyLine', E.Message);
  end;
end;  }


function ParamExists(AParamValue: string): Boolean;
var
  i: integer;
  CurrParamValue: String;
begin
  Result := false;
  if ParamCount > 0 then
    for i := 1 to ParamCount do
    begin
      CurrParamValue := ParamStr(i);
      if CurrParamValue = AParamValue then
      begin
        Result := true;
        Break; //// BREAK ////
      end;
    end;
end;
 (*
/// Tolik - - 13/01/2016 -- старая закомменчена, а здесь пробую поднять точки полилинии, как в примере - через вертексы
function TF_Import.ImportPolyLine(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
 // Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;

  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;
  Count, j: Integer;
  //Tolik
  xLine: TsgDXFPolyLine;
  wLine: TsgDXFLWPolyline;
  d2Line: Tsg2DPolyline;
  dwgLine: TsgDWGPolyline;

  Entity: TsgDXFEntity;
  aVertex: TsgDXFVertex;

begin
  try
    Result := nil;
    // Tolik 05/01/2016
    if not TsgDXFPolyLine(Sender).Visible then
    Exit;   
    //
    xLine := TsgDXFPolyLine(Sender);
    // может быть и так
//    wLine := TsgDXFLWPolyline(Sender);
//    d2Line := Tsg2DPolyline(Sender);
//    dwgLine := TsgDWGPolyline(Sender);
    j := 0;
    //S := S + ' Vertexes: ';
    //for I := 0 to TsgDXFPolyLine(Sender).Count - 1 do
    //begin
    //  S := S + #13#10;
    //  S := S + ' P' + IntToStr(I + 1) + ': ';
    //  Vertex := TsgDXFVertex(TsgDXFPolyLine(Sender).Entities[I]);
    //end;
    if not ParamExists('NoLimitDXFPolyCount') then
    begin
      i := xLine.PointCount;
      if (xLine.PointCount) > LimitDXFPolyCount then
        exit;
    end;
    //Tolik
    // чтобы меньше тормозило
    SetLength(points, xLine.Count);
    //
    begin
      j := 0;
      for I := 0 to xLine.Count - 1 do
      begin
        aVertex := TsgDXFVertex(TsgDXFPolyLine(Sender).Entities[I]);
        {$IF Defined(CADImport6)}
          P := PtXMat(aVertex.Point, FCADParams.Matrix);
          //P := PtXMat(P, FCADParams.Matrix);
        {$ELSE}
          P := FPointXMat(aVertex.Point, FCADParams.Matrix);
          // P := FPointXMat(P, FCADParams.Matrix);
          {P := xLine.Points[i];
          DoExtrusion(P, TsgDXFPolyLine(Sender).Extrusion);
          P := FPointXMat(P, FCADParams.Matrix);}
        {$IFEND}
        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
        if not ((P.x = 0) and (P.y = 0) and (P.z = 0)) then
        begin
          //Tolik
          //SetLength(points, j + 1);
          //
          P := ModificatePoint(P);
          points[j].x := P.x;
          points[j].y := P.y;
          points[j].z := P.z;
          inc(j);
        end;
      end;
      //Tolik
      // выставляем длину по факту прочитанных
      SetLength(points, j);
      //
      TxtFile.Add(S);

      if not xLine.Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;
      //**************************************************************************//
      if xLine.Count = 0 then
        exit;
      Cad := TPCDrawing(GCadForm.PCad);
  //    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LayerNbr := GetImportLayerNbr(Cad, xLine.Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
    //  Poly := TPolyline(Cad.PolyLine(LayerNbr, points, 1, ord(psSolid), clBlack, 0, ord(bsClear), clBlack, TsgDXFPolyLine(Sender).Closed, False));
      Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, xLine.Closed, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Poly.Color := xLine.Pen.Color;
        Poly.Width := xLine.Pen.Width;
      {$ELSE}
        Poly.Color := GetColor(Sender);
        Poly.Width := RoundUp(xLine.LineWeight);
        //Poly.Width := RoundUp(TsgDXFPolyLine(Sender).GlobalWeight); - после выруливания отрисовок от скалинга можно юзать, т.к. действит.толщина линии сидит здесь
        if Poly.width < 0 then
          Poly.width := 1;
      {$IFEND}
      Poly.Style := ord(entstyle(xLine));
      Result := Poly;
      //Tolik
      SetLength(Points,0);
      //
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPolyLine', E.Message);
  end;
end;
     *)

function TF_Import.ImportPolyLine(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
 // Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;

  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;
  Count, j: Integer;
  //Tolik
  xLine: TsgDXFPolyLine;
  wLine: TsgDXFLWPolyline;
  d2Line: Tsg2DPolyline;
  dwgLine: TsgDWGPolyline;
  Entity: TsgDXFEntity;
  Prev_PT: TFPoint;
  CanAddPoint : Boolean;
  //
begin
  try
    Result := nil;

    xLine := TsgDXFPolyLine(Sender);
    if not xLine.Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    if xLine.Count = 0 then
      exit;
    // может быть и так
//    wLine := TsgDXFLWPolyline(Sender);
//    d2Line := Tsg2DPolyline(Sender);
//    dwgLine := TsgDWGPolyline(Sender);
    j := 0;
    //S := S + ' Vertexes: ';
    //for I := 0 to TsgDXFPolyLine(Sender).Count - 1 do
    //begin
    //  S := S + #13#10;
    //  S := S + ' P' + IntToStr(I + 1) + ': ';
    //  Vertex := TsgDXFVertex(TsgDXFPolyLine(Sender).Entities[I]);
    //end;
    if not ParamExists('NoLimitDXFPolyCount') then
    begin
      if (xLine.PointCount) > LimitDXFPolyCount then
        exit;
    end;
    //Tolik
    // чтобы меньше тормозило
    SetLength(points, xLine.Count);
    //
    begin
      j := 0;
      for I := 0 to xLine.Count - 1 do
      begin
        P := xLine.Points[I];
        {$IF Defined(CADImport6)}
          P := PtXMat(P, FCADParams.Matrix);
        {$ELSE}
         // P := FPointXMat(P, FCADParams.Matrix);
         P := xLine.Points[i];
         DoExtrusion(P, TsgDXFPolyLine(Sender).Extrusion);
         P := FPointXMat(P, FCADParams.Matrix);
        {$IFEND}
        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
        // Tolik -- 18/01/2016 --
        // if not ((P.x = 0) and (P.y = 0) and (P.z = 0)) then
        if i = 0 then
        begin
          Prev_pt.x := P.X;
          Prev_pt.y := P.Y;
          Prev_pt.z := P.Z;
          CanAddPoint := True;
        end
        else
        begin
          if ((Prev_pt.x = P.X) and (Prev_pt.y = P.Y) and (Prev_pt.z = P.Z)) then
            CanAddPoint := False
          else
          begin
            Prev_pt.x := P.X;
            Prev_pt.y := P.Y;
            Prev_pt.z := P.Z;
            CanAddPoint := True;
          end;
        end;
        if CanAddPoint then
        begin
          P := ModificatePoint(P);
          points[j].x := P.x;
          points[j].y := P.y;
          points[j].z := P.z;
          inc(j);
        end;
      end;
      //Tolik
      // выставляем длину по факту прочитанных
      SetLength(points, j);
      //
      TxtFile.Add(S);


      Cad := TPCDrawing(GCadForm.PCad);
  //    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LayerNbr := GetImportLayerNbr(Cad, xLine.Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
    //  Poly := TPolyline(Cad.PolyLine(LayerNbr, points, 1, ord(psSolid), clBlack, 0, ord(bsClear), clBlack, TsgDXFPolyLine(Sender).Closed, False));
      Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, xLine.Closed, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Poly.Color := xLine.Pen.Color;
        Poly.Width := xLine.Pen.Width;
      {$ELSE}
        Poly.Color := GetColor(Sender);
        Poly.Width := RoundUp(xLine.LineWeight);
        //Poly.Width := RoundUp(TsgDXFPolyLine(Sender).GlobalWeight); - после выруливания отрисовок от скалинга можно юзать, т.к. действит.толщина линии сидит здесь
        if Poly.width < 0 then
          Poly.width := 1;
      {$IFEND}
      Poly.Style := ord(entstyle(xLine));
      Result := Poly;
      //Tolik
      SetLength(Points,0);
      //
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPolyLine', E.Message);
  end;
end;


// Tolik -- Experimental DXFLWPolyLine UP -- 18/01/2016
(*
function TF_Import.ImportLWPolyLine(Sender: TObject): TFigure;
var
  P: TFPoint;
  S: string;
  I: Integer;
 // Vertex: TsgDXFVertex;
  Cad: TPCDrawing;
  Poly: TPolyline;

  Points: TDoublePointArr;
  LayerNbr, LHandle: Integer;
  Count, j: Integer;
  //Tolik
  xLine: TsgDXFPolyLine;
  wLine: TsgDXFLWPolyline;
  d2Line: Tsg2DPolyline;
  dwgLine: TsgDWGPolyline;

  Entity: TsgDXFEntity;
begin
  try
    Result := nil;
    // Tolik 05/01/2016
  {  if not TsgDXFPolyLine(Sender).Visible then
    Exit;   }
    //
    xLine := TsgDXFLWPolyLine(Sender);
    // может быть и так
//    wLine := TsgDXFLWPolyline(Sender);
//    d2Line := Tsg2DPolyline(Sender);
//    dwgLine := TsgDWGPolyline(Sender);
    j := 0;
    //S := S + ' Vertexes: ';
    //for I := 0 to TsgDXFPolyLine(Sender).Count - 1 do
    //begin
    //  S := S + #13#10;
    //  S := S + ' P' + IntToStr(I + 1) + ': ';
    //  Vertex := TsgDXFVertex(TsgDXFPolyLine(Sender).Entities[I]);
    //end;
    if not ParamExists('NoLimitDXFPolyCount') then
    begin
      if (xLine.PointCount) > LimitDXFPolyCount then
        exit;
    end;
    //Tolik
    // чтобы меньше тормозило
    SetLength(points, xLine.PolyPoints.Count);
    //
    begin
      j := 0;
      for I := 0 to xLine.PolyPoints.Count - 1 do
      begin
        P := xLine.PolyPoints[I];
        {$IF Defined(CADImport6)}
          P := PtXMat(P, FCADParams.Matrix);
        {$ELSE}
         // P := FPointXMat(P, FCADParams.Matrix);
         P := xLine.PolyPoints[i];
         //DoExtrusion(P, TsgDXFPolyLine(Sender).Extrusion);
         P := FPointXMat(P, FCADParams.Matrix);
        {$IFEND}
        S := S + ' X=' + FloatToStr(P.X);
        S := S + ' Y=' + FloatToStr(P.Y);
        S := S + ' Z=' + FloatToStr(P.Z);
       // if not ((P.x = 0) and (P.y = 0) and (P.z = 0)) then
        begin
          //Tolik
          //SetLength(points, j + 1);
          //
          P := ModificatePoint(P);
          points[j].x := P.x;
          points[j].y := P.y;
          points[j].z := P.z;
          inc(j);
        end;
      end;
      //Tolik
      // выставляем длину по факту прочитанных
      SetLength(points, j);
      //
      TxtFile.Add(S);

      if not xLine.Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;
      //**************************************************************************//
      if xLine.Count = 0 then
        exit;
      Cad := TPCDrawing(GCadForm.PCad);
  //    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LayerNbr := GetImportLayerNbr(Cad, xLine.Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
    //  Poly := TPolyline(Cad.PolyLine(LayerNbr, points, 1, ord(psSolid), clBlack, 0, ord(bsClear), clBlack, TsgDXFPolyLine(Sender).Closed, False));
      Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, xLine.Closed, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Poly.Color := xLine.Pen.Color;
        Poly.Width := xLine.Pen.Width;
      {$ELSE}
        Poly.Color := GetColor(Sender);
        Poly.Width := RoundUp(xLine.LineWeight);
        //Poly.Width := RoundUp(TsgDXFPolyLine(Sender).GlobalWeight); - после выруливания отрисовок от скалинга можно юзать, т.к. действит.толщина линии сидит здесь
        if Poly.width < 0 then
          Poly.width := 1;
      {$IFEND}
      Poly.Style := ord(entstyle(xLine));
      Result := Poly;
      //Tolik
      SetLength(Points,0);
      //
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportPolyLine', E.Message);
  end;
end;
//
*)
function ImportTextFont(Sender: TObject): string;
var
  vText: TsgDXFText;

  function ImportMTextFontStyle(AStyle: TmvFontStyles): string;
  begin
    if fmBold in AStyle then Result := '  fmBold' + #13#10;
    if fmItalic in AStyle then Result := Result + '  fmItalic' + #13#10;
    if fmUnderline in AStyle then Result := Result + '  fmUnderline' + #13#10;
    if fmStrikeOut in AStyle then Result := Result + '  fmStrikeOut' + #13#10;
    if fmCondensed in AStyle then Result := Result + '  fmCondensed' + #13#10;
    if fmUpward in AStyle then Result := Result + '  fmUpward' + #13#10;
    if fmDownward in AStyle then Result := Result + '  fmDownward' + #13#10;
  end;

begin
  //Tolik
  Result := '';
  //
  try
    vText := TsgDXFText(Sender);
    if vText.Style <> nil then
    begin
      Result := Result + ' Text Style:' + #13#10;
      Result := Result + '  BigFont=' + vText.Style.BigFont + #13#10;
      Result := Result + '  WidthFactor=' + FloatToStr(vText.Style.WidthFactor) + #13#10;
    end;
    Result := ' Font: Name=' + vText.FontName + '; ';
    Result := Result + ' Height=' + IntToStr(vText.Font.Height) + '; ';
    Result := Result + ' Color=$' + IntToHex(vText.Font.Color, 8) + '; ' + #13#10;
    Result := Result + ' Style:' + #13#10 + ImportMTextFontStyle(vText.Font.Style);
    Result := Result + ' Thickness=' + FloatToStr(vText.GetThickness);
    Result := Result + #13#10' Generation=' + IntToStr(vText.Generation);
    Result := Result + #13#10' VAlign=' + IntToStr(vText.VAlign);
    Result := Result + #13#10' HAlign=' + IntToStr(vText.HAlign);
  except
    on E: Exception do AddExceptionToLogEx('ImportTextFont', E.Message);
  end;
end;

function GetDXFBlock(aID: Integer): TBlock;
var
  i: Integer;
begin
  try
    Result := nil;
    for i := 0 to FDXFBlocksList.Count - 1 do
      if aID = TBlock(FDXFBlocksList[i]).ID then
      begin
        Result := TBlock(FDXFBlocksList[i]);
        exit;
      end;
  except
    on E: Exception do AddExceptionToLogEx('CheckDXFBlockExist', E.Message);
  end;
end;

function CheckAnyText(aStr: string): Boolean;
var
  i: integer;
begin
  try
    Result := False;
    //31.10.2012 for i := 0 to Length(aStr) - 1 do
    for i := 1 to Length(aStr) do
      if aStr[i] <> #0 then
      begin
        Result := True;
        exit;
      end;
  except
    on E: Exception do AddExceptionToLogEx('CheckAnyText', E.Message);
  end;
end;

function TF_Import.ImportAttdef(Sender: TObject): TFigure;
begin
  try
    Result := nil;
    TxtFile.Add('Tag: '+TsgDXFAttdef(Sender).Tag);
    if not TsgDXFAttdef(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    Result := ImportText(Sender);
    ////
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportAttdef', E.Message);
  end;
end;

(*
function TF_Import.ImportText(Sender: TObject): TFigure;
var
  i: Integer;
  P: TFPoint;
  P1: TDoublePoint;
  S: string;
  LayerNbr, LHandle: Integer;
  vText: TRichText;
  Text: TText;
  TM: TTextMetric;
  xCanvas: TMetafileCanvas;
  h, w, txth: double;
  Cad: TPCDrawing;
  DxfText: TsgDXFText;
  a: double;

  InsideMText: Boolean;
  IsUnicodeText: Boolean;
  MText: TsgDXFMText;
  SHXText: String;
  SHXUnicodeText: String;
  Complex: Boolean;
  ObjText: String;
  TmpIntVal: Integer;
  //Tolik
  f: TextFile;
  OldP: TFPoint;
  DxfMText: TsgDXFMText;
begin
  try
    Result := nil;
    SHXText := '';
    ObjText := '';
    SHXUnicodeText := '';

    // разбиваем по классам для отдельного импорта
    if TsgDXFEntity(Sender) is TsgDXFText then
    begin
      // Tolik -- 16/01/2016 -- если текста не - можно не импортировать сразу
      // if not TsgDXFText(Sender).Visible then
      if ((not TsgDXFText(Sender).Visible) or  (TsgDXFText(Sender).IsEmpty)) then
      begin
        s := s;
        exit;
      end;
      if TsgDXFText(Sender).MText <> nil then
      begin
        if (trim(TsgDXFText(Sender).MText.Text) = '') and
           (trim(TsgDXFText(Sender).SHXText) = '') and
           (trim(TsgDXFText(Sender).SHXUnicodeText) = '') and
           (trim(TsgDXFText(Sender).Text) = '') then
        begin
          s := s;
          exit;
        end;
      end;
      if (trim(TsgDXFText(Sender).SHXText) = '') and
         (trim(TsgDXFText(Sender).SHXUnicodeText) = '') and
         (trim(TsgDXFText(Sender).Text) = '') then
      begin
        s := s;
        exit;
      end;
      if FCADParams.Insert <> nil then
      begin
        if not FCADParams.Insert.Visible then
        begin
          s := s;
          exit;
        end;
        //if FCADParams.Insert.Layer <> nil then
        begin
          //if (abs(FCADParams.Insert.Layer.Box.Bottom) = abs(FCADParams.Insert.Layer.Box.Left)) and
          //   (abs(FCADParams.Insert.Layer.Box.Left) = abs(FCADParams.Insert.Layer.Box.Right)) and
          //   (abs(FCADParams.Insert.Layer.Box.Right) = abs(FCADParams.Insert.Layer.Box.Top)) then
          if (abs(FCADParams.Insert.Box.Bottom) = abs(FCADParams.Insert.Box.Left)) and
             (abs(FCADParams.Insert.Box.Left) = abs(FCADParams.Insert.Box.Right)) and
             (abs(FCADParams.Insert.Box.Right) = abs(FCADParams.Insert.Box.Top)) and
             (trim(TsgDXFText(Sender).Text) = '') then
          begin
            s := s;
            exit;
          end;
        end;
      end;

      {$IF Defined(CADImport6)}
        P := PtXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
      {$ELSE}
        //P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
        //if FCADParams.Insert <> nil then
        //  P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Insert.GetMatrix)
        //else
        // Tolik 30/12/2015
        //P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
        P := TsgDXFText(Sender).StartPoint;
        //OldP := P;

        // DoExtrusion(P, TsgDXFText(Sender).Extrusion);
        P := FPointXMat(P, FCADParams.Matrix);
        //
      {$IFEND}
      S := S + ' Start point: ';
      S := S + #13#10' X=' + FloatToStr(P.X);
      S := S + #13#10' Y=' + FloatToStr(P.Y);
      S := S + #13#10' Z=' + FloatToStr(P.Z);
      S := S + ' Angle=' + FloatToStr(TsgDXFText(Sender).Rotation + FCADParams.Angle);
      S := S + #13#10 + ImportTextFont(Sender);
      S := S + #13#10' Text: ' + utf16decode(TsgDXFText(Sender).Text);
      if FTextUsePrevPt then
      begin
        FTextUsePrevPt := false;
        P := FTextPrevPt;
        S := S + #13#10'!!! Use prev pt.';
      end;
      TxtFile.Add(S);

      //31.10.2012 - проверка доп параметров на выявления текстов типа "\Q0.2617993878" замечено с установленным флагом InsideMText
      InsideMText := TsgDXFText(Sender).InsideMText;
      IsUnicodeText := TsgDXFText(Sender).IsUnicodeText;
      MText := TsgDXFText(Sender).MText;
      SHXText := TsgDXFText(Sender).SHXText;
      SHXUnicodeText := TsgDXFText(Sender).SHXUnicodeText;
      Complex := TsgDXFText(Sender).Complex;
      ObjText := utf16decode(TsgDXFText(Sender).Text);
      //31.10.2012 - не пропускаем служебный текст
      if InsideMText then
        if Length(ObjText) > 4 then
          if (ObjText[1] = '\') and Not TryStrToInt(ObjText[2], TmpIntVal) and TryStrToInt(ObjText[3], TmpIntVal) and (ObjText[4] = '.') then
          begin
            FTextPrevPt := P;
            FTextUsePrevPt := true;
            Exit; ///// EXIT /////
          end;


      if not TsgDXFText(Sender).Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;
      //**************************************************************************//
      Cad := TPCDrawing(GCadForm.PCad);
      DxfText := TsgDXFText(Sender);
      if not CheckAnyText(DxfText.Text) then
        exit;

      P := ModificatePoint(P);
      // Tolik -- 30/12/2015
     // if ((CompareValue(OldP.X, P.X) <> 0) or (CompareValue(OldP.X, P.X) <> 0)) then
      begin
        s:='';
        s := s + Objtext + SHXUnicodeText + SHXText;
        S := S + ' X= ' + FloatToStr(P.X);
        S := S + ' Y= ' + FloatToStr(P.Y);
        S := S + ' Z= ' + FloatToStr(P.Z);
        AssignFile(f, 'd:\Tolik\ARC.txt');
        reset(f);
        append(f);
        writeln(f,s);
        close(f);
      end;
      //
      LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
      a := DegToRad(DxfText.Rotation) + DegToRad(FCADParams.Angle);
      if ord(Cad.VerticalZero) = 1 then
        if ord(Cad.HorizontalZero) = 0 then
          a := 2 * pi - a;
      txth := DxfText.Height;
      // Tolik 12/01/2016 -- вхождение блока --
      {if FCADParams.Insert <> nil then
       txth := txth * FCADParams.Insert.Scale.Y;}
      //
      //  Text := TText(cad.TextOut(LayerNbr, P.x, P.y, 0, txth, 0, DxfText.Text, DxfText.FontName, DxfText.Font.Charset, DxfText.Color, False));
      // Tolik -- 11/01/2016 --
      //  Text := TText.Create(P.x, P.y, txth, 0, utf16decode(DxfText.Text), DxfText.FontName, DxfText.Font.Charset, DxfText.Color, LHandle, mydsNormal, Cad);
      DxfText.Color := GetColor(Sender);
      Text := TText.Create(P.x, P.y, txth, 0, utf16decode(DxfText.Text), DxfText.FontName, DxfText.Font.Charset, DxfText.Color, LHandle, mydsNormal, Cad);

      begin
        Text.TextLength := 0;
        Text.TextHeight := 0;
        Text.setRegionPoints;
      end;
      // Tolik 12/01/2016 --
      if FCadParams.Insert <> nil then
      begin
        Text.TextLength := Text.TextLength * FCadParams.Insert.Scale.X;
        Text.TextHeight := Text.TextHeight * FCadParams.Insert.Scale.Y;
      end;
     // TmvFontStyles = set of (fmBold, fmItalic, fmUnderline, fmStrikeOut, fmCondensed, fmUpward, fmDownward)
      //Text.Font.Style := DxfText.Font.Style;
      //
      P1.x := P.X;
      P1.y := P.y;
      P1.z := P.z;

      Text.Move(0, - txth);
      Text.rotate(a, P1);
      Result := Text;
    end; // -- TsgDxfText

    //  TsgDxfMText --
    if TsgDXFEntity(Sender) is TsgDXFMText then
    begin

      if not TsgDXFMText(Sender).Visible then
      begin
        s := s;
        exit;
      end;

      P := TsgDXFMText(Sender).Point;
      p := ModificatePoint(P);

      LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
      LHandle := Cad.GetLayerHandle(LayerNbr);
      a := DegToRad(TsgDXFAttrib(DxfMText.Attribs).Rotation) + DegToRad(FCADParams.Angle);
      if ord(Cad.VerticalZero) = 1 then
        if ord(Cad.HorizontalZero) = 0 then
          a := 2 * pi - a;
      txth := DxfMText.RectHeight;

      DxfMText := TsgDXFMText(Sender);
      if DxfMText.Block.Count > 0 then
      begin
        s := '';
        for i := 0 to DxfMText.Block.Count - 1 do
        begin
          if Length(s) > 0 then
            s := s + #13#10;
          s := s + TsgDxFText(DxfMText.Block.Entities[i]).Text;
        end;
        DxfMText.Color := GetColor(Sender);

        Text := TText.Create(P.x, P.y, txth, 0, utf16decode(s),TsgDxFText(DxfMText.Block.Entities[i -1]).FontName, TsgDxFText(DxfMText.Block.Entities[i -1]).Font.Charset, DxfMText.Color, LHandle, mydsNormal, Cad);
        Result := Text;
      end;


    end;


    EXIT;

    vText := TRichText.create(-100, -100, -100, -100, 1, ord(psSolid), clBlack, ord(psClear), clBlack, LHandle, mydsNormal, Cad);
    vText.re.WordWrap := false;
    vText.re.Font.Name := DxfText.FontName;
    vText.re.Font.Charset := DxfText.Font.Charset;
    vText.re.Font.Size := trunc(txth * 4);
    vText.re.Font.Style := [];
    vText.re.Font.Color := DxfText.Color;

    vText.re.Lines.Clear;
    vText.re.Lines.Add(DxfText.Text);

    // получить свойства
    xCanvas := TMetafileCanvas.Create(vText.Metafile, 0);
    xCanvas.Font.Name := vText.re.Font.Name;
    xCanvas.Font.Size := vText.re.Font.Size;
    xCanvas.Font.Style := vText.re.Font.Style;
    GetTextMetrics(xCanvas.Handle, TM);
    if vText.re.Lines.Count > 1 then
      h := TM.tmHeight / 4 * vText.re.Lines.Count + 1
    else
      h := TM.tmHeight / 4 * vText.re.Lines.Count;
    w := 0;
    for i := 0 to vText.re.Lines.Count - 1 do
    begin
      if w < xCanvas.TextWidth(vText.Re.Lines[i]) then
        w := xCanvas.TextWidth(vText.Re.Lines[i]);
    end;
    w := (w + 3) / 4 ;
    FreeAndNil(xCanvas);
    // пересоздать с новыми свойствами
    if vText <> nil then
      FreeAndNil(vText);

    vText := TRichText.create(P.x, P.y, P.x + w, P.y + h, 1, ord(psSolid), clBlack, ord(bsClear), clNone,
                              LHandle, mydsNormal, GCadForm.PCad);
    vText.re.WordWrap := false;
    vText.re.Font.Name := DxfText.FontName;
    vText.re.Font.Charset := DxfText.Font.Charset;
    vText.re.Font.Size := trunc(txth * 4);
    vText.re.Font.Style := [];
    vText.re.Font.Color := DxfText.Color;

    vText.re.Lines.Clear;
    vText.re.Lines.Add(DxfText.Text);
    P1.x := P.X;
    P1.y := P.y;
    P1.z := P.z;
    vText.Move(0, - (txth/2 + h/2));
    vText.rotate(a, P1);
    Cad.AddCustomFigure(LayerNbr, vText, false);
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportText', E.Message);
  end;
end;
*)
function TF_Import.ImportText(Sender: TObject): TFigure;
var
  i: Integer;
  P: TFPoint;
  P1: TDoublePoint;
  S: string;
  LayerNbr, LHandle: Integer;
  vText: TRichText;
  Text: TText;
  TM: TTextMetric;
  xCanvas: TMetafileCanvas;
  h, w, txth: double;
  Cad: TPCDrawing;
  DxfText: TsgDXFText;
  a: double;

  InsideMText: Boolean;
  IsUnicodeText: Boolean;
  MText: TsgDXFMText;
  SHXText: String;
  SHXUnicodeText: String;
  Complex: Boolean;
  ObjText: String;
  TmpIntVal: Integer;
  //Tolik
  f: TextFile;
  OldP: TFPoint;
begin
  try
    Result := nil;
    SHXText := '';
    ObjText := '';
    SHXUnicodeText := '';

    if not TsgDXFText(Sender).Visible then
    begin
      s := s;
      exit;
    end;
    if TsgDXFText(Sender).MText <> nil then
    begin
      if (trim(TsgDXFText(Sender).MText.Text) = '') and
         (trim(TsgDXFText(Sender).SHXText) = '') and
         (trim(TsgDXFText(Sender).SHXUnicodeText) = '') and
         (trim(TsgDXFText(Sender).Text) = '') then
      begin
        s := s;
        exit;
      end;
    end;
    if (trim(TsgDXFText(Sender).SHXText) = '') and
       (trim(TsgDXFText(Sender).SHXUnicodeText) = '') and
       (trim(TsgDXFText(Sender).Text) = '') then
    begin
      s := s;
      exit;
    end;
    if FCADParams.Insert <> nil then
    begin
      if not FCADParams.Insert.Visible then
      begin
        s := s;
        exit;
      end;
      //if FCADParams.Insert.Layer <> nil then
      begin
        //if (abs(FCADParams.Insert.Layer.Box.Bottom) = abs(FCADParams.Insert.Layer.Box.Left)) and
        //   (abs(FCADParams.Insert.Layer.Box.Left) = abs(FCADParams.Insert.Layer.Box.Right)) and
        //   (abs(FCADParams.Insert.Layer.Box.Right) = abs(FCADParams.Insert.Layer.Box.Top)) then
        if (abs(FCADParams.Insert.Box.Bottom) = abs(FCADParams.Insert.Box.Left)) and
           (abs(FCADParams.Insert.Box.Left) = abs(FCADParams.Insert.Box.Right)) and
           (abs(FCADParams.Insert.Box.Right) = abs(FCADParams.Insert.Box.Top)) and
           (trim(TsgDXFText(Sender).Text) = '') then
        begin
          s := s;
          exit;
        end;
      end;
    end;

    {$IF Defined(CADImport6)}
      P := PtXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
    {$ELSE}
      //P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
      //if FCADParams.Insert <> nil then
      //  P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Insert.GetMatrix)
      //else
      // Tolik 30/12/2015
      P := FPointXMat(TsgDXFText(Sender).StartPoint, FCADParams.Matrix);
     {
      P := TsgDXFText(Sender).StartPoint;
      OldP := P;
      DoExtrusion(P, TsgDXFText(Sender).Extrusion);
      P := FPointXMat(P, FCADParams.Matrix);
      }
      //
    {$IFEND}
    S := S + ' Start point: ';
    S := S + #13#10' X=' + FloatToStr(P.X);
    S := S + #13#10' Y=' + FloatToStr(P.Y);
    S := S + #13#10' Z=' + FloatToStr(P.Z);
    S := S + ' Angle=' + FloatToStr(TsgDXFText(Sender).Rotation + FCADParams.Angle);
    S := S + #13#10 + ImportTextFont(Sender);
    S := S + #13#10' Text: ' + utf16decode(TsgDXFText(Sender).Text);
    if FTextUsePrevPt then
    begin
      FTextUsePrevPt := false;
      P := FTextPrevPt;
      S := S + #13#10'!!! Use prev pt.';
    end;
    TxtFile.Add(S);

    //31.10.2012 - проверка доп параметров на выявления текстов типа "\Q0.2617993878" замечено с установленным флагом InsideMText
    InsideMText := TsgDXFText(Sender).InsideMText;
    IsUnicodeText := TsgDXFText(Sender).IsUnicodeText;
    MText := TsgDXFText(Sender).MText;
    SHXText := TsgDXFText(Sender).SHXText;
    SHXUnicodeText := TsgDXFText(Sender).SHXUnicodeText;
    Complex := TsgDXFText(Sender).Complex;
    ObjText := utf16decode(TsgDXFText(Sender).Text);
    //31.10.2012 - не пропускаем служебный текст
    if InsideMText then
      if Length(ObjText) > 4 then
        if (ObjText[1] = '\') and Not TryStrToInt(ObjText[2], TmpIntVal) and TryStrToInt(ObjText[3], TmpIntVal) and (ObjText[4] = '.') then
        begin
          FTextPrevPt := P;
          FTextUsePrevPt := true;
          Exit; ///// EXIT /////
        end;


    if not TsgDXFText(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    Cad := TPCDrawing(GCadForm.PCad);
    DxfText := TsgDXFText(Sender);
    if not CheckAnyText(DxfText.Text) then
      exit;

    P := ModificatePoint(P);
    // Tolik -- 30/12/2015
   // if ((CompareValue(OldP.X, P.X) <> 0) or (CompareValue(OldP.X, P.X) <> 0)) then
    begin
  {    s:='';
      s := s + Objtext + SHXUnicodeText + SHXText;
      S := S + ' X= ' + FloatToStr(P.X);
      S := S + ' Y= ' + FloatToStr(P.Y);
      S := S + ' Z= ' + FloatToStr(P.Z);
      AssignFile(f, 'd:\Tolik\ARC.txt');
      reset(f);
      append(f);
      writeln(f,s);
      close(f);  }
    end;
    //
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    a := DegToRad(DxfText.Rotation) + DegToRad(FCADParams.Angle);
    if ord(Cad.VerticalZero) = 1 then
      if ord(Cad.HorizontalZero) = 0 then
        a := 2 * pi - a;
    txth := DxfText.Height;

    DxfText.Color := GetColor(Sender);
    Text := TText.Create(P.x, P.y, txth, 0, utf16decode(DxfText.Text), DxfText.FontName, DxfText.Font.Charset, DxfText.Color, LHandle, mydsNormal, Cad);

    begin
      Text.TextLength := 0;
      Text.TextHeight := 0;
      Text.setRegionPoints;
    end;
    // Tolik 12/01/2016 --
   { if FCadParams.Insert <> nil then
    begin
      Text.TextLength := Text.TextLength * FCadParams.Insert.Scale.X;
      Text.TextHeight := Text.TextHeight * FCadParams.Insert.Scale.Y;
    end; }
   // TmvFontStyles = set of (fmBold, fmItalic, fmUnderline, fmStrikeOut, fmCondensed, fmUpward, fmDownward)
    //Text.Font.Style := DxfText.Font.Style;
    //
    P1.x := P.X;
    P1.y := P.y;
    P1.z := P.z;

    Text.Move(0, - txth);
    Text.rotate(a, P1);
    Result := Text;
    // TEST
    if TsgDxfEntity(Sender) is TsgDxfMText then
      AddExceptionToLogSilent('TF_Import.ReadCADEntities :  попался MText!!! ');
    //
    EXIT;

    vText := TRichText.create(-100, -100, -100, -100, 1, ord(psSolid), clBlack, ord(psClear), clBlack, LHandle, mydsNormal, Cad);
    vText.re.WordWrap := false;
    vText.re.Font.Name := DxfText.FontName;
    vText.re.Font.Charset := DxfText.Font.Charset;
    vText.re.Font.Size := trunc(txth * 4);
    vText.re.Font.Style := [];
    vText.re.Font.Color := DxfText.Color;

    vText.re.Lines.Clear;
    vText.re.Lines.Add(DxfText.Text);

    // получить свойства
    xCanvas := TMetafileCanvas.Create(vText.Metafile, 0);
    xCanvas.Font.Name := vText.re.Font.Name;
    xCanvas.Font.Size := vText.re.Font.Size;
    xCanvas.Font.Style := vText.re.Font.Style;
    GetTextMetrics(xCanvas.Handle, TM);
    if vText.re.Lines.Count > 1 then
      h := TM.tmHeight / 4 * vText.re.Lines.Count + 1
    else
      h := TM.tmHeight / 4 * vText.re.Lines.Count;
    w := 0;
    for i := 0 to vText.re.Lines.Count - 1 do
    begin
      if w < xCanvas.TextWidth(vText.Re.Lines[i]) then
        w := xCanvas.TextWidth(vText.Re.Lines[i]);
    end;
    w := (w + 3) / 4 ;
    FreeAndNil(xCanvas);
    // пересоздать с новыми свойствами
    if vText <> nil then
      FreeAndNil(vText);

    vText := TRichText.create(P.x, P.y, P.x + w, P.y + h, 1, ord(psSolid), clBlack, ord(bsClear), clNone,
                              LHandle, mydsNormal, GCadForm.PCad);
    vText.re.WordWrap := false;
    vText.re.Font.Name := DxfText.FontName;
    vText.re.Font.Charset := DxfText.Font.Charset;
    vText.re.Font.Size := trunc(txth * 4);
    vText.re.Font.Style := [];
    vText.re.Font.Color := DxfText.Color;

    vText.re.Lines.Clear;
    vText.re.Lines.Add(DxfText.Text);
    P1.x := P.X;
    P1.y := P.y;
    P1.z := P.z;
    vText.Move(0, - (txth/2 + h/2));
    vText.rotate(a, P1);
    Cad.AddCustomFigure(LayerNbr, vText, false);
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportText', E.Message);
  end;
end;


function TF_Import.ImportSpline(Sender: TObject): TFigure;
var
  vSpline: TsgDXFSpline absolute Sender;
  P: TFPoint;
  S: string;
  I, j: Integer;
  pLine: TPolyline;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  PCAD: TPowerCad;
  PolyPoints: TDoublePointArr;
  SinglePoint: TDoublePoint;
  aCad: TF_Cad;
  PointFound: Boolean;
  BuildByPolyPoints: boolean;

begin
  try
    Result := nil;
    if not TsgDXFSpline(Sender).Visible then
        exit;
      if FCADParams.Insert <> nil then
        if not FCADParams.Insert.Visible then
          exit;

    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFSpline(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    //Tolik

    BuildByPolyPoints := False;
  // Dear Tolik, LOOK To isByAngles flag:

  //       True:
  // Spline is built by Fit-points using BeginningTangent and EndingTangent

  //       False:
  // Spline is built by control points and knots.
  // Best regards, Tolik!

    SetLength(PolyPoints,0);
    j := 0;
    i := vSpline.FitCount;

    S := '';
    i := vSpline.Count;
    if vSpline.FitCount > 0 then
    begin
      BuildByPolyPoints := True;
    end;
    if not BuildByPolyPoints then
    begin

      if vSpline.ControlCount > 0 then
      begin
        j := 0;
        S := S + ' Control points of Spline: ';

        //Tolik
        // ограничение на количество точек
        if not ParamExists('NoLimitDXFPolyCount') then
        begin
          if (vSpline.ControlCount) > LimitDXFPolyCount then
            exit;
        end;
        // чтобы меньше тормозило
        SetLength(PolyPoints, vSpline.ControlCount);
        //
        for I := 0 to vSpline.ControlCount - 1 do
        begin
          S := S + #13#10 + ' P' + IntToStr(I + 1) + ': ';
          {$IF Defined(CADImport6)}
            P := PtXMat(PFPoint(vSpline.Controls[I])^, FCADParams.Matrix);
          {$ELSE}
           // 30/12/2015 -- Tolik
           //  P := FPointXMat(TFPoint(vSpline.Controls[I]), FCADParams.Matrix);
           P := TFPoint(vSpline.Controls[I]);
           // DoExtrusion(P, TsgDXFSpline(Sender).Extrusion);
           P := FPointXMat(P, FCADParams.Matrix);
          {$IFEND}
          S := S + PointToString(P);
          //Tolik
          // SetLength(PolyPoints, j);

          P := ModificatePoint(P);
          SinglePoint.x := P.X;
          SinglePoint.y := P.Y;
          SinglePoint.z := P.Z;

          PolyPoints[j] := SinglePoint;
          inc(j);
          //
        end;
        S := S + #13#10;
      end;

      if S <> '' then
        TxtFile.Add(S);

      // Check buid by PolyPoints
      if vSpline.ControlCount > 0 then
      begin
        i := vSpline.ControlCount;
        for i := 0 to vSpLine.ControlCount - 1 do
        begin
          PointFound := False;
          for j := 0 to vSpline.PolyPoints.Count - 1 do
          begin
            if IsEqualFPoints(vSpLine.ControlPoints[i], vSpline.PolyPoints[j], 0.00001) then
            begin
              PointFound := True;
              Break;
            end;
          end;
          if not PointFound then
          begin
            BuildByPolyPoints := True;
            Break;
          end;
        end;
      end;
    end;

    if Length(PolyPoints) = 0 then
    begin
      BuildByPolyPoints := True;
    end;

    if BuildbyPolyPoints then
    begin
      if not ParamExists('NoLimitDXFPolyCount') then
      begin
        if ((vSpline.PolyPoints.Count) > (LimitDXFPolyCount * 3)) then
          exit;
      end;
      SetLength(PolyPoints,0);
      SetLength(PolyPoints, vSpline.PolyPoints.Count);
      for i := 0 to vSpline.PolyPoints.Count - 1 do
      begin
        p := vSpline.PolyPoints[i];
        {$IF Defined(CADImport6)}
        P := PtXMat(PFPoint(P)^, FCADParams.Matrix);
        {$ELSE}
        // Tolik  -- 30/12/2015
        //  P := FPointXMat(TFPoint(P), FCADParams.Matrix);
        // DoExtrusion(P, TsgDXFSpline(Sender).Extrusion);
        P := FPointXMat(P, FCADParams.Matrix);
        {$IFEND}
        P := ModificatePoint(P);

        SinglePoint.x := P.X;
        SinglePoint.y := P.Y;
        SinglePoint.z := P.Z;

        PolyPoints[i] := SinglePoint;
      end;
    end;

    pLine := TPolyline.create(PolyPoints, 2, ord(psSolid), clBlack{xSpline.Color}, ord(bsClear), clBlack, 0, vSpline.Closed, Cad.GetLayerHandle(LayerNbr), mydsNormal, Cad);

    {$IF Defined(CADImport6)}
      PLine.Color := TsgDXFPolyLine(Sender).Pen.Color;
      PLine.Width := TsgDXFPolyLine(Sender).Pen.Width;
    {$ELSE}
      PLine.Color := GetColor(Sender);
      pLine.Width := RoundUp(TsgDXFPolyLine(Sender).LineWeight);
      if PLine.width < 0 then
        PLine.width := 1;
    {$IFEND}
    PLine.Style := ord(entstyle(TsgDXFPolyline(Sender)));
    Result := pLine;
    //
    //Tolik
    SetLength(PolyPoints, 0);
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportSpline', E.Message);
  end;
end;

(*  Не получилось поднять сплайны с преобразованием в кривые Безье (потому что для Фитов нужно еще юзать тангенты,
  // а для Контрольных точек Кноты...получается кривовато...
function TF_Import.ImportSpline(Sender: TObject): TFigure;
var
  vSpline: TsgDXFSpline absolute Sender;
  P: TFPoint;
  S: string;
  I, j: Integer;
  xSpline: TsgDXFSpline;
  xPolyLine: TsgDXFPolyline;
  pLine: TPolyline;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  PCAD: TPowerCad;
  PolyPoints: TDoublePointArr;
  SinglePoint: TDoublePoint;
  aCad: TF_Cad;
  PointFound: Boolean;
  ConvertToBezie, BuildByPolyPoints: boolean;
  KnotCounts: Integer;
  KnotVal: Single;
begin
  try
    Result := nil;
    if not TsgDXFSpline(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;

    //Tolik
    ConvertToBezie := False;
    BuildByPolyPoints := False;
  // Dear Tolik, LOOK To isByAngles flag:

  //       True:
  // Spline is built by Fit-points using BeginningTangent and EndingTangent

  //       False:
  // Spline is built by control points and knots.
  // Best regards, Tolik!

    SetLength(PolyPoints,0);
    j := 0;
    i := vSpline.FitCount;

    S := '';
    i := vSpline.Count;
    if vSpline.FitCount > 0 then
    begin
      S := S + ' Fit points of Spline: ';
      for I := 0 to vSpline.FitCount - 1 do
      begin
        S := S + #13#10 + ' P' + IntToStr(I + 1) + ': ';
        {$IF Defined(CADImport6)}
          P := PtXMat(PFPoint(vSpline.Fit[I])^, FCADParams.Matrix);
        {$ELSE}
          P := FPointXMat(TFPoint(vSpline.Fit[I]), FCADParams.Matrix);
        {$IFEND}
        S := S + PointToString(P);

        //Tolik
        inc(j);
        SetLength(PolyPoints, j);

        P := ModificatePoint(P);
        SinglePoint.x := P.X;
        SinglePoint.y := P.Y;
        SinglePoint.z := P.Z;

        PolyPoints[j - 1] := SinglePoint;
        //
      end;
      i := vSpline.KnotCount;
      for i := 0 to vSpline.Knots.Count - 1 do
      begin
      end;
      ConvertToBezie := True;
    end;
    i := vSpline.ControlCount;
    if vSpline.ControlCount > 0 then
    begin
      j := 0;
      S := S + ' Control points of Spline: ';
      for I := 0 to vSpline.ControlCount - 1 do
      begin
        S := S + #13#10 + ' P' + IntToStr(I + 1) + ': ';
        {$IF Defined(CADImport6)}
          P := PtXMat(PFPoint(vSpline.Controls[I])^, FCADParams.Matrix);
        {$ELSE}
          P := FPointXMat(TFPoint(vSpline.Controls[I]), FCADParams.Matrix);
        {$IFEND}
        S := S + PointToString(P);
        //Tolik
        inc(j);
        SetLength(PolyPoints, j);

        P := ModificatePoint(P);
        SinglePoint.x := P.X;
        SinglePoint.y := P.Y;
        SinglePoint.z := P.Z;

        PolyPoints[j - 1] := SinglePoint;
        //
      end;
      S := S + #13#10;
    end;
    if S <> '' then
      TxtFile.Add(S);

    ////
    //Tolik
    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFSpline(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    if Length(PolyPoints) = 0 then
    begin
      j := 0;
      for i := 0 to vSpline.PolyPoints.Count - 1 do
      begin
        Inc(j);
        SetLength(PolyPoints, j);
        P := vSpline.PolyPoints[i];
        {$IF Defined(CADImport6)}
          P := PtXMat(PFPoint(P)^, FCADParams.Matrix);
        {$ELSE}
          P := FPointXMat(TFPoint(P), FCADParams.Matrix);
        {$IFEND}
        P := ModificatePoint(P);
        SinglePoint.x := P.X;
        SinglePoint.y := P.Y;
        SinglePoint.z := P.Z;

        PolyPoints[j - 1] := SinglePoint;
      end;
    end;

    // Check buid by PolyPoints
    if vSpline.ControlCount > 0 then
    begin
      i := vSpline.ControlCount;
      for i := 0 to vSpLine.ControlCount - 1 do
      begin
        PointFound := False;
        for j := 0 to vSpline.PolyPoints.Count - 1 do
        begin
          if IsEqualFPoints(vSpLine.ControlPoints[i], vSpline.PolyPoints[j], 0.00001) then
          begin
            PointFound := True;
            Break;
          end;
        end;
        if not PointFound then
        begin
          BuildByPolyPoints := True;
          Break;
        end;
      end;

      KnotCounts := 0;
      for i := 0 to vSpline.Knots.Count - 1 do
      begin
        KnotVal := vSpline.Knots[i];
        if (vSpline.Knots[i] < 0) or (vSpline.Knots[i] > 1) then
        begin
          ConvertToBezie := true;
          BuildByPolyPoints := False;
          break;
        end;
      end;
    end;
{
     for i := 0 to vSpline.Knots.Count - 1 do
      begin
        KnotVal := vSpline.Knots[i];
        if (vSpline.Knots[i] <= 0) or (vSpline.Knots[i] >=1) then
          Inc(KnotCounts);
      end;
      if KnotCounts = vSpline.Knots.Count then
        ConvertToBezie := true;

      if ConvertToBezie then
        BuildByPolyPoints := False;
      end;
}
    if BuildbyPolyPoints then
    begin
      SetLength(PolyPoints,0);
      SetLength(PolyPoints, vSpline.PolyPoints.Count);
      for i := 0 to vSpline.PolyPoints.Count - 1 do
      begin
        p := vSpline.PolyPoints[i];
        {$IF Defined(CADImport6)}
        P := PtXMat(PFPoint(P)^, FCADParams.Matrix);
        {$ELSE}
          P := FPointXMat(TFPoint(P), FCADParams.Matrix);
        {$IFEND}
        P := ModificatePoint(P);

        SinglePoint.x := P.X;
        SinglePoint.y := P.Y;
        SinglePoint.z := P.Z;

        PolyPoints[i] := SinglePoint;
      end;
    end;

    pLine := TPolyline.create(PolyPoints, 2, ord(psSolid), clBlack{xSpline.Color}, ord(bsClear), clBlack, 0, vSpline.Closed, Cad.GetLayerHandle(LayerNbr), mydsNormal, Cad);

    {$IF Defined(CADImport6)}
      PLine.Color := TsgDXFPolyLine(Sender).Pen.Color;
      PLine.Width := TsgDXFPolyLine(Sender).Pen.Width;
    {$ELSE}
      PLine.Color := GetColor(Sender);
      pLine.Width := RoundUp(TsgDXFPolyLine(Sender).LineWeight);
      if PLine.width < 0 then
        PLine.width := 1;
    {$IFEND}
    PLine.Style := ord(entstyle(TsgDXFPolyline(Sender)));

    if ConvertToBezie then
      pLine.ConvertToBezier;


    Result := pLine;
    //
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportSpline', E.Message);
  end;
end;  *)

function TF_Import.ImportViewPortBegin(Sender: TObject): TFigure;
var
  V: TsgDXFViewPort absolute Sender;
  S: string;
begin
  Result := nil;
  S := 'Rect:'
    + #13#10'   Left= ' + FloatToStr(V.Rect.Left)
    + #13#10'   Top= ' + FloatToStr(V.Rect.Top)
    + #13#10'   Z1= ' + FloatToStr(V.Rect.Z1)
    + #13#10'   Right= ' + FloatToStr(V.Rect.Right)
    + #13#10'   Bottom= ' + FloatToStr(V.Rect.Bottom)
    + #13#10'   Z2= ' + FloatToStr(V.Rect.Z2);
  S := S + #13#10'---ENTITIES below are displayed in this VIEWPORT---';
  TxtFile.Add(S);
  if not TsgDXFViewport(Sender).Visible then
    exit;
  ////
end;

function TF_Import.ImportViewPortEnd(Sender: TObject): TFigure;
begin
  Result := nil;
  TxtFile.Add('-----ENTITIES above are displayed in VIEWPORT-----');
end;

function ImportDXF(aFileName: string): Boolean;
var
  vFileExt: string;
  vLayer: TsgDXFLayer;
  vLayout: TsgDXFLayout;
  vEntity: TsgDXFEntity;
  i, j, k: integer;
  TXTFileName: string;
  Image1: TImage;
  Count: Integer;
  tmat: TFMatrix;
  //P1: TFPoint;
  // Tolik
  CurrViewPort: TsgDXFViewPort;
  DWGWidth, DWGHeight: Double;
  LScale, PtDisplaySize: Double;
  Left, Top, Right, Bottom: TFPoint;
  ss: string;
  F: TextFile;
  AReader: TdwgReader;
  // если нажата клавиша Shift ...
  function ShiftDown : Boolean;
  var
    State : TKeyboardState;
  begin
    GetKeyboardState(State);
    Result := ((State[vk_Shift] and 128) <> 0);
  end;


  //
begin
  Result := false;
  HandleList := TStringList.Create;
  try
    vFileExt := ExtractFileExt(LowerCase(aFileName));
    F_Import := TF_Import.Create;
    F_Import.FEntitiesCount := 0; //29.10.2012
    F_Import.FBlockCount := 0;

    // DXF
    // Tolik -- 04/01/2016  Винда позволяет любым регистром расширение написать. Будет другой регистр - хер
    // что читает (бо не находит)
    // if pos('.dxf', aFileName) <> 0 then
    if pos('.dxf', LowerCase(aFileName)) <> 0 then
    //
    begin
      {$IF Defined(CADImport6)}
        ImgDXF := TsgDXFImage.Create;
      {$ELSE}
        ImgDXF := TsgCADDXFImage.Create;
      {$IFEND}

       ImgDXF.LoadFromFile(aFileName);

//      for I := 0 to ImgDXF.LayoutsCount - 1 do
//        cbLayouts.Items.AddObject(ImgDXF.Layouts[I].Name, ImgDXF.Layouts[I]);
//      cbLayouts.ItemIndex := ImgDXF.Converter.DefaultLayoutIndex;
//      ImgDXF.CurrentLayout := ImgDXF.Layouts[cbLayouts.ItemIndex];

      //P1 := ImgDXF.Scale;
      ImgDXF.CurrentLayout := ImgDXF.Layouts[0{ImgDXF.Converter.DefaultLayoutIndex}];
      TxtFile := TStringList.Create;

      {$IF Defined(CADImport6)}
        FCADParams.Matrix := IdentityMat;
      {$ELSE}
        FCADParams.Matrix := cnstIdentityMat;
      {$IFEND}

      ImgDXF.Converter.ImportMode := imImport;
      ImgDXF.Converter.AutoInsert := True;
      ImgDXF.Converter.Params := @FCADParams;
      ImgDXF.Converter.NumberOfPartsInSpline := NumberOfPartsInSpline;

      ImgDXF.CurrentLayout.Iterate(ImgDXF.Converter, F_Import.ReadCADEntities, F_Import.FinishReadCADEntities);

      TXTFileName := ChangeFileExt(aFileName, '.txt');
      //TxtFile.SaveToFile(TXTFileName);
      //TxtFile.SaveToFile('c:\dxf.txt');
      FreeAndNil(TxtFile);
      FreeAndNil(ImgDXF);
    end;

    // DWG
    // Tolik -- 04/01/2016  Винда позволяет любым регистром расширение написать. Будет другой регистр - хер
    // что читает (бо не находит)
   // if pos('.dwg', aFileName) <> 0 then
    if pos('.dwg', LowerCase(aFileName)) <> 0 then
    //
    begin
      ImgDWG := TsgDWGImage.Create;
      ImgDWG.LoadFromFile(aFileName);

//      for I := 0 to ImgDWG.LayoutsCount - 1 do
//        cbLayouts.Items.AddObject(ImgDWG.Layouts[I].Name, ImgDWG.Layouts[I]);
//      cbLayouts.ItemIndex := ImgDWG.Converter.DefaultLayoutIndex;
//      ImgDWG.CurrentLayout := ImgDWG.Layouts[cbLayouts.ItemIndex];
      // ImgDWG.LoadPreviewFromFile(aFileName);
      ImgDWG.CurrentLayout := ImgDWG.Layouts[0{ImgDWG.Converter.DefaultLayoutIndex}];

      // -- тут пока игрушка !!!!
      //ImgDWG.CurrentLayout := ImgDWG.Layouts[1];
            ss:='';
      // для посмотреть какие типы объектов попадаются на рисунке
      for k := 0 to ImgDWG.CurrentLayout.Count - 1 do
      begin
        if Pos(TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName, ss) = 0  then
          ss := ss + (TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName) + '  ';
      end;

      AssignFile(f, 'd:\Tolik\ARC.txt');
      reset(f);
      append(f);
      writeln(f,ss);
      close(f);
      // Tolik -- 12/01/2016 --В принципе, единицы измерения в картинке есть, хз как прикрутить, т.к. описания -- хер найдешь,
      // но вот, что там сидит:
     (* case ImgDWG.Converter.HeadVarStruct.InsUnits of
        // -- 0,1,4 - основные единицы измерения (как стандарт), остальные могут попадаться довольно редко
        // и мало где описаны -- ссылка ниже смотри
        {https://knowledge.autodesk.com/support/autocad/learn-explore/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-Core/files/GUID-A58A87BB-482B-4042-A00A-EEF55A2B4FD8-htm.html}
        0: ; //  -- единицы измерения не заданы
        1: ; //ShowMessage('mm'); // миллиметры
        4: ; //ShowMessage('inch'); // дюймы
        2: ; //  Feet - футы
        3: ; //  Miles - мили
        5: ; //  Centimeters  сантиметры
        6: ; //  Meters       метры
        7: ; //  Kilometers   километры
        8: ; //  MicroInches  микродюймы
        9: ; //  Mils -- хз, сам не понял, что такое (могу предположить, что это Mil - одна тысячная дюйма)
        10: ; // Yards   ярды
        11: ; // Angstroms   Ангстремы
        12: ; // NanoMeters   нанометры
        13: ; // Microns    микроны
        14: ; // DeciMeters   дециметры
        15: ; // DekaMeters   декаметры
        16: ; // HectoMeters   гектометры
        17: ; // GigaMeters     гигаметры
        18: ; // Astronomical Units    астрономические единицы (одна АЕ = средн. расстояние от Земли до Солнца,
              // это примерно 149 598 000 км )
        19: ; // Light Years   световые года  -- это понятно
        20: ; // Parsecs      парсеки  -- (1 парсек примерно = 3,2616 светового года)
      end;
      *)
      //
      //PtDisplaySize := ImgDWG.Converter.HeadVarStruct.PointDisplaySize;
      //
      TxtFile := TStringList.Create;

      {$IF Defined(CADImport6)}
        FCADParams.Matrix := IdentityMat;
      {$ELSE}
        FCADParams.Matrix := cnstIdentityMat;
      {$IFEND}

//      FCADParams.Matrix := MatXMat(FCADParams.Matrix, StdMat(MakeFPoint(0, 0, 0), MakeFPoint(100, 100, 100)));

      ImgDWG.Converter.ImportMode := imImport;
      ImgDWG.Converter.AutoInsert := True;
      ImgDWG.Converter.Params := @FCADParams;
      ImgDWG.Converter.NumberOfPartsInSpline := NumberOfPartsInSpline;
      // Tolik
      //ImgDWG.Converter.AllArcsAsCurves := True;
      //
     (* if not ShiftDown then
        ImgDWG.CurrentLayout.Iterate(ImgDWG.Converter, F_Import.ReadCADEntities, F_Import.FinishReadCADEntities);
      else
      begin
        {
        for k := 0 to ImgDWG.CurrentLayout.Count - 1 do
        begin
          ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
          F_Import.SimpleReadCADEntities(TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]));
        end;
        }

        for k := 0 to ImgDWG.CurrentLayout.Converter.Sections[csEntities].Count - 1 do
        begin
         // ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
          F_Import.SimpleReadCADEntities(TsgDXFEntity(ImgDWG.CurrentLayout.Converter.Sections[csEntities].Entities[k]));
        end;

        for k := 0 to ImgDWG.CurrentLayout.Converter.Sections[csTables].Count - 1 do
        begin
         // ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
         for i := 0 to TsgDXFTable(ImgDWG.CurrentLayout.Converter.Sections[csTables].Entities[k]).Count - 1 do
           F_Import.SimpleReadCADEntities(TsgDXFTable(ImgDWG.CurrentLayout.Converter.Sections[csTables].Entities[k]).Entities[i]);
        end;

        for k := 0 to ImgDWG.CurrentLayout.Converter.Sections[csBlocks].Count - 1 do
        begin
         // ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
         for i := 0 to TsgDXFBlock(ImgDWG.CurrentLayout.Converter.Sections[csBlocks].Entities[k]).Count - 1 do
           F_Import.SimpleReadCADEntities(TsgDXFEntity(TsgDXFBlock(ImgDWG.CurrentLayout.Converter.Sections[csBlocks].Entities[k]).Entities[i]));
        end;

        for k := 0 to ImgDWG.CurrentLayout.Converter.Sections[csVPorts].Count - 1 do
        begin
         // ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
          for i := 0 to TsgDXFViewPort(ImgDWG.CurrentLayout.Converter.Sections[csVPorts].Entities[k]).Count - 1 do
            F_Import.SimpleReadCADEntities(TsgDXFViewPort(ImgDWG.CurrentLayout.Converter.Sections[csVPorts].Entities[k]).Entities[i]);
        end;

      end;  *)
      // Look for a ViewPort
     { CurrViewPort := nil;
      for k := 0 to ImgDWG.CurrentLayout.Count - 1 do
      begin
        ImgDWG.CurrentLayout.Converter.ViewPortCut := True;
        if (TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k])).EntType = ceViewPort then
        begin
          CurrViewPort := TsgDXFViewPort(ImgDWG.CurrentLayout.Entities[k]);
          break;
        end;
      end;  }

      {
      for k := 0 to ImgDWG.CurrentLayout.Count - 1 do
      begin
        ss := TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).ClassName + TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]).EntName;
        F_Import.SimpleReadCADEntities(TsgDXFEntity(ImgDWG.CurrentLayout.Entities[k]));
      end;
      }


      ImgDWG.CurrentLayout.Iterate(ImgDWG.Converter, F_Import.ReadCADEntities, F_Import.FinishReadCADEntities);

      TXTFileName := ChangeFileExt(aFileName, '.txt');
      TxtFile.SaveToFile(TXTFileName);
      FreeAndNil(TxtFile);
      FreeAndNil(ImgDWG);
    end;

    // SVG
    // Tolik -- 04/01/2016  Винда позволяет любым регистром расширение написать. Будет другой регистр - хер
    // что читает (бо не находит)
    // if pos('.svg', aFileName) <> 0 then
    if pos('.svg', LowerCase(aFileName)) <> 0 then
    //
    begin
      ImgSVG := TsgSVGImage.Create;
      ImgSVG.LoadFromFile(aFileName);
//      for I := 0 to ImgSVG.LayoutsCount - 1 do
//        cbLayouts.Items.AddObject(ImgSVG.Layouts[I].Name, ImgSVG.Layouts[I]);
//      cbLayouts.ItemIndex := ImgSVG.Converter.DefaultLayoutIndex;
//      ImgSVG.CurrentLayout := ImgSVG.Layouts[cbLayouts.ItemIndex];
      ImgSVG.CurrentLayout := ImgSVG.Layouts[0{ImgSVG.Converter.DefaultLayoutIndex}];
      TxtFile := TStringList.Create;

      {$IF Defined(CADImport6)}
        FCADParams.Matrix := IdentityMat;
      {$ELSE}
        FCADParams.Matrix := cnstIdentityMat;
      {$IFEND}

      ImgSVG.Converter.ImportMode := imImport;
      ImgSVG.Converter.AutoInsert := True;
      ImgSVG.Converter.Params := @FCADParams;
      ImgSVG.Converter.NumberOfPartsInSpline := NumberOfPartsInSpline;

      ImgSVG.CurrentLayout.Iterate(ImgSVG.Converter, F_Import.ReadCADEntities, F_Import.FinishReadCADEntities);
      TXTFileName := ChangeFileExt(aFileName, '.txt');
//      TxtFile.SaveToFile(TXTFileName);
      FreeAndNil(TxtFile);
      FreeAndNil(ImgSVG);
    end;

    // PRN & PLT
    // Tolik --04/12/2016
   // if (pos('.prn', aFileName) <> 0) or (pos('.plt', aFileName) <> 0) then
    if (pos('.prn', LowerCase(aFileName)) <> 0) or (pos('.plt', LowerCase(aFileName)) <> 0) then
    begin
      ImgHPGL := TsgHPGLImage.Create;
      ImgHPGL.LoadFromFile(aFileName);
//      for I := 0 to ImgHPGL.LayoutsCount - 1 do
//        cbLayouts.Items.AddObject(ImgHPGL.Layouts[I].Name, ImgHPGL.Layouts[I]);
//      cbLayouts.ItemIndex := ImgHPGL.Converter.DefaultLayoutIndex;
//      ImgHPGL.CurrentLayout := ImgHPGL.Layouts[cbLayouts.ItemIndex];
      ImgHPGL.CurrentLayout := ImgHPGL.Layouts[0{ImgHPGL.Converter.DefaultLayoutIndex}];
      TxtFile := TStringList.Create;

      {$IF Defined(CADImport6)}
        FCADParams.Matrix := IdentityMat;
      {$ELSE}
        FCADParams.Matrix := cnstIdentityMat;
      {$IFEND}

      ImgHPGL.Converter.ImportMode := imImport;
      ImgHPGL.Converter.AutoInsert := True;
      ImgHPGL.Converter.Params := @FCADParams;
      ImgHPGL.Converter.NumberOfPartsInSpline := NumberOfPartsInSpline;
      ImgHPGL.CurrentLayout.Iterate(ImgHPGL.Converter, F_Import.ReadCADEntities, F_Import.FinishReadCADEntities);
      TXTFileName := ChangeFileExt(aFileName, '.txt');
//      TxtFile.SaveToFile(TXTFileName);
      FreeAndNil(TxtFile);
      FreeAndNil(ImgHPGL);
    end;

    if F_Import.FEntitiesCount = 0 then
    begin
   //   PauseProgress(true);
      try
        MessageInfo(cImport_Mes13);
      finally
   //     PauseProgress(false);
      end;
    end
    else
      Result := true;

    FreeAndNil(F_Import);
    FreeAndNil(HandleList);
  except
    on E: Exception do AddExceptionToLogEx('ImportDXF', E.Message);
  end;
end;

function ModificatePoint(aP: TFPoint): TFPoint;
var
  CadHeight, CadWidth: double;
begin
  try
    result.X := aP.x;
    result.Y := aP.Y;
    result.Z := aP.Z;
    result.V := aP.V;
    // наша
    if ord(GCadForm.PCad.VerticalZero) = 1 then
    begin
      CadHeight := GCadForm.PCad.WorkHeight;
      result.y := CadHeight - Result.y;
    end;
    // хз
    if ord(GCadForm.PCad.HorizontalZero) = 1 then
    begin
      CadWidth := GCadForm.PCad.WorkWidth;
      result.x := CadWidth - Result.x;
    end;

  except
    on E: Exception do AddExceptionToLogEx('U_ImportDXF.ModificatePoint', E.Message);
  end;
end;

function GetImportLayerNbr(aCad: TPCDrawing; aDxfLayer: TsgDXFLayer): Integer;
var
  i: Integer;
  NewLayer: TLayer;
  s: string;
begin
  try
    Result := aCad.GetLayerNbr(utf16decode(aDxfLayer.Name));
    if Result = -1 then
    begin
      s := aDxfLayer.Name;
      NewLayer := TLayer.create(utf16decode(aDxfLayer.Name));
      NewLayer.IsDxf := True;
      aCad.Layers.Add(NewLayer);
      Result := aCad.Layers.Count - 1;
    end;
  except
    on E: Exception do AddExceptionToLogEx('U_ImportDXF.GetImportLayerNbr', E.Message);
  end;
end;    

function TF_Import.ImportHatch(Sender: TObject): TList;//TFigure;
var
  vPolygon: TsgCADPolyPolygon;
  vHatch: TsgCADHatch;
  i, j: Integer;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  P, P1, P2: TFPoint;
  points: TDoublePointArr;
  Line: TLine;
  Blk: TBlock;
  Poly: TPolyline;
  Count, vIndex: Integer;
  // Tolik
  LHBack: Integer;
  vPolygonC: TsgCADCurvePolygon;
  vList: TF2DPointList;


  Function GetLayerHandle(LayerNbr: integer): Integer;
  begin
    Result := 0;
    if (LayerNbr < Cad.LayerCount) then
    begin
      Result := Integer(Cad.Layers[LayerNbr]);
    end;
  end;

begin

  try
   //Tolik
    Result := TList.Create;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    ///

    vPolygon := nil;
    vPolygonC := nil;

    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLine(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);

    if Sender is TsgCADHatch then
      vHatch := TsgCADHatch(Sender)
    else
      vHatch := nil;

    if vHatch <> nil then
    begin
      if not vHatch.Visible then
        exit;
      Count := vHatch.ParsedLines.Count;
      if Count = 0 then
        exit;

      Blk := TBlock.Create(LHandle, Cad);
      SetLength(points, Count);
      for i := 0 to vHatch.ParsedLines.Count - 1 do
      begin
        {$IF Defined(CADImport6)}
          P.X := PFPoint(vHatch.ParsedLines[i]).X;
          P.Y := PFPoint(vHatch.ParsedLines[i]).Y;
          P.Z := 0{PFPoint(vHatch.ParsedLines[i]).Z};
          P := PtXMat(P, FCADParams.Matrix);
        {$ELSE}
          P.X := TFPoint(vHatch.ParsedLines[i]).X;
          P.Y := TFPoint(vHatch.ParsedLines[i]).Y;
          P.Z := 0{TFPoint(vHatch.ParsedLines[i]).Z};
          // Tolik -- 30/12/0215
          // P := FPointXMat(P, FCADParams.Matrix);
          //DoExtrusion(P, TsgCADHatch(Sender).Extrusion);
          P := FPointXMat(P, FCADParams.Matrix);
          //
        {$IFEND}
        P := ModificatePoint(P);
        points[i].x := P.x;
        points[i].y := P.y;
        points[i].z := P.Z;
      end;
      I := 0;
      while I < Count do
      begin
        P1.x := points[i].x;
        P1.y := points[i].y;
        P1.z := points[i].z;
        P2.x := points[i + 1].x;
        P2.y := points[i + 1].y;
        P2.z := points[i + 1].z;
        Inc(I, 2);
        Line := TLine.create(P1.X, P1.Y, P2.x, P2.y, 1, 0, 0, 0, LHandle, mydsNormal, Cad);
        Line.color := GetColor(vHatch);
        Blk.AddFigure(Line);
      end;
      //Tolik
      //Result := Blk;
      Result.Add(Blk);
    end
    else
    begin
      begin
        if not (Sender  is TsgCADCurvePolygon) then
        begin
          vPolygon := TsgCADPolyPolygon(Sender);

          if not vPolygon.Visible then
            exit;
          vIndex := 0;
          SetLength(points, vIndex);
          for i := 0 to vPolygon.Boundaries.Count - 1 do
          begin
            vList := TF2DPointList(vPolygon.Boundaries[i]);
            if vList.Count < 10000 then
            begin
              for j := 0 to vList.Count - 1 do      // prepares TPoint array for GDI
              begin
                {$IF Defined(CADImport6)}
                  P.X := PFPoint(vList[j]).X;
                  P.Y := PFPoint(vList[j]).Y;
                  P.Z := 0{PFPoint(vList[j]).Z};

                  P := PtXMat(P, FCADParams.Matrix);
                {$ELSE}
                  P.X := TF2dPoint(vList[j]).X;
                  P.Y := TF2dPoint(vList[j]).Y;
                  P.Z := 0{PFPoint(vList[j]).Z};

                  P := FPointXMat(P, FCADParams.Matrix);
                {$IFEND}
                P := ModificatePoint(P);
                inc(vIndex);
                SetLength(points, vIndex);
                points[vIndex - 1].x := P.x;
                points[vIndex - 1].y := P.y;
                points[vIndex - 1].z := P.Z;
              end;
            end;

            if Length(points) > 0 then
            begin
              Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, True, LHandle, mydsNormal, Cad);
              Poly.Color := GetColor(vPolygon);
              Result.Add(Poly);
              SetLength(points, 0);
              vIndex := 0;
            end;
          end;
        end
        else
        begin
          //Tolik
          if Result.Count = 0 then
          begin
            vIndex := 0;
            vPolygonC := TsgCADCurvePolygon(Sender);
            // Tolik -- 02/01/2016 --
            if not vPolygonC.Visible then
              Exit;
            begin
            //
              vPolygonC.Converter.DoExtents;
              for i := 0 to vPolygonc.Boundaries.Count - 1 do
              begin
                vList := TF2DPointList(vPolygonc.Boundaries[i]);
                if vList.Count < 10000 then
                begin
                  for j := 0 to vList.Count - 1 do      // prepares TPoint array for GDI
                  begin
                    {$IF Defined(CADImport6)}
                      P.X := PFPoint(vList[j]).X;
                      P.Y := PFPoint(vList[j]).Y;
                      P.Z := 0{PFPoint(vList[j]).Z};
                      P := PtXMat(P, FCADParams.Matrix);
                    {$ELSE}
                      P.X := TF2dPoint(vList[j]).X;
                      P.Y := TF2dPoint(vList[j]).Y;
                      P.Z := 0{PFPoint(vList[j]).Z};
                      //DoExtrusion(P, TsgCADCurvePolygon(Sender).Extrusion);
                      P := FPointXMat(P, FCADParams.Matrix);
                    {$IFEND}
                    P := ModificatePoint(P);
                    inc(vIndex);
                    SetLength(points, vIndex);
                    points[vIndex - 1].x := P.x;
                    points[vIndex - 1].y := P.y;
                    points[vIndex - 1].z := P.Z;
                  end;
                end;
                if Length(points) > 0 then
                begin
                  Poly := TPolyline.create(points, 1, ord(psSolid), clBlack, ord(bsClear), clBlack, 0, True, LHandle, mydsNormal, Cad);
                  Poly.Color := GetColor(vPolygonC);
                  if vPolygonC.SolidFill then
                  begin
                    vPolygonC.ColorCAD := vPolygonC.FillColor;
                    Poly.Brc := GetColor(vPolygonC);
                    Poly.Brs := ord(bsSolid);
                  end;
                  // тип заливки см здесь, например
                  // vPolygonC.HatchName = 'GRADIENT' и другие ...
                  // пока не дописано, красим все однозначно
                  Result.Add(Poly);
                  SetLength(points, 0);
                  vIndex := 0;
                end;
              end;
            end;
          end;
        end;
        //
      end;
    end;
    //Tolik
    if Length(points) > 0 then
      SetLength(points, 0);
    //
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportHatch', E.Message);
  end;  
end;

function TF_Import.ImportLeader(Sender: TObject): TFigure;
var
  P, P1, P2: TFPoint;
  S: string;
  Cad: TPCDrawing;
  LayerNbr, LHandle: Integer;
  C: Integer;
  Leader: TsgDXFLeader;
  i: integer;
  points: TDoublePointArr;
  Poly: TPolyline;
  Blk: TBlock;
  Line: TLine;
begin
  try
    Result := nil;
//  P2 := PtXMat(TsgDXFLine(Sender).Point1, FCADParams.Matrix);
    if not TsgDXFLeader(Sender).Visible then
      exit;
    if FCADParams.Insert <> nil then
      if not FCADParams.Insert.Visible then
        exit;
    //**************************************************************************//
    Cad := TPCDrawing(GCadForm.PCad);
    LayerNbr := GetImportLayerNbr(Cad, TsgDXFLeader(Sender).Layer);
    LHandle := Cad.GetLayerHandle(LayerNbr);
    Leader := TsgDXFLeader(Sender);

    Blk := TBlock.Create(LHandle, Cad);
    for i := 1 to Leader.ControlCount - 1 do
    begin
      P1.X := TFPoint(Leader.ControlPoints[i]).X;
      P1.Y := TFPoint(Leader.ControlPoints[i]).Y;
      P1.Z := TFPoint(Leader.ControlPoints[i]).Z;
      P2.X := TFPoint(Leader.ControlPoints[i - 1]).X;
      P2.Y := TFPoint(Leader.ControlPoints[i - 1]).Y;
      P2.Z := TFPoint(Leader.ControlPoints[i - 1]).Z;

      {$IF Defined(CADImport6)}
        P1 := PtXMat(P1, FCADParams.Matrix);
        P2 := PtXMat(P2, FCADParams.Matrix);
      {$ELSE}
        // Tolik -- 30/12/2015
        //P1 := FPointXMat(P1, FCADParams.Matrix);
        // DoExtrusion(P1, TsgDXFLeader(Sender).Extrusion);
        P1 := FPointXMat(P1, FCADParams.Matrix);
        // DoExtrusion(P2, TsgDXFLeader(Sender).Extrusion);
        P2 := FPointXMat(P2, FCADParams.Matrix);
        //
      {$IFEND}
      P1 := ModificatePoint(P1);
      P2 := ModificatePoint(P2);

      Line := TLine.create(P1.X, P1.Y, P2.x, P2.y, 1, 0, 0, 0, LHandle, mydsNormal, Cad);

      {$IF Defined(CADImport6)}
        Line.color := TsgDXFLine(Sender).Color;
        Line.Width := TsgDXFLine(Sender).Pen.Width;
      {$ELSE}
        Line.color := GetColor(Sender);
        Line.Width := RoundUp(TsgDXFLine(Sender).LineWeight);
        if Line.Width < 0 then
          Line.Width := 1;
      {$IFEND}

      Line.Style := ord(entstyle(TsgDXFLine(Sender)));
//      if i = 1 then
//        if Leader.Arrowhead then
//          Line.RowStyle := 1;
      Blk.AddFigure(Line);
    end;

    Result := Blk;
  except
    on E: Exception do AddExceptionToLogEx('TF_Import.ImportLeader', E.Message);
  end;
end;


end.
