We work with KOMPAS 3D from DELPHI

    imageimageGreetings,% username%.
    Where fate never throws us. What only creatures of the human mind do not have to face. So I had to dig a topic regarding the Ascon Compass API.
    I did not find enough information on this topic. The zero developer is given the SDK Help and a number of examples, all bundled with the program.
    Support on the forum http://forum.ascon.ru/index.php/board,4.0.html - almost none (80% of the questions users answer for themselves).
    But the program is still quite popular (especially honestly hacked versions) , therefore questions are asked. To somehow help those who, by the will of fate (evil rock, management, or a hysterical customer), encounter this product, this article.
    Here I will lay out the "living wage", a start, starting from which you can write not the worst programs, and make money if you want, as practice has shown.

    I’ll immediately warn you that before writing under Compass, you need to have at least minimal ideas about the system (drawing, creating a model, parameterization, working with variables)

    I note right away that the information for this article was taken from different sources, I don’t remember many ... I wrote on my own ... all hints of copy-paste to ignore, except for some pieces of code, because the bike is a good thing, but personally it is more convenient for me to use ready-made ideas.

    1. Installation

    Nothing new has been invented here. By default, we install the component for Delphi. We make sure that the paths are registered.
    2. After installation

    I recommend to run (see) Demos that come in the kit.
    3. How to start Compass from our program

    (general structure, purely for example):

    Copy Source | Copy HTML
    1. uses
    2.   ActiveX, Db, IniFiles, LDefin2D,LDefin3D, ksConstTLB,
    3. {$IFDEF __LIGHT_VERSION__}
    4.   klTLB;
    5. {$ELSE}
    6.   ksTLB, CheckLst;
    7. {$ENDIF}
    8.  
    9. var kompas:KompasObject;
    10.     doc2:ksDocument2D;


    Copy Source | Copy HTML
    1. // Создать объект автоматизации KOMPAS_Graphic
    2.       if Kompas = nil then begin
    3.          {$IFDEF __LIGHT_VERSION__}
    4.          Kompas:= KompasObject( CreateOleObject('KompasLT.Application.5') );
    5.          {$ELSE}
    6.          Kompas:= KompasObject( CreateOleObject('Kompas.Application.5') );
    7.          {$ENDIF}
    8.          if Kompas <> nil then Kompas.Visible := true;
    9.       end;
    10.  
    11.       doc2:= ksDocument2D( kompas.Document2D );
    12.       if FileIsThere(FileName) then // FileName - имя шаблона+путь       
    13.          doc2.ksOpenDocument(FileName,false) // Открываем чертеж
    14.       else MessageBox(self.Handle,Pchar(FileName),'Файл не найден',MB_OK);
    15.       if doc2<>nil then begin
    16.  
    17.      //ТУТ РАБОТАЕМ С ДОКУМЕНТОМ
    18.  
    19.         doc2.ksSaveDocument(FileName1);//FileName1 - имя готового документа+путь
    20.       end;
    21.  
    22.       //Когда закончим - Kompas:=nil; 


    FileIsThere Function - Torn from help Delphi examples.

    Let me remind you that, as with any third-party applications (written by someone), whenever possible it is necessary to check all returned results.
    There are two ways to work with the Compass API: External program and built-in library. Here we will consider only the external control of the system, because the difference is not great (in the sense of the essence of interaction with Compass).

    There are examples of direct drawing in Compass in the SDK demos, but I prefer to draw manually, especially since usually the output requires variants of one product with different sizes, which means we can use templates.

    4. And so ... we work with the item

    4.1. Template preparation

    First, create a template. Let's say it will be a three-stage shaft. So far, simple (no frills).
    We draw a 3D shaft. We parameterize it. Variables L1, D1, L2, D2, D3, L3 - Lengths and Diameters of steps. Let's make them external variables. Assign Designation, Part Name and create a Specification Object. Do not forget to save. Further, based on this 3d template, we need a drawing, create it. Make sure that the dimensions are correctly aligned with the drawing elements. Save already, let's get started programming.








    4.2. Preparation of the program form

    Let's create a form, throw 6 TEdit elements on it, name them by the names of our external variables edL1 ... edD3.
    We will throw 3 buttons on the form. We’ll write them “Launch”, “Exit” and “Apply”.
    We also need TSaveDialog .
    The rest, at the request of the workers: 2 TEdit elements under the Designation and name of the part (you can not do this, but assign it programmatically).

    Variables:

    Copy Source | Copy HTML
    1. var doc: ksDocument3D;
    2.     doc2:ksDocument2D;
    3.     Kompas :KompasObject;


    The “Start” button is assigned a code:

    Copy Source | Copy HTML
    1. begin
    2.   // Создать объект автоматизации KOMPAS_Graphic
    3.   if Kompas = nil then
    4.   begin
    5. {$IFDEF __LIGHT_VERSION__}
    6.     Kompas:= KompasObject( CreateOleObject('KompasLT.Application.5') );
    7. {$ELSE}
    8.     Kompas:= KompasObject( CreateOleObject('Kompas.Application.5') );
    9. {$ENDIF}
    10.     if Kompas <> nil then
    11.       Kompas.Visible := true;
    12.   end;
    13. end;


    We assign the code to the “Exit” button:

    Copy Source | Copy HTML
    1. begin
    2.      if doc2d<>nil then doc2d:=nil;
    3.      if doc3d<>nil then doc3d:=nil;
    4.      if Kompas <> nil then begin
    5.         //принудительно закрыть
    6.         Kompas.Quit;
    7.         Kompas := nil;
    8.      end;
    9. end;


    Save the project and run it. The compass opens, the compass closes, which cannot but rejoice.

    4.3. We work with external variables 3d

    We process the input of values ​​in TEdit. We only need numbers.
    And let's start working with the "Apply" button.
    We will check for the presence of an attached compass object and the entered parameters. I will not consciously write error messages, because we have a clean demonstration, sorry for the bad manners.

    I put all the processing of the part in a separate procedure so that, if necessary, I could work with different products.
    procedure TForm2.ReBuildPart (FileName: String);
    we make the call from the handler of clicking the "Apply" button ReBuildPart ('Shaft.m3d');
    where, as everyone already guessed, 'Shaft.m3d' is the name of the file with our shaft.

    The variables we will work with:
    Copy Source | Copy HTML
    1. Var
    2.   part: ksPart; //Тут храним нашу деталь
    3.   varCol: ksVariableCollection; //Коллекция переменных детали
    4.   variable: ksVariable; //Активная переменная
    5.   i,count: integer; //Счётчики
    6.   Patch:String; //Путь до файла - шаблона


    Let's start by opening the model template file. (I have it saved in the “draw” subdirectory, for convenience)
    The procedure itself for processing external variable details:

    Copy Source | Copy HTML
    1. Begin
    2.   Patch:=ExtractFilePath(Paramstr(0))+'draw\'; //Шаблоны у меня в каталоге "draw"
    3.   if Kompas <> nil then begin
    4.     if FileIsThere(Patch+FileName) then begin
    5.       doc3d := ksDocument3D( Kompas.Document3D );
    6.       if doc3d <> nil then
    7.         doc3d.Open(Patch+FileName, false );
    8.     end else exit;
    9.   end else exit;
    10.   part := ksPart( doc3d.GetPart(pTop_Part) ); // первая деталь в сборке
    11.                                               // в нашем случае, наша деталь.
    12.   if part <> nil then begin
    13.      // работа с массивом внешних переменных
    14.      varCol := ksVariableCollection(part.VariableCollection() );
    15.      if varCol <> nil then
    16.         begin
    17.            variable := ksVariable( kompas.GetParamStruct(ko_VariableParam) );
    18.        if variable = nil then exit; //Проверим, а есть ли они?
    19.            count := varCol.GetCount(); //Количество внешних переменных
    20.            for i := 0 to count - 1 do //Пробежим по всем переменным
    21.               begin
    22.          variable := ksVariable( varCol.GetByIndex(i) );
    23.                  // Смотрим имя переменной, если наше, то присваиваем значение.
    24.                  if variable.Name='L1' then variable.Value := StrToFloat(edL1.Text);
    25.                  if variable.Name='L2' then variable.Value := StrToFloat(edL2.Text);
    26.                  if variable.Name='L3' then variable.Value := StrToFloat(edL3.Text);
    27.                  if variable.Name='D1' then variable.Value := StrToFloat(edD1.Text);
    28.                  if variable.Name='D2' then variable.Value := StrToFloat(edD2.Text);
    29.                  if variable.Name='D3' then variable.Value := StrToFloat(edD3.Text);
    30.               end;
    31.  
    32.            // Здесь вставим запонение спецификации.
    33.  
    34.            part.needRebuild:=true;
    35.            part.Update;
    36.            part.RebuildModel(); // перестроение модели детали
    37.  
    38.         end;
    39.   end;
    40.  
    41.   doc3d.treeNeedRebuild:=true;
    42.   doc3d.RebuildDocument; // перестроение модели документа
    43.  
    44.   //Перезаписываем файл.
    45.   doc3d.Save;
    46.   doc3d.close; //Опционально... не люблю, когда много всего открыто...
    47.               //Для познавательного момента, можно и закомментировать.
    48.  
    49. End;


    The questions immediately arise: “Why rebuild the model so many times?” I
    ’ll answer right away: “Sometimes it doesn’t work. That variable "does not hook", then the rest of the values ​​"will not accept". It happens ... Different consumers have different versions, from a licensed one with occasionally pop-up errors, to a broken one, sometimes working perfectly ... ”
    (This is not a call to refuse to purchase a licensed version, it’s rather a request to local distributors to try to solve problems qualitatively, albeit sometimes“ crooked ", But Customers.)

    We will try the generated code in action.

    For sim, that's all for now ... If you have the strength, desire and mood, then perhaps we will see in part two:

    4.4. We work with the specification

    4.5. We work with the name of the part

    4.6. We work with the drawing

    5. Small "workarounds." Or not always bad advice

    Also popular now: