summaryrefslogtreecommitdiffstats
path: root/pkgs/development/tools/godot/common.nix
blob: 30416a828ad9b81e32e153e9142bc643ed83691f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
310
311
312
313
314
315
316
317
318
319
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
{
  alsa-lib,
  apple-sdk_26,
  autoPatchelfHook,
  buildPackages,
  callPackage,
  darwin,
  dbus,
  dotnetCorePackages,
  embree,
  enet,
  exportTemplatesHash,
  fetchFromGitHub,
  fetchpatch,
  fontconfig,
  freetype,
  gettext,
  glib,
  glslang,
  graphite2,
  harfbuzz,
  hash,
  icu,
  installShellFiles,
  lib,
  libdecor,
  libGL,
  libjpeg_turbo,
  libpulseaudio,
  libtheora,
  libwebp,
  libx11,
  libxcursor,
  libxext,
  libxfixes,
  libxi,
  libxinerama,
  libxkbcommon,
  libxrandr,
  libxrender,
  makeWrapper,
  mbedtls,
  miniupnpc,
  moltenvk,
  openxr-loader,
  pcre2,
  perl,
  pkg-config,
  recastnavigation,
  runCommand,
  scons,
  sdl3,
  speechd-minimal,
  stdenv,
  stdenvNoCC,
  strip-nondeterminism,
  testers,
  udev,
  unzip,
  updateScript,
  version,
  vulkan-loader,
  wayland,
  wayland-scanner,
  withAlsa ? stdenv.hostPlatform.isLinux,
  withDbus ? true,
  withFontconfig ? true,
  withMono ? false,
  nugetDeps ? null,
  # only linux supports builtin_ flags properly
  withBuiltins ? !stdenv.hostPlatform.isLinux,
  withPlatform ? if stdenv.hostPlatform.isDarwin then "macos" else "linuxbsd",
  withPrecision ? "single",
  withPulseaudio ? true,
  withSpeechd ? true,
  withTouch ? true,
  withUdev ? stdenv.hostPlatform.isLinux,
  # Wayland in Godot requires X11 until upstream fix is merged
  # https://github.com/godotengine/godot/pull/73504
  withWayland ? stdenv.hostPlatform.isLinux,
  withX11 ? stdenv.hostPlatform.isLinux,
  wslay,
  zip,
  zstd,
}:
assert lib.asserts.assertOneOf "withPrecision" withPrecision [
  "single"
  "double"
];
let
  mkSconsFlagsFromAttrSet = lib.mapAttrsToList (
    k: v: if builtins.isString v then "${k}=${v}" else "${k}=${builtins.toJSON v}"
  );

  arch = stdenv.hostPlatform.linuxArch;

  dotnet-sdk = if withMono then dotnetCorePackages.sdk_8_0-source else null;
  dotnet-sdk_alt = if withMono then dotnetCorePackages.sdk_9_0-source else null;

  dottedVersion = lib.replaceStrings [ "-" ] [ "." ] version + lib.optionalString withMono ".mono";

  harfbuzz-raster = harfbuzz.override {
    withRaster = lib.versionAtLeast version "4.7";
    withCairo = lib.versionAtLeast version "4.7";
  };

  harfbuzz-icu = harfbuzz-raster.override {
    withIcu = true;
    harfbuzz = harfbuzz-raster;
  };

  mkTarget =
    target:
    let
      editor = target == "editor";
      suffix = lib.optionalString withMono "-mono" + lib.optionalString (!editor) "-template";
      binary = lib.concatStringsSep "." (
        [
          "godot"
          withPlatform
          target
        ]
        ++ lib.optional (withPrecision != "single") withPrecision
        ++ [ arch ]
        ++ lib.optional withMono "mono"
      );

      mkTests =
        pkg: dotnet-sdk:
        {
          version = testers.testVersion {
            package = pkg;
            version = dottedVersion;
          };
        }
        // lib.optionalAttrs editor (
          let
            platform =
              {
                linuxbsd = "Linux";
                macos = "macOS";
              }
              .${withPlatform};
            project-src =
              runCommand "${pkg.name}-6"
                {
                  nativeBuildInputs = [ pkg ] ++ lib.optional (dotnet-sdk != null) dotnet-sdk;
                }
                (
                  ''
                    mkdir "$out"
                    cd "$out"
                    touch project.godot

                    cat >create-scene.gd <<'EOF'
                    extends SceneTree

                    func _initialize():
                      var node = Node.new()
                      var script = ResourceLoader.load("res://test.gd")
                      node.set_script(script)
                  ''
                  + lib.optionalString withMono ''
                    ${""}
                      var monoNode = Node.new()
                      var monoScript = ResourceLoader.load("res://Test.cs")
                      monoNode.set_script(monoScript)
                      node.add_child(monoNode)
                      monoNode.owner = node
                  ''
                  + ''
                    ${""}
                      var scene = PackedScene.new()
                      var scenePath = "res://test.tscn"
                      scene.pack(node)
                      node.free()
                      var x = ResourceSaver.save(scene, scenePath)
                      ProjectSettings["application/run/main_scene"] = scenePath
                  ''
                  + lib.optionalString stdenv.hostPlatform.isDarwin ''
                    ${""}
                      ProjectSettings["rendering/textures/vram_compression/import_etc2_astc"] = true
                  ''
                  + ''
                      ProjectSettings.save()
                      quit()
                    EOF

                    cat >test.gd <<'EOF'
                    extends Node
                    func _ready():
                      print("Hello, World!")
                      get_tree().quit()
                    EOF

                    cat >export_presets.cfg <<'EOF'
                    [preset.0]
                    name="build"
                    platform="${platform}"
                    runnable=true
                    export_filter="all_resources"
                    include_filter=""
                    exclude_filter=""
                    [preset.0.options]
                    binary_format/architecture="${if stdenv.hostPlatform.isDarwin then "universal" else arch}"
                  ''
                  + lib.optionalString stdenv.hostPlatform.isDarwin ''
                    application/bundle_identifier="test"
                  ''
                  + ''
                    EOF
                  ''
                  + lib.optionalString withMono ''
                    cat >Test.cs <<'EOF'
                    using Godot;
                    using System;

                    public partial class Test : Node
                    {
                      public override void _Ready()
                      {
                        GD.Print("Hello, Mono!");
                        GetTree().Quit();
                      }
                    }
                    EOF

                    sdk_version=$(basename ${pkg}/share/nuget/packages/godot.net.sdk/*)
                    cat >UnnamedProject.csproj <<EOF
                    <Project Sdk="Godot.NET.Sdk/$sdk_version">
                      <PropertyGroup>
                        <TargetFramework>net${lib.versions.majorMinor (lib.defaultTo pkg.dotnet-sdk dotnet-sdk).version}</TargetFramework>
                        <EnableDynamicLoading>true</EnableDynamicLoading>
                      </PropertyGroup>
                    </Project>
                    EOF

                    configureNuget

                    dotnet new sln -n UnnamedProject
                    message=$(dotnet sln add UnnamedProject.csproj)
                    echo "$message"
                    # dotnet sln doesn't return an error when it fails to add the project
                    [[ $message == "Project \`UnnamedProject.csproj\` added to the solution." ]]

                    rm nuget.config
                  ''
                );

            export-tests = lib.makeExtensible (final: {
              inherit (pkg) export-template;

              export = stdenvNoCC.mkDerivation {
                name = "${final.export-template.name}-export";

                nativeBuildInputs = [ pkg ] ++ lib.optional (dotnet-sdk != null) dotnet-sdk;

                src = project-src;

                buildPhase = ''
                  runHook preBuild

                  export HOME=$(mktemp -d)
                  local dataDir="$HOME/${
                    if stdenv.hostPlatform.isDarwin then "Library/Application Support/Godot" else ".local/share/godot"
                  }/"
                  mkdir -p "$dataDir"
                  ln -s "${final.export-template}"/share/godot/export_templates "$dataDir"

                  godot${suffix} --headless --build-solutions -s create-scene.gd

                  runHook postBuild
                '';

                installPhase = ''
                  runHook preInstall

                  mkdir -p "$out"/bin
                  godot${suffix} --headless --export-release build "$out"/bin/test${lib.optionalString stdenv.hostPlatform.isDarwin ".app"}

                  runHook postInstall
                '';
              };

              run = runCommand "${final.export.name}-runs" { passthru = { inherit (final) export; }; } (
                ''
                  (
                    set -eo pipefail
                    HOME=$(mktemp -d)
                    "${final.export}"/bin/test${lib.optionalString stdenv.hostPlatform.isDarwin ".app/Contents/MacOS/Unnamed"} --headless | tail -n+3 | (
                ''
                + lib.optionalString withMono ''
                  # indent
                      read output
                      if [[ "$output" != "Hello, Mono!" ]]; then
                        echo "unexpected output: $output" >&2
                        exit 1
                      fi
                ''
                + ''
                      read output
                      if [[ "$output" != "Hello, World!" ]]; then
                        echo "unexpected output: $output" >&2
                        exit 1
                      fi
                    )
                    touch "$out"
                  )
                ''
              );
            });

          in
          {
            export-runs = export-tests.run;

            export-bin-runs =
              (export-tests.extend (
                final: prev: {
                  export-template = pkg.export-templates-bin;

                  export = prev.export.overrideAttrs (prev: {
                    nativeBuildInputs =
                      prev.nativeBuildInputs or [ ] ++ lib.optional stdenv.hostPlatform.isElf autoPatchelfHook;

                    # stripping dlls results in:
                    # Failed to load System.Private.CoreLib.dll (error code 0x8007000B)
                    stripExclude = lib.optionals withMono [ "*.dll" ];

                    runtimeDependencies =
                      prev.runtimeDependencies or [ ]
                      ++ map lib.getLib [
                        libpulseaudio
                        libx11
                        libxcursor
                        libxext
                        libxi
                        libxrandr
                        vulkan-loader
                      ]
                      ++ lib.optionals stdenv.hostPlatform.isLinux [
                        alsa-lib
                        udev
                      ];
                  });
                }
              )).run;
          }
        );

      attrs = finalAttrs: {
        __structuredAttrs = true;

        pname = "godot${suffix}";
        inherit version;

        src = fetchFromGitHub {
          owner = "godotengine";
          repo = "godot";
          tag = version;
          inherit hash;
          # Required for the commit hash to be included in the version number.
          #
          # `methods.py` reads the commit hash from `.git/HEAD` and manually follows
          # refs.
          #
          # See also 'hash' in
          # https://docs.godotengine.org/en/stable/classes/class_engine.html#class-engine-method-get-version-info
          leaveDotGit = true;
          # Only keep HEAD, because leaveDotGit is non-deterministic:
          # https://github.com/NixOS/nixpkgs/issues/8567
          postFetch = ''
            hash=$(git -C "$out" rev-parse HEAD)
            rm -r "$out"/.git
            mkdir "$out"/.git
            echo "$hash" > "$out"/.git/HEAD
          '';
        };

        outputs = [
          "out"
        ]
        ++ lib.optional editor "man";
        separateDebugInfo = true;

        env = {
          # Set the build name which is part of the version. In official downloads, this
          # is set to 'official'. When not specified explicitly, it is set to
          # 'custom_build'. Other platforms packaging Godot (Gentoo, Arch, Flatpack
          # etc.) usually set this to their name as well.
          #
          # See also 'methods.py' in the Godot repo and 'build' in
          # https://docs.godotengine.org/en/stable/classes/class_engine.html#class-engine-method-get-version-info
          BUILD_NAME = "nixpkgs";
        }
        // lib.optionalAttrs stdenv.hostPlatform.isDarwin {
          NIX_CFLAGS_COMPILE = toString [
            "-I${lib.getDev harfbuzz-icu}/include/harfbuzz"
            "-I${lib.getDev recastnavigation}/include/recastnavigation"
          ];
        };

        preConfigure = lib.optionalString (editor && withMono) ''
          # TODO: avoid pulling in dependencies of windows-only project
          dotnet sln modules/mono/editor/GodotTools/GodotTools.sln \
            remove modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj

          dotnet restore modules/mono/glue/GodotSharp/GodotSharp.sln
          dotnet restore modules/mono/editor/GodotTools/GodotTools.sln
          dotnet restore modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
        '';

        # Godot 4.7 with system HarfBuzz needs explicit raster linkage, but should be resolved with 4.7.1.
        # See https://github.com/godotengine/godot/pull/120568
        preBuild =
          lib.optionalString (!withBuiltins && lib.versionAtLeast version "4.7") ''
            export NIX_LDFLAGS="$NIX_LDFLAGS -lharfbuzz-raster"
          ''
          # darwin needs $HOME/.cache/clang/ModuleCache.
          + lib.optionalString stdenv.hostPlatform.isDarwin ''
            export HOME=$(mktemp -d)
          '';

        # From: https://github.com/godotengine/godot/blob/4.2.2-stable/SConstruct
        sconsFlags = mkSconsFlagsFromAttrSet (
          {
            # Options from 'SConstruct'
            precision = withPrecision; # Floating-point precision level
            production = true; # Set defaults to build Godot for use in production
            platform = withPlatform;
            inherit target;
            debug_symbols = true;

            # Options from 'platform/linuxbsd/detect.py'
            alsa = withAlsa;
            dbus = withDbus; # Use D-Bus to handle screensaver and portal desktop settings
            fontconfig = withFontconfig; # Use fontconfig for system fonts support
            pulseaudio = withPulseaudio; # Use PulseAudio
            speechd = withSpeechd; # Use Speech Dispatcher for Text-to-Speech support
            touch = withTouch; # Enable touch events
            udev = withUdev; # Use udev for gamepad connection callbacks
            wayland = withWayland; # Compile with Wayland support
            x11 = withX11; # Compile with X11 support

            module_mono_enabled = withMono;

            # aliasing bugs exist with hardening+LTO
            # https://github.com/godotengine/godot/pull/104501
            ccflags = "-fno-strict-aliasing";
            # on darwin: ld: unknown option: --build-id
            linkflags = lib.optionalString (!stdenv.hostPlatform.isDarwin) "-Wl,--build-id";

            # libraries that aren't available in nixpkgs
            builtin_msdfgen = true;
            builtin_rvo2_2d = true;
            builtin_rvo2_3d = true;
            builtin_xatlas = true;

            # using system clipper2 is currently not implemented
            builtin_clipper2 = true;

            use_sowrap = false;
          }
          // lib.optionalAttrs (lib.versionOlder version "4.4") {
            # libraries that aren't available in nixpkgs
            builtin_squish = true;

            # broken with system packages
            builtin_miniupnpc = true;
          }
          // lib.optionalAttrs (lib.versionAtLeast version "4.5") {
            redirect_build_objects = false; # Avoid copying build objects to output
          }
          # see postBuild
          // lib.optionalAttrs (stdenv.hostPlatform.isDarwin && !(editor && withMono)) {
            generate_bundle = "yes";
          }
        );

        enableParallelBuilding = true;

        strictDeps = true;

        propagatedSandboxProfile = lib.optionalString stdenv.hostPlatform.isDarwin ''
          (allow file-read* (subpath "/System/Library/CoreServices/SystemAppearance.bundle"))
        '';

        patches =
          lib.optionals (lib.versionOlder version "4.6") [
            ./Linux-fix-missing-library-with-builtin_glslang-false.patch
          ]
          ++ lib.optionals (lib.versionOlder version "4.4") [
            (fetchpatch {
              name = "wayland-header-fix.patch";
              url = "https://github.com/godotengine/godot/commit/6ce71f0fb0a091cffb6adb4af8ab3f716ad8930b.patch";
              hash = "sha256-hgAtAtCghF5InyGLdE9M+9PjPS1BWXWGKgIAyeuqkoU=";
            })
            (fetchpatch {
              name = "thorvg-header-fix.patch";
              url = "https://github.com/godotengine/godot/commit/1823460787a6c1bb8e4eaf21ac2a3f90d24d5ee0.patch";
              hash = "sha256-PcHEMXd0v2c3j6Eitxt5uWi6cD+OmsBAn3TNMNRNPog=";
            })
            # Fix a crash in the mono test project build. It no longer seems to
            # happen in 4.4, but an existing fix couldn't be identified.
            ./CSharpLanguage-fix-crash-in-reload_assemblies-after-.patch
          ]
          ++ lib.optional (
            stdenv.hostPlatform.isDarwin && lib.versionAtLeast version "4.4"
          ) ./fix-moltenvk-detection.patch;

        postPatch = ''
          # this stops scons from hiding e.g. NIX_CFLAGS_COMPILE
          perl -pi -e '{ $r += s:(env = Environment\(.*):\1\nenv["ENV"] = os.environ: } END { exit ($r != 1) }' SConstruct

        ''
        + lib.optionalString (!withBuiltins) ''
          # disable all builtin libraries by default
          perl -pi -e '{ $r |= s:(opts.Add\(BoolVariable\("builtin_.*, )True(\)\)):\1False\2: } END { exit ($r != 1) }' SConstruct

        ''
        + lib.optionalString (lib.versionOlder version "4.6") ''
          substituteInPlace platform/linuxbsd/detect.py \
            --replace-fail /usr/include/recastnavigation ${lib.escapeShellArg (lib.getDev recastnavigation)}/include/recastnavigation
        ''
        + lib.optionalString (libGL != null) ''
          substituteInPlace thirdparty/glad/egl.c \
            --replace-fail \
              'static const char *NAMES[] = {"libEGL.so.1", "libEGL.so"}' \
              'static const char *NAMES[] = {"${lib.getLib libGL}/lib/libEGL.so"}'

          substituteInPlace thirdparty/glad/gl.c \
            --replace-fail \
              'static const char *NAMES[] = {"libGLESv2.so.2", "libGLESv2.so"}' \
              'static const char *NAMES[] = {"${lib.getLib libGL}/lib/libGLESv2.so"}' \

          substituteInPlace thirdparty/glad/gl{,x}.c \
            --replace-fail \
              '"libGL.so.1"' \
              '"${lib.getLib libGL}/lib/libGL.so"'
        ''
        + ''
          substituteInPlace thirdparty/volk/volk.c \
            --replace-fail \
              'dlopen("libvulkan.so.1"' \
              'dlopen("${lib.getLib vulkan-loader}/lib/libvulkan.so"'
        ''
        + lib.optionalString stdenv.hostPlatform.isDarwin (
          ''
            substituteInPlace platform/macos/export/export_plugin.cpp \
              --replace-fail \
                /usr/bin/codesign \
                '${lib.getExe' darwin.sigtool "sigtool"}'
          ''
          # https://github.com/godotengine/godot/issues/107199
          + lib.optionalString (lib.versionAtLeast version "4.5") ''
            substituteInPlace drivers/metal/SCsub \
              --replace-fail \
                'env_metal.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])' \
                ""
          ''
          # godot zips these files and fails if mtime < 1980
          + lib.optionalString (!editor) ''
            find misc/dist/macos_template.app -exec touch {} \;
          ''
        );

        depsBuildBuild = lib.optionals (stdenv.buildPlatform != stdenv.hostPlatform) [
          buildPackages.stdenv.cc
          pkg-config
        ];

        buildInputs =
          lib.optionals (!withBuiltins) (
            [
              embree
              enet
              freetype
              glslang
              graphite2
              harfbuzz-icu
              icu
              libtheora
              libwebp
              mbedtls
              miniupnpc
              openxr-loader
              pcre2
              recastnavigation
              wslay
              zstd
            ]
            ++ lib.optionals (lib.versionAtLeast version "4.5") [
              libjpeg_turbo
              sdl3
            ]
          )
          ++ lib.optionals (editor && withMono) dotnet-sdk.packages
          ++ lib.optional withAlsa alsa-lib
          ++ lib.optional (withX11 || withWayland) libxkbcommon
          ++ lib.optionals withX11 [
            libx11
            libxcursor
            libxext
            libxfixes
            libxi
            libxinerama
            libxrandr
            libxrender
          ]
          ++ lib.optionals withWayland [
            libdecor
            wayland
          ]
          ++ lib.optionals withDbus [
            dbus
          ]
          ++ lib.optionals withFontconfig [
            fontconfig
          ]
          ++ lib.optional withPulseaudio libpulseaudio
          ++ lib.optionals withSpeechd [
            speechd-minimal
            glib
          ]
          ++ lib.optional withUdev udev
          ++ lib.optionals stdenv.hostPlatform.isDarwin [
            apple-sdk_26
            moltenvk
          ];

        nativeBuildInputs = [
          gettext
          installShellFiles
          perl
          pkg-config
          scons
        ]
        ++ lib.optionals withWayland [ wayland-scanner ]
        ++ lib.optionals (editor && withMono) [
          makeWrapper
          dotnet-sdk
        ]
        ++ lib.optionals stdenv.hostPlatform.isDarwin (
          [
            darwin.sigtool
          ]
          ++ lib.optionals (!editor) [
            strip-nondeterminism
            unzip
            zip
          ]
        );

        postBuild = lib.optionalString (editor && withMono) (
          ''
            echo "Generating Glue"
            bin/${binary} --headless --generate-mono-glue modules/mono/glue
            echo "Building C#/.NET Assemblies"
            python modules/mono/build_scripts/build_assemblies.py --godot-output-dir bin --precision=${withPrecision}
          ''
          # when building the mono editor, we need to build the assemblies
          # before generating the bundle
          + lib.optionalString stdenv.hostPlatform.isDarwin ''
            scons "''${sconsFlags[@]}" generate_bundle=yes
          ''
        );

        installPhase = ''
          runHook preInstall

          mkdir -p "$out"/{bin,libexec}
          cp -r bin/${binary} "$out"/libexec/

          cd "$out"/bin
          ln -s ../libexec/${binary} godot${lib.versions.majorMinor version}${suffix}
          ln -s godot${lib.versions.majorMinor version}${suffix} godot${lib.versions.major version}${suffix}
          ln -s godot${lib.versions.major version}${suffix} godot${suffix}
          cd -
        ''
        + (
          if editor then
            ''
              installManPage misc/dist/linux/godot.6

              mkdir -p "$out"/share/{applications,icons/hicolor/scalable/apps}
              cp misc/dist/linux/org.godotengine.Godot.desktop \
                "$out/share/applications/org.godotengine.Godot${lib.versions.majorMinor version}${suffix}.desktop"

              substituteInPlace "$out/share/applications/org.godotengine.Godot${lib.versions.majorMinor version}${suffix}.desktop" \
                --replace-fail "Exec=godot" "Exec=$out/bin/godot${suffix}" \
                --replace-fail "Godot Engine" "Godot Engine ${
                  lib.versions.majorMinor version + lib.optionalString withMono " (Mono)"
                }"
              ${
                if lib.versionOlder version "4.7" then
                  ''
                    cp icon.svg "$out/share/icons/hicolor/scalable/apps/godot.svg"
                    cp icon.png "$out/share/icons/godot.png"
                  ''
                else
                  ''
                    cp misc/logo/icon.svg "$out/share/icons/hicolor/scalable/apps/godot.svg"
                    cp misc/logo/icon.png "$out/share/icons/godot.png"
                  ''
              }
            ''
            + lib.optionalString withMono ''
              cp -r bin/GodotSharp "$out"/libexec/
              mkdir -p "$out"/share/nuget
              mv "$out"/libexec/GodotSharp/Tools/nupkgs "$out"/share/nuget/source

              wrapProgram "$out"/libexec/${binary} \
                --prefix NUGET_FALLBACK_PACKAGES ';' "$out"/share/nuget/packages/
            ''
            + lib.optionalString stdenv.hostPlatform.isDarwin ''
              mkdir -p "$out"/Applications
              cp -r bin/godot_macos_editor${lib.optionalString withMono "_mono"}.app "$out"/Applications/GodotMono.app
            ''
          else
            let
              template =
                (lib.replaceStrings
                  [ "template" ]
                  [
                    {
                      linuxbsd = "linux";
                      macos = "macos";
                    }
                    .${withPlatform}
                  ]
                  target
                )
                + "."
                + arch;
            in
            ''
              templates="$out"/share/godot/export_templates/${dottedVersion}
              mkdir -p "$templates"
              ln -s "$out"/libexec/${binary} "$templates"/${template}
            ''
            # TODO: teach godot to use a template that isn't zipped. for now we
            # just need to make it uncompressed so it doesn't break dependencies
            + lib.optionalString stdenv.hostPlatform.isDarwin ''
              cd bin
              unzip godot_macos${lib.optionalString withMono "_mono"}.zip
              zip -rq0 "$templates"/macos.zip macos_template.app
              strip-nondeterminism --type zip "$templates"/macos.zip
              cd -
            ''
        )
        + ''
          runHook postInstall
        '';

        passthru = {
          inherit updateScript;
          tests =
            mkTests finalAttrs.finalPackage dotnet-sdk
            // lib.optionalAttrs (editor && withMono) {
              sdk-override = mkTests finalAttrs.finalPackage dotnet-sdk_alt;
            };
        }
        // lib.optionalAttrs editor {
          export-template = mkTarget "template_release";
          export-templates-bin = (
            callPackage ./export-templates-bin.nix {
              inherit version withMono;
              godot = finalAttrs.finalPackage;
              hash = exportTemplatesHash;
            }
          );
        };

        requiredSystemFeatures = [
          # fixes: No space left on device
          "big-parallel"
        ];

        meta = {
          changelog = "https://github.com/godotengine/godot/releases/tag/${version}";
          description = "Free and Open Source 2D and 3D game engine";
          homepage = "https://godotengine.org";
          license = lib.licenses.mit;
          platforms = [
            "x86_64-linux"
            "aarch64-linux"
          ]
          ++ lib.optional (!withMono) "i686-linux"
          # 4.3 doesn't compile on darwin, and 4.4 doesn't pass tests
          ++ lib.optionals (lib.versionAtLeast version "4.5") [
            "aarch64-darwin"
          ];
          maintainers = with lib.maintainers; [
            corngood
            shiryel
          ];
          mainProgram = "godot${suffix}";
        };
      };

      unwrapped = stdenv.mkDerivation (
        if (editor && withMono) then
          dotnetCorePackages.addNuGetDeps {
            inherit nugetDeps;
            overrideFetchAttrs = old: rec {
              runtimeIds = map (system: dotnetCorePackages.systemToDotnetRid system) old.meta.platforms;
              buildInputs =
                old.buildInputs
                ++ lib.concatLists (lib.attrValues (lib.getAttrs runtimeIds dotnet-sdk.targetPackages));
            };
          } attrs
        else
          attrs
      );

      wrapper =
        if (editor && withMono) then
          stdenv.mkDerivation (finalAttrs: {
            __structuredAttrs = true;

            pname = finalAttrs.unwrapped.pname + "-wrapper";
            inherit (finalAttrs.unwrapped) version outputs meta;
            inherit unwrapped dotnet-sdk;

            dontUnpack = true;
            dontConfigure = true;
            dontBuild = true;

            nativeBuildInputs = [ makeWrapper ];
            strictDeps = true;

            installPhase = ''
              runHook preInstall

              mkdir -p "$out"/{bin,libexec,share/applications,nix-support}

              cp -d "$unwrapped"/bin/* "$out"/bin/
              ln -s "$unwrapped"/libexec/* "$out"/libexec/
              ln -s "$unwrapped"/share/nuget "$out"/share/
              cp "$unwrapped/share/applications/org.godotengine.Godot${lib.versions.majorMinor version}${suffix}.desktop" \
                "$out/share/applications/org.godotengine.Godot${lib.versions.majorMinor version}${suffix}.desktop"

              substituteInPlace "$out/share/applications/org.godotengine.Godot${lib.versions.majorMinor version}${suffix}.desktop" \
                --replace-fail "Exec=$unwrapped/bin/godot${suffix}" "Exec=$out/bin/godot${suffix}"
              ln -s "$unwrapped"/share/icons $out/share/

              # ensure dotnet hooks get run
              echo "${finalAttrs.dotnet-sdk}" >> "$out"/nix-support/propagated-build-inputs

              wrapProgram "$out"/libexec/${binary} \
                --prefix PATH : "${lib.makeBinPath [ finalAttrs.dotnet-sdk ]}"

              runHook postInstall
            '';

            postFixup = lib.concatMapStringsSep "\n" (output: ''
              [[ -e "''$${output}" ]] || ln -s "${unwrapped.${output}}" "''$${output}"
            '') finalAttrs.unwrapped.outputs;

            passthru = unwrapped.passthru // {
              tests = mkTests finalAttrs.finalPackage null // {
                unwrapped = lib.recurseIntoAttrs unwrapped.tests;
                sdk-override = lib.recurseIntoAttrs (
                  mkTests (finalAttrs.finalPackage.overrideAttrs { dotnet-sdk = dotnet-sdk_alt; }) null
                );
              };
            };
          })
        else
          unwrapped;
    in
    wrapper;
in
mkTarget "editor"