Commit graph

340 commits

Author SHA1 Message Date
Raul Santos
a1f454fee3
C#: Add global class support
Co-authored-by: willnationsdev <willnationsdev@gmail.com>
2023-05-29 19:04:02 +02:00
Yuri Sizov
156a2fabea
Merge pull request #76659 from shana/shana/75152-fix-crash-when-initializing-glue-generation
Skip initializing the C# runtime when generating glue bindings
2023-05-19 17:10:40 +02:00
Andreia Gaita
e56fdc8a9a Skip initializing the C# runtime when generating glue bindings
The bindings generator doesn't require the C# runtime in order to generate
the glue, and when it the glue generation runs, it exits immediately
afterwards, so we can skip this initialization when the `--generate-mono-glue`
flag is passed in.

Fixes issue 75152
2023-05-18 13:57:42 +02:00
Clay John
610877e326
Merge pull request #72288 from MewPurPur/use-string-repeat
Use `String.repeat()` to optimize several String methods
2023-05-05 09:56:48 -07:00
VolTer
6b84e258d2 Use String.repeat() in more places 2023-05-01 02:27:46 +02:00
Ninni Pipping
ff5d8c4a42 Fix "hides member" warnings in csharp_script.cpp 2023-03-25 14:44:12 +01:00
Yuri Sizov
8402927d3f Prevent crashing on startup if project has scripted theme types
Also avoid order of operation conflicts by moving C# binding generation hook to main.cpp
2023-03-08 11:17:21 +01:00
Aleks Rutins
ae8752a731 Validate that C# class names are valid identifiers 2023-03-04 10:30:40 -05:00
RedworkDE
c0ebc28136 C#: Fix crash when errors occur before language initialization. 2023-03-01 00:00:33 +01:00
voidedWarranties
bd5ab9f9b4 Remove unused ScriptLanguage methods 2023-02-26 22:30:56 -08:00
bruvzg
b3c64675cc
[macOS] Replace all Alt/Option+Letter/Number default shortcuts to avoid conflicts with special character input. 2023-02-20 22:02:47 +02:00
Raul Santos
1aceacaa6b
C#: Rename Object to GodotObject 2023-01-27 02:04:18 +01:00
Raul Santos
a968e51414
C#: Renames to follow .NET naming conventions
Renamed C# types and members to use PascalCase and follow .NET naming conventions.
2023-01-27 02:04:17 +01:00
Juan Linietsky
dddd8d43f6 Support script global resource name in EditorFileSystem
* Works for binary and text files.
* Makes EditorQuickOpen work with custom resources again.
* Information is cached and easily accessible.

Properly fixes #66179. Supersedes #66215 and supersedes #62417

**WARNING**: This required breaking backwards binary compatibility (.res and .scn files). Files saved after this PR is merged will no longer open in any earlier versions of Godot.
2023-01-21 14:19:27 +01:00
Raul Santos
3425d43fed
C#: Move GLOBAL_DEFs to CSharpLanguage ctor
Also documents the .NET project settings.
2023-01-18 21:53:58 +01:00
Juan Linietsky
6f0e210093 Refactor ProjectSetting overrides
* Overrides no longer happen for set/get.
* They must be checked with a new function: `ProjectSettings::get_setting_with_override()`.
* GLOBAL_DEF/GLOBAL_GET updated to use this

This change solves many problems:
* General confusion about getting the actual or overriden setting.
* Feature tags available after settings are loaded were being ignored, they are now considered.
* Hacks required for the Project Settings editor to work.

Fixes #64100. Fixes #64014. Fixes #61908.
2023-01-13 15:13:56 +01:00
Rémi Verschelde
d95794ec8a
One Copyright Update to rule them all
As many open source projects have started doing it, we're removing the
current year from the copyright notice, so that we don't need to bump
it every year.

It seems like only the first year of publication is technically
relevant for copyright notices, and even that seems to be something
that many companies stopped listing altogether (in a version controlled
codebase, the commits are a much better source of date of publication
than a hardcoded copyright statement).

We also now list Godot Engine contributors first as we're collectively
the current maintainers of the project, and we clarify that the
"exclusive" copyright of the co-founders covers the timespan before
opensourcing (their further contributions are included as part of Godot
Engine contributors).

