Skip to content

lib

Unreal launching and project tools.

create_unreal_project(project_name, unreal_project_name, ue_version, pr_dir, engine_path, dev_mode=False, env=None)

This will create .uproject file at specified location.

As there is no way I know to create a project via command line, this is easiest option. Unreal project file is basically a JSON file. If we find the AYON_UNREAL_PLUGIN environment variable we assume this is the location of the Integration Plugin and we copy its content to the project folder and enable this plugin.

Parameters:

Name Type Description Default
project_name str

Name of the project in AYON.

required
unreal_project_name str

Name of the project in Unreal.

required
ue_version str

Unreal engine version (like 4.23).

required
pr_dir Path

Path to directory where project will be created.

required
engine_path Path

Path to Unreal Engine installation.

required
dev_mode bool

Flag to trigger C++ style Unreal project needing Visual Studio and other tools to compile plugins from sources. This will trigger automatically if Binaries directory is not found in plugin folders as this indicates this is only source distribution of the plugin. Dev mode is also set in Settings.

False
env dict

Environment to use. If not set, os.environ.

None
Throws

NotImplementedError: For unsupported platforms.

Returns:

Type Description
None

None

Deprecated

since 3.16.0

Source code in client/ayon_unreal/lib.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def create_unreal_project(project_name: str,
                          unreal_project_name: str,
                          ue_version: str,
                          pr_dir: Path,
                          engine_path: Path,
                          dev_mode: bool = False,
                          env: dict = None) -> None:
    """This will create `.uproject` file at specified location.

    As there is no way I know to create a project via command line, this is
    easiest option. Unreal project file is basically a JSON file. If we find
    the `AYON_UNREAL_PLUGIN` environment variable we assume this is the
    location of the Integration Plugin and we copy its content to the project
    folder and enable this plugin.

    Args:
        project_name (str): Name of the project in AYON.
        unreal_project_name (str): Name of the project in Unreal.
        ue_version (str): Unreal engine version (like 4.23).
        pr_dir (Path): Path to directory where project will be created.
        engine_path (Path): Path to Unreal Engine installation.
        dev_mode (bool, optional): Flag to trigger C++ style Unreal project
            needing Visual Studio and other tools to compile plugins from
            sources. This will trigger automatically if `Binaries`
            directory is not found in plugin folders as this indicates
            this is only source distribution of the plugin. Dev mode
            is also set in Settings.
        env (dict, optional): Environment to use. If not set, `os.environ`.

    Throws:
        NotImplementedError: For unsupported platforms.

    Returns:
        None

    Deprecated:
        since 3.16.0

    """

    preset = get_project_settings(project_name)["unreal"]["project_setup"]
    # get unreal engine identifier
    # -------------------------------------------------------------------------
    # FIXME (antirotor): As of 4.26 this is problem with UE4 built from
    # sources. In that case Engine ID is calculated per machine/user and not
    # from Engine files as this code then reads. This then prevents UE4
    # to directly open project as it will complain about project being
    # created in different UE4 version. When user convert such project
    # to his UE4 version, Engine ID is replaced in uproject file. If some
    # other user tries to open it, it will present him with similar error.

    # engine_path should be the location of UE_X.X folder

    ue_editor_exe: Path = get_editor_exe_path(engine_path, ue_version)
    cmdlet_project: Path = get_path_to_cmdlet_project(ue_version)

    project_file = pr_dir / f"{unreal_project_name}.uproject"

    print("--- Generating a new project ...")
    commandlet_cmd = [
        ue_editor_exe.as_posix(),
        cmdlet_project.as_posix(),
        "-run=AyonGenerateProject",
        project_file.resolve().as_posix()
    ]

    if dev_mode or preset["dev_mode"]:
        commandlet_cmd.append('-GenerateCode')

    gen_process = subprocess.Popen(commandlet_cmd,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)

    for line in gen_process.stdout:
        print(line.decode(), end='')
    gen_process.stdout.close()
    return_code = gen_process.wait()

    if return_code and return_code != 0:
        raise RuntimeError(
            (f"Failed to generate '{unreal_project_name}' project! "
             f"Exited with return code {return_code}"))

    print("--- Project has been generated successfully.")

    with open(project_file.as_posix(), mode="r+") as pf:
        pf_json = json.load(pf)
        pf_json["EngineAssociation"] = get_build_id(engine_path, ue_version)
        pf.seek(0)
        json.dump(pf_json, pf, indent=4)
        pf.truncate()
        print("--- Engine ID has been written into the project file")

    if dev_mode or preset["dev_mode"]:
        u_build_tool = get_path_to_ubt(engine_path, ue_version)

        arch = "Win64"
        if platform.system().lower() == "windows":
            arch = "Win64"
        elif platform.system().lower() == "linux":
            arch = "Linux"
        elif platform.system().lower() == "darwin":
            # we need to test this out
            arch = "Mac"

        command1 = [
            u_build_tool.as_posix(),
            "-projectfiles",
            f"-project={project_file}",
            "-progress"
        ]

        subprocess.run(command1)

        command2 = [
            u_build_tool.as_posix(),
            f"-ModuleWithSuffix={unreal_project_name},3555",
            arch,
            "Development",
            "-TargetType=Editor",
            f"-Project={project_file}",
            project_file,
            "-IgnoreJunk"
        ]

        subprocess.run(command2)

