Jump to content

DXF

From FreeCAD Documentation
This page is a translated version of the page DXF and the translation is 40% complete.

Исторические данные

Формат обмена чертежами (DXF) - это фирменный формат данных САПР, разработанный компанией Autodesk для обеспечения обмена файлами между их флагманским продуктом AutoCAD и другим программным обеспечением. Существует ряд хороших программных библиотек для чтения/записи в формате DXF.

Существует множество версий формата DXF. Вы услышите о некоторых версиях клавиш, таких как R12 (1992 года выпуска) или R14 (1997 года выпуска, в которых были сплайны). В более поздних версиях DXF есть элементы 3D, но они редко используются или реализованы. То, как вы используете DXF для обмена данными САПР между программами, зависит в основном от ограничений и ошибок в соответствующих программах чтения/импорта и записи/экспортирования. Они редко полностью документируются и могут стать большим источником разочарования.

Если вы редактируете файлы формата DXF и хотите, чтобы они оставались практически неизменными при сохранении, мы рекомендуем вам использовать LibreCAD или QCad, поскольку внутренние структуры данных этих программ совместимы с объектами в файле формата DXF.

В FreeCAD программы чтения файлов формата DXF должны преобразовать геометрию (например, формы сплайнов) из файла формата DXF в конкретные внутренние представления Workbench.

Методы импорта DXF в FreeCAD

Если вы собираетесь часто просматривать настройки, мы рекомендуем вам перейти в меню Правка → Настройки → Импорт-экспорт → DXF и установить флажок "[ ] Показывать это диалоговое окно при импорте и экспорте".

Более подробная информация содержится на страницах Черновик DXF и Импорт FreeCAD и DXF.

Если вы используете импортированную геометрию для построения 3D-фигур в программе Part Design Workbench, попробуйте Sketcher Validate после импорта DXF в эскиз.

C++ DXF импортер

Эта реализация быстра, но пропускает функции, которые она не распознает, такие как DXF-сплайны. Она также может импортировать геометрию в Draft Workbench только в виде отдельных элементов в дереве модели. Цвета могут быть считаны из файла, если вы установите флажок, чтобы включить эту опцию. Дополнительную информацию смотрите в этом сообщении на форуме.

Python DXF импортер

Перед использованием необходимо загрузить и установить этот импортер. Используйте опцию "[ ] Разрешить FreeCAD автоматически загружать и обновлять библиотеки DXF".

Этот импортер обладает большим количеством функций (например, реализацией сплайнов) и возможностью загрузки форм в формате DXF в Sketcher Workbench. Однако имейте в виду, что все элементы эскиза будут отображаться в дереве модели по отдельности во второй раз, что может привести к путанице. Вы можете удалить все эти отдельные объекты и сохранить один эскиз (который появится вторым в списке новых элементов).

Unfortunately, the Sketcher Workbench does not implement colors, so all the geometry will appear on the same level, which is a problem if the file contains many construction lines. One work-around is to open your drawing in LibreCAD, and delete all the geometry you don't want to appear before saving a file that contains exactly the geometry that you want to load.

Макросы

Keep an eye out on the FreeCAD forum or in the Macros recipes for alternative implementations of DXF importing and cleaning up as they develop.

Сохранение DXF

In addition to the options under the Edit → Preferences, the TechDraw Workbench can also export drawing pages to DXF using the TechDraw ExportPageDXF function.


DXF terms and definitions

Anonymous blocks

When discussing DXF files, several terms are used to describe blocks that are generated automatically by the CAD software rather than by the user.

  • Anonymous block (or "Asterisk" block): This is the technical term defined by the DXF standard. It refers to any block whose name begins with an asterisk (*). It is the overarching term.
  • System block: This term describes the purpose of most anonymous blocks. They are not typically created by a user directly. Instead, the CAD application (e.g., AutoCAD) generates them automatically to represent complex objects that are composed of simpler geometric entities, such as hatches and dimensions.
  • Hidden block: This term describes the typical behavior of anonymous blocks within a CAD program's user interface. Because they are system-generated and not meant for direct user manipulation, they are usually hidden from the list of blocks that a user can insert.

Essentially, "anonymous block" is the technical name, "system block" describes its function, and "hidden block" describes its typical user interface behavior. For practical purposes in the context of the FreeCAD DXF importer, they all refer to the same category of blocks.

Classes of anonymous blocks

Anonymous blocks are further categorized based on the character that follows the initial asterisk. This prefix indicates the block's specific purpose. The most common classes are:

  • *D... (Dimensions): A block representing the graphical components of a dimension entity (lines, arrowheads, etc.).
  • *X... (Hatches): A block representing the geometry that makes up a hatch pattern.
  • *P... (Paper Space Layouts): A block that contains all the entities that exist on a specific paper space layout. The main model is typically in a block named *Model_Space, and individual layouts are named *Paper_Space, *Paper_Space0, *Paper_Space1, and so on.
  • *U... (Dynamic Blocks): These are complex blocks used for AutoCAD's dynamic block functionality.
  • *E..., *T..., etc.: Other prefixes exist for specialized objects like associative arrowheads and tables.

BLOCKs and INSERTs

The BLOCK entity

A BLOCK is a named collection of geometric entities (lines, arcs, polylines, etc.) that are grouped together to form a single object definition. It can be thought of as a template.

A BLOCK:

  • Has a name: every user-created block has a unique name (e.g., "CHAIR-01", "BOLT-M8"). This name is used to reference the block.
  • Has a base point: this is the origin point (0,0,0) within the block's own internal coordinate system. When the block is inserted, this base point is aligned with the specified insertion coordinates.
  • Is not visible by itself: the BLOCK definition is stored in a library-like section of the DXF file (the BLOCKS section). The geometry within the block does not appear in the final drawing until an instance of it is created.

The INSERT entity

An INSERT entity is what places a copy, or instance, of a BLOCK's geometry into the drawing's model space or paper space. It is a very lightweight entity because it does not contain the geometry itself; it only contains a reference to a BLOCK definition and instructions on how to place and transform it.

An INSERT:

  • References a block by name: it specifies which BLOCK definition to use (e.g., "I am an instance of block 'CHAIR-01'").
  • Has an insertion point: this is the (X, Y, Z) coordinate in the drawing where the block's base point should be placed.
  • Has transformations: each instance can be transformed independently without affecting the original block definition. These transformations include:
    • Scale: the instance can be scaled differently in the X, Y, and Z directions.
    • Rotation: the instance can be rotated around its insertion point.

BLOCK placement strategies

A DXF file separates the definition of a component from its placement.

  • A BLOCK is the template or blueprint. It contains the geometry that makes up a component, like a chair or a window. These definitions are stored in the BLOCKS section of the file and are not directly visible in the final drawing.
  • An INSERT is the instruction to place a BLOCK into the drawing at a specific position, orientation, and scale. These are the visible instances of the block and are found in the ENTITIES section.

There are two primary workflows for using blocks and inserts:

  1. Template and instance workflow: A single BLOCK definition is created, and multiple INSERT entities are used to place instances of it throughout the drawing. This is an efficient method for handling repetitive elements. For instance, the geometry for a chair is defined once in a BLOCK and then referenced many times by INSERT entities.
  2. Compound object workflow: A BLOCK is created from existing geometry simply to group those objects together as a single, selectable unit. In this case, the BLOCK definition is used by a single INSERT entity only.

The DXF importer must be able to distinguish between these two use cases to correctly represent the original drawing's intent, either by creating many linked instances to a single base object (template model) or by creating a single, visible object (grouped object model).