Also fixed "cf." Frenchism - it's meant as "refer to / see".
2023-01-05 13:25:55 +01:00
Raul Santos
24e4ac9167
C#: Rename ConvertToX methods
- Renamed `ConvertToX` to `ConvertToNativeX`.
- Renamed `ConvertToXObject` to `ConvertToX`.
- Renamed `ConvertToXManaged` to `ConvertToX`.
- Fix `Signal` name in bindings generator and csharp script.
2022-12-23 19:40:32 +01:00
Raul Santos
2be8cd6863
C#: Add note about the class name in instantiate error
Adds a note about the requirement that a C# class name must match the
script filename in which the they are defined to the instantiate error.
2022-12-17 20:02:01 +01:00
Gilles Roudière
be1c9d677d Rename all gdnative occurences to gdextension
Non-exhaustive list of case-sensitive renames:

GDExtension -> GDNative
GDNATIVE -> GDEXTENSION
gdextension -> gdnative
ExtensionExtension ->Extension (for where there was GDNativeExtension)
EXTENSION_EXTENSION ->EXTENSION (for where there was GDNATIVE_EXTENSION)
gdnlib -> gdextension
gdn_interface -> gde_interface
gdni -> gde_interface
2022-12-12 11:04:57 +01:00
Ignacio Roldán Etcheverry
bcc061edae
Merge pull request #67023 from raulsntos/dotnet/fix-signal-callback-generation
C#: Fix signature of generated signal callbacks
2022-12-02 03:19:49 +01:00
trollodel
c90d0bd84f Use forward-declarations in big editor classes 2022-11-29 09:59:43 +01:00
Ignacio Roldán Etcheverry
2303c26783 C#: Load assemblies as collectible only in the Godot editor
We use collectible AssemblyLoadContexts as that's the only way to allow
reloading assemblies after building. However, collectible assemblies
have some restrictions:

- https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/collectible-assemblies#restrictions-on-collectible-assemblies

Those restrictions can cause issues with third-party code, such as some
mocking libraries.

In order to work around this problem, we're going to load assemblies
as collectible only in Godot editor, and not when running games.
These issues will still exist in the editor, but this will be enough
for some users.
2022-10-17 00:22:48 +02:00
Raul Santos
86f6662a8c
C#: Fix signature of generated signal callbacks
- Use `long` and `double` types since signals currently only support 64-bit types.
- Fix bug for checking if the type name is a class registered in ClassDB.
2022-10-07 12:11:24 +02:00
Rémi Verschelde
5bf95518fd GDScript/C#: Tweak error message for invalid script type for object
See #66870.
2022-10-04 12:56:49 +02:00
Marc Gilleron
474cee7daf Rename and expose RefCounted::get_reference_count() 2022-09-21 21:18:54 +01:00
Ignacio Roldán Etcheverry
8199a209c2 C#: Fix module builds for Windows 32-bit with mingw-w64
The lambda was giving issues, so I re-wrote it as a static function.
2022-09-08 20:57:28 +02:00
Rémi Verschelde
785ce4208d Merge pull request #65266 from raulsntos/dotnet/reload-non-tool-scripts
Create script instance of reloaded scripts even if they're not tools
2022-09-05 08:27:16 +02:00
Raul Santos
a91a3d01f8
C#: Create script instance of reloaded scripts even if they're not tools
Scripts that are instantiated at some point will always be recreated
if they ever become placeholders to prevent non-tool scripts
instantiated manually by users to become placeholders, if they
do become placeholders due to errors that prevent instantiation
(such as a missing parameterless constructor) these scripts
will also be recreated replacing the temporary placeholder.

If a script is marked as a tool but becomes a non-tool script
in a rebuild, the script will become a placeholder and will
no longer be considered applicable to be replaced by an instance
since the user explicitly removed the Tool attribute.
2022-09-04 20:39:37 +02:00
Raul Santos
281ccc7e1b
C#: Connect only once for each signal of a script
Since the list of signals in `CSharpScript::event_signals` retrieved
from calling `ScriptManagerBridge.UpdateScriptClassInfo` already
includes the signals from base scripts there is no need to iterate the
hierarchy again on `CSharpInstance::connect_event_signals`.
2022-09-03 20:39:01 +02:00
Aaron Franke
10a56981dc
Rename String plus_file to path_join 2022-08-29 19:38:13 -05:00
Ignacio Roldán Etcheverry
2c180f62d9 C#: Replace P/Invoke with delegate pointers
- Moves interop functions to UnmanagedCallbacks struct that
  contains the function pointers and is passed to C#.