get_compatible_integration(ue_version, integration_root)

Get path to compatible version of integration plugin.

This will try to get the closest compatible versions to the one specified in sorted list.

Parameters:

Name Type Description Default
ue_version str

version of the current Unreal Engine.

required
integration_root Path

path to built-in integration plugins.

required

Returns:

Type Description
List[Path]

list of Path: Sorted list of paths closest to the specified version.

Source code in client/ayon_unreal/lib.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def get_compatible_integration(
        ue_version: str, integration_root: Path) -> List[Path]:
    """Get path to compatible version of integration plugin.

    This will try to get the closest compatible versions to the one
    specified in sorted list.

    Args:
        ue_version (str): version of the current Unreal Engine.
        integration_root (Path): path to built-in integration plugins.

    Returns:
        list of Path: Sorted list of paths closest to the specified
            version.

    """
    major, minor = ue_version.split(".")
    integration_paths = [p for p in integration_root.iterdir()
                         if p.is_dir()]

    compatible_versions = []
    for i in integration_paths:
        # parse version from path
        try:
            i_major, i_minor = re.search(
                r"(?P<major>\d+).(?P<minor>\d+)$", i.name).groups()
        except AttributeError:
            # in case there is no match, just skip to next
            continue

        # consider versions with different major so different that they
        # are incompatible
        if int(major) != int(i_major):
            continue

        compatible_versions.append(i)

    sorted(set(compatible_versions))
    return compatible_versions

get_editor_exe_path(engine_path, engine_version)

Get UE Editor executable path.

Source code in client/ayon_unreal/lib.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def get_editor_exe_path(engine_path: Path, engine_version: str) -> Path:
    """Get UE Editor executable path."""
    ue_path = engine_path / "Engine/Binaries"

    ue_name = "UnrealEditor"

    # handle older versions of Unreal Engine
    if engine_version.split(".")[0] == "4":
        ue_name = "UE4Editor"

    if platform.system().lower() == "windows":
            ue_path /= f"Win64/{ue_name}.exe"

    elif platform.system().lower() == "linux":
        ue_path /= f"Linux/{ue_name}"

    elif platform.system().lower() == "darwin":
        ue_path /= f"Mac/{ue_name}"

    return ue_path

get_engine_versions(env=None)

Detect Unreal Engine versions.

This will try to detect location and versions of installed Unreal Engine. Location can be overridden by UNREAL_ENGINE_LOCATION environment variable.

.. deprecated:: 3.15.4

Parameters:

Name Type Description Default
env dict

Environment to use.

None

Returns:

Name Type Description
OrderedDict

dictionary with version as a key and dir as value. so the highest version is first.

Example

get_engine_versions() { "4.23": "C:/Epic Games/UE_4.23", "4.24": "C:/Epic Games/UE_4.24" }

Source code in client/ayon_unreal/lib.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_engine_versions(env=None):
    """Detect Unreal Engine versions.

    This will try to detect location and versions of installed Unreal Engine.
    Location can be overridden by `UNREAL_ENGINE_LOCATION` environment
    variable.

    .. deprecated:: 3.15.4

    Args:
        env (dict, optional): Environment to use.

    Returns:
        OrderedDict: dictionary with version as a key and dir as value.
            so the highest version is first.

    Example:
        >>> get_engine_versions()
        {
            "4.23": "C:/Epic Games/UE_4.23",
            "4.24": "C:/Epic Games/UE_4.24"
        }

    """
    env = env or os.environ
    engine_locations = {}
    try:
        root, dirs, _ = next(os.walk(env["UNREAL_ENGINE_LOCATION"]))

        for directory in dirs:
            if directory.startswith("UE"):
                try:
                    ver = re.split(r"[-_]", directory)[1]
                except IndexError:
                    continue
                engine_locations[ver] = os.path.join(root, directory)
    except KeyError:
        # environment variable not set
        pass
    except OSError:
        # specified directory doesn't exist
        pass
    except StopIteration:
        # specified directory doesn't exist
        pass

    # if we've got something, terminate auto-detection process
    if engine_locations:
        return OrderedDict(sorted(engine_locations.items()))

    # else kick in platform specific detection
    if platform.system().lower() == "windows":
        return OrderedDict(sorted(_win_get_engine_versions().items()))
    if platform.system().lower() == "linux":
        # on linux, there is no installation and getting Unreal Engine involves
        # git clone. So we'll probably depend on `UNREAL_ENGINE_LOCATION`.
        pass
    if platform.system().lower() == "darwin":
        return OrderedDict(sorted(_darwin_get_engine_version().items()))

    return OrderedDict()