Code Monkey home page Code Monkey logo

ue4cmake's Introduction

discord

UE4CMake

Provides a simple way to add a cmake lib to any Unreal Engine 4 or 5 project.

It works by setting itself up as an empty plugin, this allows the .cs build files to generate an Assembly that will be included into your project through the plugin system.

Setup

Copy the contents of this repo (or git submodule it) into your UE4/5 project under Plugins/UE4CMake. The directory naming matters as some of the build script is hard coded to use the above naming (as there is no easy way to get the specific plugin directory otherwise). The .uplugin file sets up a plugin with no source, however it allows the CMakeTarget.Build.cs file to be compiled and included with your project.

In your UE4/5 project file .uproject (or if you are building a plugin it should work with your .uplugin file) add CMakeTarget as a plugin as follows

    "FileVersion": 3,
    ...
    "Plugins": [
		{
			"Name": "CMakeTarget",
			"Enabled": true
		}
	]

This generates the UE4CMake Assembly and links it with your build Assembly which will allow you to call the functions in the UE4CMake build scripts.

From there you can include any modern cmake project (older cmake may/may not have issues). Just call the static function CMakeTarget.add() with the TargetRules, ModuleRules, lib's cmake target name, location of lib and any cmake args.

public class {YourProject}:ModuleRules
{
    public {YourProject}(ReadOnlyTargetRules Target) : base(Target)
    {
        ...
        CMakeTarget.add(Target, this, "{lib's cmake target name}", "{location to cmake lib source}", "{cmake args}", {bool, use system compiler});
        ...
    }
}
  • {lib's cmake target name} - target name in the libraries CMakeLists.txt file, name provided to add_library({target name})
  • {location to cmake lib source} - directory of libraries CMakeLists.txt, it can be relative to your projects {Project}.Build.cs or an absolute path (although you should generate it from something relative like, this.ModuleDirectory).
  • {cmake args} - any cmake arguments you want to provide to the target, some information is pulled from the unreal build system like, BUILD_TYPE, INSTALL_PATH, CXX_COMPILER, and etc... but you can still override them via this argument and set any options.
  • {bool, use system compiler} - optional linux only, tells the build system to use the system compiler over the embbeded compiler in UE4/5. The embbeded compiler can be limited although it is relatively new clang version, for example even though it supports C++17 it does not include the std::filesystem library. Likely if you use this option your cmake library needs to be a shared object (.so) as static linking from a different compiler likely won't work.

Including third-party headers

For legacy reasons, Unreal Engine forces 4-byte packing on Win32. This can result in hard-to-debug alignment issues in classes that use 8-byte types such as doubles or longs. To restore the default packing around third-party code that defines 8-byte types in public structs, use the following macros:

PRAGMA_PUSH_PLATFORM_DEFAULT_PACKING
#include <thirdparty.h>
PRAGMA_POP_PLATFORM_DEFAULT_PACKING

For more info, check the Unreal Engine Docs

How it works

When your project build files are generated, CMakeTarget will create a directory in the Intermediate directory under Intermediate/CMakeTarget/{LibName}. It will generate a CMakeLists.txt file that will link to then added library directory. It will then call cmake to generate the build files for that library under build in the same Intermediate/CMakeTarget/{LibName} directory. Once the cmake generation is complete it will then use cmake to build the library and will fetch the library's include directoryes and additonal libraries required for the target. It will then automatically add those to the ModuleRules variables PublicIncludePaths and PublicAdditionalLibraries. It will also add the cmake target's CMakeLists.txt file and source files to ModuleRules.ExternalDependencies so that changes to the cmake target or it's source will outdate the UE4/5 project which will force a re-build of the cmake target. If the cmake generation or build fails it will add a non existent file to the dependencies forcing the UE4/5 build system to run cmake again on the next build. Once the cmake completes successfully the non existent file will no longer be included.

The above cmake functionality generates an output file in the Intermediate/CMakeTarget/{LibName}/Build directory buildinfo_{BuildType}.ouput, this file includes all the information that is added to the ModuleRules. This same directory includes all the cmake build information that is generated and will include cmake logs if you run into errors.

There is support to get the binary locations of the lib but is not currently setup.

Example

FastNoise2

FastNoise2Example.uproject:

Original

{
	"FileVersion": 3,
	"EngineAssociation": "4.25",
	"Category": "",
	"Description": "",
	"Modules": [
		{
			"Name": "FastNoise2Example",
			"Type": "Runtime",
			"LoadingPhase": "Default"
		}
	]
}

to

{
	"FileVersion": 3,
	"EngineAssociation": "4.25",
	"Category": "",
	"Description": "",
	"Modules": [
		{
			"Name": "FastNoise2Example",
			"Type": "Runtime",
			"LoadingPhase": "Default"
		}
	],
	"Plugins": [
		{
			"Name": "CMakeTarget",
			"Enabled": true
		}
	]
}

FastNoise2Example.Build.cs:

Original

using UnrealBuildTool;

public class FastNoise2Example : ModuleRules
{
    public FastNoise2Example(ReadOnlyTargetRules Target) : base(Target)
    {
        ...
    }
}

to

using UnrealBuildTool;

public class FastNoise2Example : ModuleRules
{
    public FastNoise2Example(ReadOnlyTargetRules Target) : base(Target)
    {
        ...
        CMakeTarget.add(Target, this, "FastNoise", Path.Combine(this.ModuleDirectory, "../Deps/FastNoise2"), "-DFASTNOISE2_NOISETOOL=OFF", true);
        ...
    }
}

ue4cmake's People

Contributors

andreacatania avatar caseymcc avatar kvarnefalk avatar salamiarmi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ue4cmake's Issues

Possibility to override the CMake configuration?

Currently the CMake build configuration uses the UE configuration, mapping all Debug-configs to the CMake Debug configuration. There may be cases where one would like to use e.g. the Release configuration of the CMake dependency while still building UE in Debug mode.

Currently, passing e.g. -DCMAKE_BUILD_TYPE=Release as a CMake argument to add() does not override the used configuration.

"The name 'CMakeTarget' does not exist" when adding to a plugin.

Hi,
I'm currently trying to add UE4CMake to a plugin I'm developing. The readme briefly states that this should be possible.

Though, when I generate the projects files I get the error
C:\Users\Lars\Documents\Unreal Projects\Test\Plugins\SenSim\Source\SenSim\SenSim.Build.cs(16,3): error CS0103: The name 'CMakeTarget' does not exist in the current context

My Build.cs file:

using UnrealBuildTool;
using System.IO;

public class SenSim : ModuleRules
{
	public SenSim(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
		
		PublicIncludePaths.AddRange(new string[] {});		
		PrivateIncludePaths.AddRange(new string[] {});
		PublicDependencyModuleNames.AddRange(new string[]{"Core",});
		PrivateDependencyModuleNames.AddRange(new string[]{"CoreUObject", "Engine", "Slate", "SlateCore", "CMakeTarget",});
		DynamicallyLoadedModuleNames.AddRange(new string[] {});

		CMakeTarget.add(Target, this, "MAVSDK", Path.Combine(this.ModuleDirectory, "../../Deps/MAVSDK"), "", true);

	}
}

Excerpt from my .uplugin file:

    "Plugins": [
		{
			"Name": "CMakeTarget",
			"Enabled": true
		}
	]

UE4CMake is in my plugins /Plugins folder.
I'm using Unreal 5.2 with this pull request.

I'm pretty inexperienced with the Unreal Build Tool, so help would be appreciated :)

Can't compile JoltPhysics in debug using this library

Hi, I'm trying to compile Jolt (a Physics Library using CMake) in unreal engine using this plugin.

When I compile the engine in Development it works, when I try to compile in debug this error appears:

Jolt.lib: Error  : LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match value '0' in SharedPCH.Engine.NonOptimized.Cpp17.h.obj
0>Jolt.lib: Error  : LNK2038: mismatch detected for 'RuntimeLibrary': value 'MDd_DynamicDebug' doesn't match value 'MD_DynamicRelease' in SharedPCH.Engine.NonOptimized.Cpp17.h.obj

Does it means that Unreal expects the Jolt Library to be compiled in release target even when Unreal is compiled in debug?

Cannot configure cmake project. Exited with code: 1

When generating my project files, ue4-cmake says it can't configure the cmake project.

I have CMakeTarget.add(Target, this, "libname", Path.Combine(ModuleDirectory, "../ThirdParty/libname"))

where "../ThirdPary/libname" is the directory to the cmake library's source.

The source is pulled from FastNoise2 with submodules included

I have added the CMakeLists.txt to the same directory as my project's build.cs

P.S. I'm not sure how credible I am when I say I get this error because I am particularly new cmake

Can't get this working in UE5.1

I've tried using this as a reference: https://github.com/caseymcc/UE4_FastNoise2
I've tried using Bing's version of ChatGPT for help.
I just can't get this working at all after 8 hours. I have lost my mind.

I've been using VS 2022 with Unreal just fine with no issues with the portable version of FastNoise but need to upgrade for performance reasons. The UE4_FastNoise2 example gives me this error:

error CS0117: 'WindowsCompiler' does not contain a definition for 'VisualStudio2017'

But I've installed the build tools for 2017 to no success.

While trying to use this (UE4CMake) project on its own without taking the other project (UE4_FastNoise2) into account, I.. will try to recap what I've done but it's been a long time under stress.

I made this Cmakelists.txt file in the root directory of my project:


cmake_minimum_required(VERSION 3.10)
project(VoxelSurvivalGame VERSION 1.0)

set(UE4_ROOT "C:/Program Files/Epic Games/UE_5.1")
set(UE4_PROJECT_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
set(UE4_PROJECT_NAME "${PROJECT_NAME}")
set(UE4_PROJECT_FILE "${UE4_PROJECT_ROOT}/${UE4_PROJECT_NAME}.uproject")
set(UE4_PROJECT_BUILD_FILE "${UE4_PROJECT_ROOT}/Source/${UE4_PROJECT_NAME}.Target.cs")
set(UE4_PROJECT_BUILD_CONFIG "Development")
set(UE4_PROJECT_BUILD_PLATFORM "Win64")
set(UE4_PROJECT_BUILD_ARGS "-rocket -progress")

include("UE4CMake/UE4CMake.cmake")

set(FASTNOISE2_ROOT "D:/Projects\Unreal/VoxelSurvivalGame/FastNoise2")
set(FASTNOISE2_INCLUDE_DIR "${FASTNOISE2_ROOT}/include")
set(FASTNOISE2_LIBRARY_DIR "${FASTNOISE2_ROOT}/lib")

add_subdirectory("${FASTNOISE2_ROOT}")

file(GLOB_RECURSE UE4_PROJECT_SOURCE_FILES "${UE4_PROJECT_ROOT}/Source/*.cpp" "${UE4_PROJECT_ROOT}/Source/*.h")
add_executable(${UE4_PROJECT_NAME} ${UE4_PROJECT_SOURCE_FILES})

target_include_directories(${UE4_PROJECT_NAME} PRIVATE ${FASTNOISE2_INCLUDE_DIR})
target_link_libraries(${UE4_PROJECT_NAME} PRIVATE FastNoise2)
target_link_libraries(${UE4_PROJECT_NAME} PRIVATE UE4)

I placed a folder named FastNoise2 in the root of my project, inside is everything from the github (cmake, include, NoiseTool, src...)

I placed a folder named Plugins inside of my root and added the CMakeTarget folder with Source, CMakeTarget.uplugin inside

In my root is a CMakeTarget.build.cs file that I didn't modify in any way

And my .uProject is:

{
	"FileVersion": 3,
	"EngineAssociation": "5.1",
	"Category": "",
	"Description": "",
	"Modules": [
		{
			"Name": "VoxelSurvivalGame",
			"Type": "Runtime",
			"LoadingPhase": "Default",
			"AdditionalDependencies": [
				"Engine"
			]
		},
		{
			"Name": "FastNoise2",
			"Type": "Runtime",
			"LoadingPhase": "Default"
		}
	],
	"Plugins": [
		{
			"Name": "CMakeTarget",
			"Type": "Runtime",
			"Enabled": true
		},
		{
			"Name": "ModelingToolsEditorMode",
			"Type": "Runtime",
			"Enabled": true,
			"TargetAllowList": [
				"Editor"
			]
		}
	]
}


Attempting to generate my project files grants me this error:

Running C:/Program Files/Epic Games/UE_5.1/Engine/Build/BatchFiles/Build.bat  -projectfiles -project="D:/Projects/Unreal/VoxelSurvivalGame/VoxelSurvivalGame.uproject" -game -rocket -progress -log="D:\Projects\Unreal\VoxelSurvivalGame/Saved/Logs/UnrealVersionSelector-2023.03.11-21.23.17.log"
Running UnrealBuildTool: dotnet "..\..\Engine\Binaries\DotNET\UnrealBuildTool\UnrealBuildTool.dll" -projectfiles -project="D:/Projects/Unreal/VoxelSurvivalGame/VoxelSurvivalGame.uproject" -game -rocket -progress -log="D:\Projects\Unreal\VoxelSurvivalGame/Saved/Logs/UnrealVersionSelector-2023.03.11-21.23.17.log"
Log file: D:\Projects\Unreal\VoxelSurvivalGame\Saved\Logs\UnrealVersionSelector-2023.03.11-21.23.17.log
Log file: C:\Users\Travi\AppData\Local\UnrealBuildTool\Log_GPF.txt
Discovering modules, targets and source code for project...
D:\Projects\Unreal\VoxelSurvivalGame\Plugins\CMakeTarget\Source\CMakeTarget.Build.cs(247,30): error CS0117: 'WindowsCompiler' does not contain a definition for 'VisualStudio2017'
D:\Projects\Unreal\VoxelSurvivalGame\Plugins\CMakeTarget\Source\CMakeTarget.Build.cs(262,41): error CS0117: 'WindowsCompiler' does not contain a definition for 'VisualStudio2017'
D:\Projects\Unreal\VoxelSurvivalGame\Plugins\CMakeTarget\Source\CMakeTarget.Build.cs(264,52): error CS0117: 'WindowsArchitecture' does not contain a definition for 'x86'
D:\Projects\Unreal\VoxelSurvivalGame\Plugins\CMakeTarget\Source\CMakeTarget.Build.cs(268,57): error CS0117: 'WindowsArchitecture' does not contain a definition for 'ARM32'
Expecting to find a type to be declared in a target rules named 'FastNoise2ExampleTarget'.  This type must derive from the 'TargetRules' type defined by Unreal Build Tool.

I'm using UE5 5.1 and don't know any other way of getting FastNoise2 working in C++ outside of this project. I'm expecting that I'm doing something wrong but there's just not enough information and attempting to learn from the example project and follow Ai instructions has left me very very much at wits end.

Oh, and I also placed, inside of the Source folder in the root directory, the Deps and FastNoise2Example folders, FastNoise2Example.Target.cs, and FastNoise2ExampleEditor.Target.cs

Take interface include directories into account for targets

It looks like currently include directories are only pulled from the INCLUDE_DIRECTORIES property of a target. One would expect that INTERFACE_INCLUDE_DIRECTORIES and possibly INTERFACE_SYSTEM_INCLUDE_DIRECTORIES should be added to the include path as well.

Possibility to add a list of targets for a targetLocation?

Currently a call to add() is needed for each added target, this in turn invokes CMake. If I want to add several targets from the same CMakeLists.txt, CMake will be invoked once for each target even though, in theory, only a single invocation should be needed.

A nice feature would be if we could support this use case of adding several targets for one location and only invoce CMake once for that location.

5.2.1 - ERROR - Does not match the generator used previously: Visual Studio 17 2022

I noticed an error which comes up for the 5.2.1 packaging steps.

UATHelper: Packaging (Linux): CMake Error: Error: generator : Unix Makefiles
UATHelper: Packaging (Linux): Does not match the generator used previously: Visual Studio 17 2022
UATHelper: Packaging (Linux): Either remove the CMakeCache.txt file and CMakeFiles directory or choose a different binary directory.

also:

PackagingResults: Error: Error: generator : Unix Makefiles
UATHelper: Packaging (Linux): Failed to create ConsoleBuf!
setActiveInputCodepage failed!Failed to create ConsoleBuf!
setActiveInputCodepage failed!
CMake Error: Error: generator : Unix MakefilesDoes not match the generator used previously: Visual Studio 17 2022
Either remove the CMakeCache.txt file and CMakeFiles directory or choose a different binary directory.
UATHelper: Packaging (Linux): Cannot configure CMake project. Exited with code: 1

How can I switch this in the main project?
Running on the Cross Compile Toolchain from the Unreal Linux Development Requirement.

Visual Studio 2022 is becoming the standard so I was wondering about switching this manually.

UE5 support?

I use vcpkg / CMake for my separate server application, and upgrading to UE5 broke UnrealGDAL (https://github.com/TensorWorks/UnrealGDAL), so I'm considering transitioning to UE_CMake instead to be able to share a gdal installation between the codebases. I have some questions:

  • How would upgrading to UE5 go? I'll be trying this myself but any guidance would be appreciated.
  • Is there anything in the way of me specifying a CMake toolchain to use (-DCMAKE_TOOLCHAIN_FILE...)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.