- Implements UnmanagedCallbacksGenerator, a C# source generator that
  generates the UnmanagedCallbacks struct in C# and the body for the
  NativeFuncs methods (their implementation just calls the function
  pointer in the UnmanagedCallbacks). The generated methods are needed
  because .NET pins byref parameters of native calls, even if they are
  'ref struct's, which don't need pinning. The generated methods use
  `Unsafe.AsPointer` so that we can benefit from byref parameters
  without suffering overhead of pinning.

Co-authored-by: Raul Santos <raulsntos@gmail.com>
2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
1bf4397e5b C#: Use custom project setting for C# project files name
The setting is initially assigned the name of the Godot project,
but it's kept freezed to prevent issues when renaming the Godot
project.

The user can always rename the C# project and solution manually and
change the setting to the new name.
2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
344f5028d4 C#: Add dedicated Variant struct, replacing System.Object 2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
a9892f2571 C#: Add source generator for method list 2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
97713ff77a C#: Add source generator for signals as events
Changed the signal declaration signal to:

```
// The following generates a MySignal event
[Signal] public delegate void MySignalEventHandler(int param);
```
2022-08-22 03:36:52 +02:00
Ignacio Roldán Etcheverry
e235cef09f C#: Re-implement assembly reloading with ALCs 2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
4b90d16250 C#: Initial NativeAOT support
This commit adds initial support for games exported as NativeAOT shared
libraries.

At this moment, the NativeAOT runtime is experimental. Additionally,
Godot is not trim-safe as it still makes some use of reflection.
For the time being, a rd.xml file is needed to prevent code triming:

```
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
  <Application>
    <Assembly Name="GodotSharp" Dynamic="Required All" />
    <Assembly Name="GAME_ASSEMBLY" Dynamic="Required All" />
  </Application>
</Directives>
```

These are the csproj changes for publishing:

```
  <PropertyGroup>
    <NativeLib>Shared</NativeLib>
  </PropertyGroup>
  <ItemGroup>
    <RdXmlFile Include="rd.xml" />
    <PackageReference Include="Microsoft.DotNet.ILCompiler" Version="7.0.0-*" />
  </ItemGroup>
```

More info:
- https://github.com/dotnet/runtimelab/blob/feature/NativeAOT/docs/using-nativeaot/compiling.md
- https://github.com/dotnet/runtimelab/tree/feature/NativeAOT/samples/NativeLibrary
- https://github.com/dotnet/runtimelab/blob/feature/NativeAOT/docs/using-nativeaot/rd-xml-format.md
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
778007a358 C#: Re-introduce exception logging and error stack traces in editor
These two had been disabled while moving to .NET 5, as the previous
implementation relied on Mono embedding APIs.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
67db89988d C#: Ensure we only create one CSharpScript per type
Previously, for each scripts class instance that was created from code
rather than by the engine, we were constructing, configuring and
assigning a new CSharpScript.
This has changed now and we make sure there's only one CSharpScript
associated to each type.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
92503ae8db C#: Add source generator for properties and exports default values
The editor no longer needs to create temporary instances to get the
default values. The initializer values of the exported properties are
still evaluated at runtime. For example, in the following example,
`GetInitialValue()` will be called when first looks for default values:

```
[Export] int MyValue = GetInitialValue();
```

Exporting fields with a non-supported type now results in a compiler
error rather than a runtime error when the script is used.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
88e367a406 C#/netcore: Add base desktop game export implementation
This base implementation is still very barebones but it defines the path
for how exporting will work (at least when embedding the .NET runtime).

Many manual steps are still needed, which should be automatized in the
future. For example, in addition to the API assemblies, now you also
need to copy the GodotPlugins assembly to each game project.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
f88d8902cf C#: Ensure native handles are freed after switch to .NET Core
Finalizers are longer guaranteed to be called on exit now that
we switched to .NET Core. This results in native instances leaking.

The only solution I can think of so far is to keep a list of all
instances alive to dispose when the AssemblyLoadContext.Unloading
event is raised.
2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
e5e7a795b1 C#: Code cleanup and greatly reduce use of C# pointers 2022-08-22 03:36:51 +02:00
Ignacio Roldán Etcheverry
f9a67ee9da C#: Begin move to .NET Core
We're targeting .NET 5 for now to make development easier while
.NET 6 is not yet released.

