Compile on Windows/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "FreeCAD использует [https://en.wikipedia.org/wiki/Qt_(software) Qt] в качестве инструментария для его пользовательского...")
(Created page with "(Повторно)Запустите Qt Designer и проверьте его меню {{MenuCommand|Help → Plugins}}. Если плагин "' FreeCAD_widgets.dll"' ука...")
Line 353: Line 353:
* If you have a full Qt installation: you can choose between the folder</br>''C:\Qt\5.15.2\msvc2019_64\plugins\designer''</br>or</br>''C:\Qt\5.15.2\msvc2019_64\bin\designer'' (you must first create the ''designer'' subfolder.)</br>(adapt the paths to your installation!).
* If you have a full Qt installation: you can choose between the folder</br>''C:\Qt\5.15.2\msvc2019_64\plugins\designer''</br>or</br>''C:\Qt\5.15.2\msvc2019_64\bin\designer'' (you must first create the ''designer'' subfolder.)</br>(adapt the paths to your installation!).


(Re)Start Qt Designer and check its menu {{MenuCommand|Help → Plugins}}. If the plugin '''FreeCAD_widgets.dll''' is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must [[#Compilation|compile]] the DLL by yourself.
(Повторно)Запустите Qt Designer и проверьте его меню {{MenuCommand|Help → Plugins}}. Если плагин "' FreeCAD_widgets.dll"' указана как загружаемая, теперь вы можете создавать и изменять файлы .ui FreeCAD. Если нет, вы должны [[#Compilation|compile]] создать библиотеку DLL самостоятельно.





Revision as of 13:25, 7 August 2021

На этой странице шаг за шагом объясняется "как скомпилировать FreeCAD 0.19 или новее в Windows"". Для других платформ см.Compiling.

Требования

Для компиляции FreeCAD в Windows требуется несколько инструментов и библиотек.

Требования

  • Компилятор. FreeCAD тестируется с помощью Visual Studio (MSVC)—другие компиляторы могут работать, но инструкции по использованию здесь не включены. Более подробная информация в #Compiler, находится ниже.
  • Git (Для Git также доступны графические интерфейсы, см. Следующий раздел.)
  • CMake версия 3.11.x или более новая.
    "Подсказка:" Выбор опции Add CMake to the system PATH for all users при установке CMake сделает CMake доступным из командной строки Windows, что может быть полезно.
  • LibPack (так называемый FreeCADLibs). Это единый пакет, содержащий все библиотеки, необходимые для компиляции FreeCAD в Windows. Загрузите версию LibPack, соответствующую версии FreeCAD, которую вы хотите скомпилировать. Чтобы скомпилировать FreeCAD 0.19 или последнюю версию разработки 0.20, загрузите LibPack для 0.19/0.20 (только 64-разрядная версия). Извлеките пакет LibPack в удобное место. (Если ваш компьютер не распознает расширение .7z, вам следует установить программу 7-zip.)
    "Примечание": Настоятельно рекомендуется компилировать FreeCAD с версией компилятора, для которой предназначен LibPack. Например, вы можете столкнуться с проблемами при компиляции FreeCAD 0.19 с использованием MSVC 15, поскольку LibPack для 0.19 предназначен для сборки с MSVC 17.

Опционные программы

  • Графический интерфейс для Git. Существует несколько доступных интерфейсов, см. this list. Основное преимущество интерфейса заключается в том, что вам не нужно изучать команды Git, чтобы получить исходный код FreeCAD или отправлять исправления в репозиторий FreeCAD на GitHub.

Ниже мы опишем обработку исходного кода с использованием интерфейса TortoiseGit. Этот интерфейс интегрируется непосредственно в проводник файлов Windows и имеет большое сообщество пользователей, которые могут получить помощь в случае возникновения проблем.

  • NSIS используется для создания установщика Windows FreeCAD.

Исходный код

Теперь вы можете получить исходный код FreeCAD:

Использование интерфейса

При использовании TortoiseGit Интерфейс Git:

  1. Создайте новую папку, в которую будет загружен исходный код.
  2. Щелкните правой кнопкой мыши на этой папке в проводнике файлов Windows и выберите "'Git Clone" в контекстном меню.
  3. Появится диалоговое окно. В нем введите URL-адрес репозитория FreeCAD Git

https://github.com/FreeCAD/FreeCAD.git

и нажмите "ОК".

Последний исходный код будет загружен из репозитория FreeCAD Git, и Git будет отслеживать папку.

Использование командной строки

Чтобы создать локальную ветвь отслеживания и загрузить исходный код, откройте терминал (command prompt) и перейдите в каталог, в котором вы хотите получить исходный код, затем введите:

git clone https://github.com/FreeCAD/FreeCAD.git

Компилятор

По умолчанию (recommended) используется компилятор MS Visual Studio (MSVC). Хотя, возможно, можно использовать другие компиляторы, например gcc через Cygwin или MinGW, это не тестируется и не рассматривается здесь.

Вы можете получить бесплатную версию MSVC (для индивидуального использования), загрузив Community edition of MS Visual Studio.

Для тех, кто хочет избежать установки огромного MSVC только для того, чтобы иметь компилятор, см. CompileOnWindows - Reducing Disk Footprint.

"Примечание:" Несмотря на то, что "Community" выпуск MSVC является бесплатным, для использования среды IDE в течение более чем 30-дневного пробного периода необходимо создать учетную запись Майкрософт. Если вы будете компилировать только с помощью командной строки, вам не понадобится среда разработки и, следовательно, учетная запись Microsoft.

В качестве бесплатной и альтернативной среды разработки с открытым исходным кодом вы можете использовать KDevelop. Вы можете использовать KDevelop для изменения и написания кода на C++, но для компиляции необходимо использовать командную строку.

Дополнительная конфигурация системного пути

При необходимости вы можете включить пути к некоторым папкам в переменную системного ПУТИ. Это полезно, если вы хотите получить доступ к программам в этих папках из командной строки/powershell или если вы хотите, чтобы компилятор или CMake находили специальные программы. Кроме того, добавление папок в ПУТЬ может потребоваться, если вы не использовали соответствующие параметры при установке программы.

  • Вы можете включить папку вашего LibPack в переменную системного ПУТИ. Это полезно, если вы планируете создавать несколько конфигураций/версий FreeCAD.
  • Если вы не использовали опцию добавления CMake в ПУТЬ при его установке, добавьте папку его установки

"C:\Program Files\CMake\bin" по ПУТИ.

  • Если вы не использовали опцию добавления TortoiseGit в ПУТЬ при его установке, добавьте папку его установки

C:\Program Files\TortoiseGit\bin по ПУТИ.

Чтобы добавить пути к папкам в переменную PATH:

  1. В меню "Start" Windows щелкните правой кнопкой мыши на "Computer" и выберите "Properties".
  2. В появившемся диалоговом окне нажмите "Advanced system settings".
  3. Откроется другое диалоговое окно. Нажмите там на вкладке "Advanced" в разделе "Environment Variables".
  4. Снова откроется другое диалоговое окно. Затем выберите переменную "Path" и нажмите "Edit".
  5. И снова откроется другое диалоговое окно. Нажмите там на "New" и добавьте в путь к папке Git или LibPack.
  6. Наконец, нажмите "ОК" и закройте все диалоговые окна, также нажав "ОК".

Конфигурация

Как только у вас будут все необходимые инструменты, библиотеки и исходный код FreeCAD, вы будете готовы приступить к процессу настройки и компиляции. Этот процесс будет проходить в пять этапов:

  1. Запустите CMake один раз, чтобы проверить вашу систему и начать процесс настройки (это сообщит о том, что она не удалась).
  2. Настройте необходимые параметры CMake, чтобы установить расположение пакета LibPack и включить Qt5.
  3. Повторно запустите CMake, чтобы завершить настройку (на этот раз она должна завершиться успешно).
  4. Используйте CMake для создания системы сборки Visual Studio.
  5. Используйте Visual Studio для создания FreeCAD.

CMake

Во-первых, настройте среду сборки с помощью CMake:

  1. Откройте графический интерфейс CMake
  2. Укажите исходную папку FreeCAD.
  3. Укажите папку сборки (не используйте исходную папку-CMake создаст эту папку, если она не существует).
  4. Нажмите кнопку "Configure".
  5. В появившемся диалоговом окне укажите генератор, который вы хотите использовать: в большинстве случаев вы будете использовать значения по умолчанию в этом диалоговом окне. Для стандартной MS Visual Studio используйте "Visual Studio xx 2yyy", где xx-версия компилятора, а 2yyy-год его выпуска. Рекомендуется использовать опцию по умолчанию "Use default native compilers".

""Примечание:"" Важно указать правильный вариант бита. Если у вас есть 64-разрядный вариант LibPack, вы также должны использовать компилятор x64.

Это приведет к началу настройки и "завершится ошибкой" из-за отсутствия настроек. Это нормально, вы еще не указали местоположение пакета LibPack. Однако могут возникнуть и другие сбои, которые потребуют некоторых дальнейших действий с вашей стороны.

Если произойдет сбой с сообщением о том, что Visual Studio не найдена, поддержка CMake в MSVC еще не установлена. Для этого:

  1. Откройте среду разработки MSVC
  2. Используйте меню Tools → Get Tools и Features
  3. На вкладке "Workloads" включите "Desktop development with C++".
  4. На правой стороне теперь вы должны видеть, что будет установлен компонент "Visual C++ tools for CMake".
  5. Установите его.

Если он завершится ошибкой с сообщением о неверной версии Python или отсутствующем Python, то:

  1. Используйте поле "Search:" в CMake для поиска строки "Python".
  2. Если вы видите там путь, подобный "C:/Program Files/Python38/python.exe", CMake распознал Python, который уже установлен на вашем компьютере, но эта версия несовместима с LibPack. Поскольку LibPack включает совместимую версию Python, измените следующие параметры Python в CMake в соответствии с его путями (при условии, что LibPack находится в папке "D:\FreeCAD-build\FreeCADLibs_12.5.2_x64_VC17"):

Если нет ошибки в Visual Studio или Python, все в порядке, но CMake еще не знает всех необходимых настроек. Поэтому сейчас:

  1. Найдите в CMake переменную "FREECAD_LIBPACK_DIR" и укажите местоположение папки LibPack, которую вы загрузили ранее.
  2. Только если сборка FreeCAD 0.19, найдите переменную "'BUILD_QT5" и включите эту опцию.
  3. Нажмите "Configure" еще раз.

Теперь ошибок быть не должно. Если вы по-прежнему сталкиваетесь с ошибками, которые не можете диагностировать, посетите Install/Compile forum на веб-сайте форума FreeCAD. Если CMake прошел правильно, нажмите на кнопку "Generate". После этого вы можете закрыть CMake и начать компиляцию FreeCAD с помощью Visual Studio. Однако для первой компиляции держите его открытым на случай, если вам захочется или потребуется изменить некоторые параметры процесса сборки.

Note: When compiling FreeCAD 0.19, the CMake variable BUILD_ENABLE_CXX_STD will be set to C++14 while for FreeCAD 0.20 it will be set to C++17. This is because FreeCAD 0.20 requires at least the C++ language standard version 17. So when you compiled the last time FreeCAD 0.19 it is necessary to re-run CMake for FreeCAD 0.20 to change the C++ language standard.

Параметры процесса сборки

Система сборки CMake дает вам контроль над некоторыми аспектами процесса сборки. В частности, вы можете включать и выключать некоторые функции или модули с помощью переменных CMake.

Вот описание некоторых из этих переменных:

Variable name Description Default
BUILD_XXX Build FreeCAD with the component XXX. If you don't want/need to compile e.g. the workbench OpenSCAD, disable the variable BUILD_OPENSCAD. FreeCAD will then not have this workbench.

Note: Some components are required for other components. If you for example uncheck BUILD_ROBOT CMake will inform you that then the component Path cannot be compiled correctly. Therefore check the CMake output after you changed a BUILD_XXX option!

depends
BUILD_ENABLE_CXX_STD The version of the C++ language standard. C++14 is the highest possible for FreeCAD 0.19 while at least C++17 is required for FreeCAC 0.20. See also the note in section Building with Visual Studio 15 (2017) and 16 (2019) depends
CMAKE_INSTALL_PREFIX The output folder when building the target INSTALL, see also section Running and installing FreeCAD Windows' default program installation folder
FREECAD_COPY_DEPEND_DIRS_TO_BUILD Copies depending libraries needed to execute the FreeCAD.exe to the build folder. See also section Running and installing FreeCAD.
Note: the options FREECAD_COPY_XXX only appear if the libraries were not already copied. So when you change to another LibPack version, it is important to delete all folders in your build folder, except of the LibPack folder. In CMake delete the cache and start as if you compile for the first time and you will get the FREECAD_COPY_XXX options.
OFF
FREECAD_COPY_LIBPACK_BIN_TO_BUILD Copies the LibPack binaries needed to execute the FreeCAD.exe to the build folder. See also section Running and installing FreeCAD. OFF
FREECAD_COPY_PLUGINS_BIN_TO_BUILD Copies Qt's plugin files needed to execute the FreeCAD.exe to the build folder. See also section Running and installing FreeCAD. OFF
FREECAD_LIBPACK_USE Switch the usage of the FreeCAD LibPack on or off ON
FREECAD_LIBPACK_DIR Directory where the LibPack is FreeCAD's source code folder
FREECAD_RELEASE_PDB Create debug libraries also for release builds ON

Сборка FreeCAD

Depending on your compiler, the process for building FreeCAD will be slightly different. In the following sections you known workflows are described. If you are building with Qt Creator, jump to Building with Qt Creator, otherwise proceed directly:

Сборка в Visual Studio 15 (2017) и 16 (2019)

Сборка релиза

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Release.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build.

This will now take quite a long time.

Чтобы скомпилировать готовый к использованию FreeCAD, скомпилируйте целевую "INSTALL", см. раздел Running and installing FreeCAD.

Если вы не получили никаких ошибок, значит все готов. "Поздравляю!" Теперь вы можете выйти из MSVC или оставить его открытым.

Note: FreeCAD 0.20 requires at least the C++ language standard version 17 but the 3rd-party component flann from the LibPack is not yet ready for this. Therefore you will get compilation errors for the target ReverseEngineering. To fix this, right-click on this target in the MSVC solution explorer and select in the context menu the last entry Properties. In the appearing dialog change the C++ Language Standard to ISO C++14. Finally build the target ALL_BUILD again.

Отладочная сборка

For a debug build it is necessary that the Python is used that is included in the LibPack. To assure this:

  1. Search in the CMake GUI for "Python"
  2. If you see there a path like C:/Program Files/Python38/python.exe, CMake recognized the Python that is installed on your PC and not the one of the LibPack. In this case adapt these different Python settings in CMake to this (assuming the LibPack is in the folder D:\FreeCAD-build\FreeCADLibs_12.5.2_x64_VC17):

Now

  1. Start the Visual Studio IDE. This can either be done by pressing the button Open Project in the CMake GUI or by double-clicking on the file FreeCAD.sln that you find in your build folder.
  2. In the toolbar of the MSVC IDE assure that you use for the first compilation Debug.
  3. There is a window called Solution Explorer. It lists all possible compilation targets. To start a full compilation, right-click on the target ALL_BUILD and then choose Build in the context menu.

This will now take quite a long time. If there were no compilation errors, you can start the debug build:

  1. Right-click on the target FreeCADMain and then choose Set as Startup Project in the context menu.
  2. Finally click in the toolbar on the button with the green triangle named Local Windows Debugger.

Это запустит отладочную сборку FreeCAD, и вы сможете использовать среду разработки MSVC для ее отладки.

Видеоресурс

Учебник по английскому языку, который начинается с настройки в графическом интерфейсе CMake и продолжается командой "Build" в Visual Studio 16 2019, доступен без списка на YouTube по адресу Tutorial: Build FreeCAD from source on Windows 10.

Сборка с помощью Qt Creator (устарело)

Инсталяция и настройка Qt Creator

  • Download and install Qt Creator
  • Tools → Options → Text Editor → Behavior tab:
    • File Encodings → Default Encodings:
    • Set to: ISO-8859-1 /...csISOLatin1 (Certain characters create errors/warnings with Qt Creator if left set to UTF-8. This seems to fix it.)
  • Tools → Options → Build & Run:
    • CMake tab
      • Fill Executable box with path to cmake.exe
    • Kits tab
      • Name: MSVC 2008
      • Compiler: Microsoft Visual C++ Compiler 9.0 (x86)
      • Debugger: Auto detected...
      • Qt version: None
    • General tab
      • Uncheck: Always build project before deploying it
      • Uncheck: Always deploy project before running it

Импорт проекта и здания

  • File → Open File or Project
  • Открыть "'CMakeLists.txt"' который находится на верхнем уровне источника
  • Это запустит CMake
  • Выберите каталог сборки и нажмите кнопку Далее
  • Установите для генератора значение "NMake Generator (MSVC 2008)"'
  • Нажмите кнопку Запустить CMake. Следуйте инструкциям, приведенным выше, чтобы настроить CMake по своему вкусу.

Теперь FreeCAD можно построить

  • Build → Build All
  • Это займет много времени...

После завершения его можно запустить: В левом нижнем углу есть 2 зеленых треугольника. Один из них-отладка. Другой "run". Выбери, что тебе больше нравится.

Сборка из командной строки

The steps how to compile from the command line depends on the compiler. For MSVC 2017 the steps are:

  1. In Windows' start menu go to Visual Studio 2017 → Visual Studio Tools and choose Developer Command Prompt for VS 2017
  2. Change to your build folder.
  3. Execute the command
msbuild ALL_BUILD.vcxproj /p:Configuration=Release

или

msbuild INSTALL.vcxproj /p:Configuration=Release

Эти шаги также могут быть автоматизированы. Вот, например, решение для MSVC 2017:

  1. Скачать скрипт compile-FC.txt.
  2. Переименуйте его в "compile-FC.bat".
  3. В проводнике файлов Windows Shift+Right-click на папке сборки и используйте из контекстного меню "Command prompt here".
  4. Выполните команду
compile-FC install

Вместо вызова "'compile-FC" с опцией "install" вы также можете использовать "debug" или "release".:

debug   - компиляция FreeCAD в конфигурации отладки

"release" - компиляция FreeCAD в конфигурации выпуска

install    - скомпилируйте FreeCAD в конфигурации выпуска и создайте установку установки

Запуск и установка FreeCAD

Существует 2 метода для запуска скомпилированного FreeCAD:

"Метод 1": Вы выполняете FreeCAD.exe которые вы найдете в своей папке сборки во вложенной папке "bin"

"Метод 2": Вы создаете целевую "УСТАНОВКУ"

Метод 2 является более простым, поскольку он автоматически гарантирует, что все библиотеки, необходимые для запуска FreeCAD.exe находятся в нужной папке. В FreeCAD.exe и библиотеки будут выведены в папку, указанную вами в переменной CMake "CMAKE_INSTALL_PREFIX".

For Method 1 you need to put the libraries into the bin folder of your build folder (where the FreeCAD.exe is). This can easily be done:

  1. Open the CMake GUI.
  2. Search there for the variable option FREECAD_COPY_DEPEND_DIRS_TO_BUILD and check it. If there is no such option, the libraries were already copied, see the description of the options.
  3. Search there for the variable option FREECAD_COPY_LIBPACK_BIN_TO_BUILD and check it.
  4. Search there for the variable option FREECAD_COPY_PLUGINS_BIN_TO_BUILD and check it.
  5. Click on Configure. At the end of the configuration CMake will automatically copy the necessary libraries from the LibPack folder.

Обновление сборки

FreeCAD очень активно развивается. Поэтому его исходный код меняется почти ежедневно. Добавляются новые функции и исправляются ошибки. Чтобы извлечь выгоду из этих изменений исходного кода, вы должны перестроить свой FreeCAD. Это делается в два этапа:

  1. Обновление исходного кода
  2. Перекомпиляция

Обновление исходного кода

Использование интерфейса

When using the Git frontend TortoiseGit:

  1. Right-click on your FreeCAD source code folder in the Windows file explorer and select in the context menu Pull.
  2. A dialog will appear. Select there what development branch you want to get. master is the main branch. Therefore use this unless you want to compile a special new feature from a branch that has not yet been merged to master. (For more about Git branches, see Git development process.)

Наконец, нажмите "ОК".

Использование командной строки

Откройте терминал (командная строка) и переключитесь там в свой исходный каталог. Затем введите:

git pull https://github.com/FreeCAD/FreeCAD.git master

где "master" - название основной ветви разработки. Если вы хотите получить код из другой ветви, используйте ее имя вместо "master".

Сборник

  1. Откройте среду разработки MSVC, дважды щелкнув файл "FreeCAD.sln" или файл "ALL_BUILD.vcxproj" в папке сборки.
  2. Перейдите к шагу 2 из раздела Building with Visual Studio 15 2017.

Инструменты

Для того, чтобы включиться к разработке FreeCAD, вы должны скомпилировать и установить следующие инструменты:

Плагин Qt designer

FreeCAD использует Qt в качестве инструментария для его пользовательского интерфейса. Все диалоговые окна настраиваются в UI-файлах, которые можно редактировать с помощью программы Qt Designer, который является частью любой установки Qt, а также включен в пакет LibPack. FreeCAD имеет свой собственный набор виджетов Qt для предоставления специальных функций, таких как добавление единицы измерения в поля ввода и настройка свойств настроек.

Установка

Чтобы Qt Designer знал о виджетах FreeCAD, вы должны

  1. Download this ZIP file. (Compiled using Qt 5.12, see below.)
  2. Extract the DLL file in the ZIP and copy it
  • If you use the LibPack: to the folder
    ~\FreeCADLibs_12.5.2_x64_VC17\bin\designer
    Since there will only be a bin folder and you must first create the designer subfolder.
  • If you have a full Qt installation: you can choose between the folder
    C:\Qt\5.15.2\msvc2019_64\plugins\designer
    or
    C:\Qt\5.15.2\msvc2019_64\bin\designer (you must first create the designer subfolder.)
    (adapt the paths to your installation!).

(Повторно)Запустите Qt Designer и проверьте его меню Help → Plugins. Если плагин "' FreeCAD_widgets.dll"' указана как загружаемая, теперь вы можете создавать и изменять файлы .ui FreeCAD. Если нет, вы должны compile создать библиотеку DLL самостоятельно.


If you prefer using Qt Creator instead of Qt Designer, the DLL must be placed in this folder:
C:\Qt\Qt5.15.2\Tools\QtCreator\bin\plugins\designer
(Re)Start Qt Creator, switch to the mode Design and then check the menu Tools → Form Editor → About Qt Designer Plugins. If the plugin FreeCAD_widgets.dll is listed as being loaded, you can now design and change FreeCAD's .ui files. If not, you must compile the DLL by yourself.

Сборник

The DLL cannot be loaded as plugin if it was compiled using another Qt version than the one your Qt Designer/Qt Creator is based on. In this case you must compile the DLL by yourself. This is done the following way:

  1. Change to the FreeCAD source folder
    ~\src\Tools\plugins\widget
  2. Open a MSVC x64 command prompt using the Windows Start menu and change within it to the above folder. It is important that it is the x64 version of the MSVC command prompt!
  3. Execute this command
    qmake -t vclib plugin.pro
    
    If qmake could not be found, use the full path to it, e.g. for the LibPack it should be this one (adapt it to your installation):
    D:\FreeCAD-build\FreeCADLibs_12.5.2_x64_VC17\bin\qmake -t vclib plugin.pro
    for a full Qt installation it is
    C:\Qt\5.15.2\msvc2019_64\bin\qmake -t vclib plugin.pro
    (adapt the paths to your installation!)
  4. The call of qmake created the file FreeCAD_widgets.vcxproj in the folder ~\src\Tools\plugins\widget. Double-click on it and the MSVC IDE will open.
  5. In the toolbar of the MSVC IDE assure that you use the compilation target Release.
  6. There is a window called Solution Explorer. Right-click there on FreeCAD_widgets and then choose Build.
  7. As result you should now have a FreeCAD_widgets.dll in the folder ~\src\Tools\plugins\widget\release that you can install as plugin as described above.

Поставщик миниатюр

FreeCAD has the feature to provide preview thumbnails for *.FCStd files. That means that in the Windows file explorer *.FCStd files are shown with a screenshot of the model it contains. To provide this feature, FreeCAD needs to have the file FCStdThumbnail.dll installed to Windows.

Установка

The DLL is installed this way:

  1. Download this ZIP file and extract it.
  2. Open a Windows command prompt with administrator privileges (these privileges are a requirement).
  3. Change to the folder where the DLL is.
  4. Execute this command
    regsvr32 FCStdThumbnail.dll
    

So check if it works, assure that in FreeCAD the preferences option Save thumbnail into project file when saving document is enabled and save a model. Then view in Windows Explorer the folder of the saved model using a symbol view. You should now see a screenshot of the model in the folder view.

Сборник

To compile the FCStdThumbnail.dll

  1. Change to the FreeCAD source folder
    ~\src\Tools\thumbs\ThumbnailProvider
  2. Open the CMake GUI
  3. Specify there as source folder the one you are currently in.
  4. Use the same folder as build folder.
  5. Click Configure
  6. In the appearing dialog, specify the generator according to the one you want to use. For the standard MS Visual Studio use Visual Studio xx 2yyy where xx is the compiler version and 2yyy the year of its release. It is recommended to use the default option Use default native compilers.
    Note: It is important to specify the correct bit variant. If you have the 64bit variant of LibPack you must also use the x64 compiler.
  7. Click on Generate.
  8. You should now have the file ALL_BUILD.vcxproj in the folder ~\src\Tools\thumbs\ThumbnailProvider. Double-click on it and the MSVC IDE will open.
  9. In the toolbar of the MSVC IDE assure that you use the compilation target Release.
  10. There is a window called Solution Explorer. Right-click there on ALL_BUILD and then choose Build.
  11. As result you should now have a FCStdThumbnail.dll in the folder ~\src\Tools\thumbs\ThumbnailProvider\release that you can install as described above.


Компиляция OpenCascade

The standard Libpack comes with a version of OpenCASCADE that is suitable for general use. However, under some circumstances you may wish to compile against an alternate version of OpenCASCADE, such as one of their official releases, or a patched fork. Note that there is no guarantee that FreeCAD will work with all versions of OpenCASCADE, and using a non-Libpack version is for advanced users only. Note also that if you are using the Netgen library, it uses OpenCASCADE for some of its functionality and must be compiled against the same version of OpenCASCADE that you use when compiling FreeCAD.

The process for building a custom version of OpenCASCADE is similar to that for FreeCAD, and can make use of the FreeCAD Libpack that you have already downloaded to provide the third-party dependencies it needs (Freetype and Tcl/Tk).

First obtain the OpenCASCADE source code, either directly from the release page at OpenCASCADE.org, via git, or by cloning someone else's fork, such as the "blobfish" fork maintained by FreeCAD forum member tanderson69.

Next, use CMake to configure the build system in a similar manner to building FreeCAD. Notable CMake options for OpenCASCADE are:

  • 3RDPARTY_DIR - The location of your thrid-party libraries, typically set to your FreeCAD Libpack directory
  • INSTALL_DIR - Where to install the finished libraries. A good practice is to use an isolated directory on your system, rather than installing globally, or overwriting the Libpack's version.

Наконец, откройте проект в Visual Studio и создайте ALL_BUILD, а затем УСТАНОВИТЕ целевые объекты.

Once you have generated the appropriate DLLs for OpenCASCADE (there are many of them), you will need to rebuild FreeCAD. Open CMake and set up the source and build directories of a FreeCAD build as directed above. It is generally a good idea to use a new build directory for this alternate version of OpenCASCADE so that it is easy to switch back to your old version of FreeCAD if something goes wrong, and to set up an install directory so you can ensure the correct libraries are in place. In addition to the CMake variables discussed above, set the OpenCASCADE_DIR variable to the location of the cmake folder containing your OpenCASCADE build information. For example:

CMAKE_INSTALL_PREFIX    C:/Users/JaneDoe/Work/FreeCAD_occt751-install/
OpenCASCADE_DIR         C:/Users/JaneDoe/Work/opencascade-7.5.1-install/cmake/


После того, как вы использовали CMake для создания файлов сборки для FreeCAD, откройте его в Visual Studio, создайте его, а затем запустите сборку в целевом объекте УСТАНОВКИ.

Ссылки на литературу

Смотрите также