TEMPORARY REGRESSIONS
---------------------

Assembly unloading is not implemented yet. As such, many Godot
resources are leaked at exit. This will be re-implemented later
together with assembly hot-reloading.
2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
513ee857a9 C#: Restructure code prior move to .NET Core
The main focus here was to remove the majority of code that relied on
Mono's embedding APIs, specially the reflection APIs. The embedding
APIs we still use are the bare minimum we need for things to work.
A lot of code was moved to C#. We no longer deal with any managed
objects (`MonoObject*`, and such) in native code, and all marshaling
is done in C#.

The reason for restructuring the code and move away from embedding APIs
is that once we move to .NET Core, we will be limited by the much more
minimal .NET hosting.

PERFORMANCE REGRESSIONS
-----------------------

Some parts of the code were written with little to no concern about
performance. This includes code that calls into script methods and
accesses script fields, properties and events.
The reason for this is that all of that will be moved to source
generators, so any work prior to that would be a waste of time.

DISABLED FEATURES
-----------------

Some code was removed as it no longer makes sense (or won't make sense
in the future).
Other parts were commented out with `#if 0`s and TODO warnings because
it doesn't make much sense to work on them yet as those parts will
change heavily when we switch to .NET Core but also when we start
introducing source generators.
As such, the following features were disabled temporarily:
- Assembly-reloading (will be done with ALCs in .NET Core).
- Properties/fields exports and script method listing (will be
  handled by source generators in the future).
- Exception logging in the editor and stack info for errors.
- Exporting games.
- Building of C# projects. We no longer copy the Godot API assemblies
  to the project directory, so MSBuild won't be able to find them. The
  idea is to turn them into NuGet packages in the future, which could
  also be obtained from local NuGet sources during development.
2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
5e37d073bb C#: Re-write GD and some other icalls as P/Invoke 2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
9a51430441 C#: Re-write Array, Dictionary, NodePath, String icalls as P/Invoke 2022-08-22 03:35:59 +02:00
Ignacio Roldán Etcheverry
124fbf95f8 C#: Move marshaling logic and generated glue to C#
We will be progressively moving most code to C#.
The plan is to only use Mono's embedding APIs to set things at launch.
This will make it much easier to later support CoreCLR too which
doesn't have rich embedding APIs.

Additionally the code in C# is more maintainable and makes it easier
to implement new features, e.g.: runtime codegen which we could use to
avoid using reflection for marshaling everytime a field, property or
method is accessed.

SOME NOTES ON INTEROP

We make the same assumptions as GDNative about the size of the Godot
structures we use. We take it a bit further by also assuming the layout
of fields in some cases, which is riskier but let's us squeeze out some
performance by avoiding unnecessary managed to native calls.

Code that deals with native structs is less safe than before as there's
no RAII and copy constructors in C#. It's like using the GDNative C API
directly. One has to take special care to free values they own.
Perhaps we could use roslyn analyzers to check this, but I don't know
any that uses attributes to determine what's owned or borrowed.

As to why we maily use pointers for native structs instead of ref/out:
- AFAIK (and confirmed with a benchmark) ref/out are pinned
  during P/Invoke calls and that has a cost.
- Native struct fields can't be ref/out in the first place.
- A `using` local can't be passed as ref/out, only `in`. Calling a
  method or property on an `in` value makes a silent copy, so we want
  to avoid `in`.

REGARDING THE BUILD SYSTEM

There's no longer a `mono_glue=yes/no` SCons options. We no longer
need to build with `mono_glue=no`, generate the glue and then build
again with `mono_glue=yes`. We build only once and generate the glue
(which is in C# now).
However, SCons no longer builds the C# projects for us. Instead one
must run `build_assemblies.py`, e.g.:
```sh
%godot_src_root%/modules/mono/build_scripts/build_assemblies.py \
        --godot-output-dir=%godot_src_root%/bin \
        --godot-target=release_debug`
```
We could turn this into a custom build target, but I don't know how
to do that with SCons (it's possible with Meson).

OTHER NOTES

Most of the moved code doesn't follow the C# naming convention and
still has the word Mono in the names despite no longer dealing with
Mono's embedding APIs. This is just temporary while transitioning,
to make it easier to understand what was moved where.
2022-08-22 03:35:59 +02:00
Yuri Sizov
980f5f32f4 Make property_*_revert methods multilevel and expose them for scripting 2022-08-18 00:03:53 +03:00