2
0
mirror of https://github.com/raylib-cs/raylib-cs synced 2025-06-30 19:03:42 -04:00

Added Raymath binding + Initial examples

- Added Raymath.cs binding. Raylib.cs depends on this since they both share some types.
- Bindings moved into source directly.
- Inital examples port alot of syntax still needs to be fixed.
- Couldn't get cppsharp to work correctly so using a custom generator(WIP).
This commit is contained in:
2018-08-17 09:34:50 +01:00
parent f9350917c2
commit 5286546ad4
154 changed files with 3170 additions and 9265 deletions

View File

@ -1,69 +1,178 @@
using CppSharp;
using CppSharp.AST;
using CppSharp.Generators;
using System;
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Raylibcs
{
/// <summary>
/// Generates the bindings for raylib(WIP)
/// ConsoleDriver.Run(new SampleLibrary());
/// </summary>
public class SampleLibrary : ILibrary
static class Generator
{
void ILibrary.Setup(Driver driver)
{
var options = driver.Options;
options.GeneratorKind = GeneratorKind.CSharp;
options.OutputDir = Path.Combine(Environment.CurrentDirectory, "Raylib-cs");
options.Verbose = true;
// options.UseHeaderDirectories = true;
static string template = @"
using System;
using System.Runtime.InteropServices;
var module = options.AddModule("raylib");
module.IncludeDirs.Add("C:\\raylib\\raylib\\src");
module.Headers.Add("raylib.h");
// module.Headers.Add("rlgl.h");
// module.Headers.Add("raymath.h");
module.LibraryDirs.Add("C:\\raylib\\raylib\\projects\\VS2017\\x64\\Debug.DLL");
module.Libraries.Add("raylib.lib");
// module.OutputNamespace = "Raylib";
// module.internalNamespace = "rl";
}
namespace Raylib
{
public static partial class rl
{
#region Raylib-cs Variables
void ILibrary.SetupPasses(Driver driver)
{
// driver.Context.TranslationUnitPasses.RenameDeclsUpperCase(RenameTargets.Any);
// driver.AddTranslationUnitPass(new FunctionToInstanceMethodPass());
// driver.AddTranslationUnitPass(new CheckOperatorsOverloadsPass());
/*driver.Context.TranslationUnitPasses.RemovePrefix("FLAG_");
driver.Context.TranslationUnitPasses.RemovePrefix("KEY_");
driver.Context.TranslationUnitPasses.RemovePrefix("MOUSE_");
driver.Context.TranslationUnitPasses.RemovePrefix("GAMEPAD_");
driver.Context.TranslationUnitPasses.RemovePrefix("GAMEPAD_PS3_");
driver.Context.TranslationUnitPasses.RemovePrefix("GAMEPAD_PS3_AXIS_");
driver.Context.TranslationUnitPasses.RemovePrefix("GAMEPAD_XBOX_AXIS_");
driver.Context.TranslationUnitPasses.RemovePrefix("GAMEPAD_ANDORID_");*/
}
// Used by DllImport to load the native library.
private const string nativeLibName = 'raylib.dll';
public void Preprocess(Driver driver, ASTContext ctx)
{
ctx.SetNameOfEnumWithMatchingItem("KEY_UNKOWN", "Key");
ctx.GenerateEnumFromMacros("Flag", "FLAG_(.*)");
ctx.GenerateEnumFromMacros("Key", "KEY_(.*)");
ctx.GenerateEnumFromMacros("Mouse", "MOUSE_(.*)");
ctx.GenerateEnumFromMacros("Gamepad", "GAMEPAD_(.*)");
ctx.GenerateEnumFromMacros("GamepadPS3", "GAMEPAD_PS3_(.*)");
ctx.GenerateEnumFromMacros("GamepadPS3Axis", "GAMEPAD_PS3_AXIS_(.*)");
ctx.GenerateEnumFromMacros("GamepadXbox", "GAMEPAD_XBOX_(.*)");
ctx.GenerateEnumFromMacros("GamepadXboxAxis", "GAMEPAD_XBOX_AXIS_(.*)");
ctx.GenerateEnumFromMacros("GamepadAndroid", "GAMEPAD_ANDROID_(.*)");
// TODO: MaxTouchPoints, MaxShaderLocations, MaxMateiralMaps
}
#endregion
public void Postprocess(Driver driver, ASTContext ctx)
{
}
#region Raylib-cs Functions
{{ CONTENT }}
}
}
}
";
static string exampleTemplate = @"
using Raylib;
using static Raylib.rl;
public partial class Examples
{
{{ CONTENT }}
}";
public static string InstallDirectory = "C:\\raylib\\raylib\\src\\";
public static string ExamplesDirectory = "C:\\raylib\\raylib\\examples\\";
// string extensions
private static string CapitalizeFirstCharacter(string format)
{
if (string.IsNullOrEmpty(format))
return string.Empty;
else
return char.ToUpper(format[0]) + format.ToLower().Substring(1);
}
public static string Indent(this string value, int size)
{
var strArray = value.Split('\n');
var sb = new StringBuilder();
foreach (var s in strArray)
sb.Append(new string(' ', size)).Append(s);
return sb.ToString();
}
public static string ReplaceEx(this string input, string pattern, string replacement)
{
input = input.Replace("\r", "\r\n");
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
}
//return input;
//var match = Regex.IsMatch(input, pattern);
return Regex.Replace(input, pattern, replacement);
}
/// <summary>
/// Proocess raylib file
/// </summary>
/// <param name="filePath"></param>
/// <param name="api"></param>
public static void Process(string filePath, string api)
{
var lines = File.ReadAllLines(InstallDirectory + filePath);
var output = "";
// convert functions to c#
foreach (string line in lines)
{
if (line.StartsWith(api))
{
output += "\t\t[DllImport(nativeLibName)]\n";
string newLine = line.Clone().ToString();
newLine = newLine.Replace(api, "public static extern");
// add converted function
output += "\t\t" + newLine + "\n\n";
}
}
output += "\t\t#endregion\n";
// convert syntax to c#
output = template.Replace("{{ CONTENT }}", output);
output = output.Replace("(void)", "()");
output = output.Replace("const char *", "string ");
output = output.Replace("const char * ", "string");
output = output.Replace("const char*", "string");
output = output.Replace("unsigned int", "uint");
output = output.Replace("unsigned char", "byte");
output = output.Replace("const void *", "byte[] ");
output = output.Replace("const float *", "float[] ");
output = output.Replace("const int *", "int[] ");
output = output.Replace("...", "params object[] args");
output = output.Replace("Music ", "IntPtr ");
Console.WriteLine(output);
filePath = Path.GetFileNameWithoutExtension(filePath);
filePath = CapitalizeFirstCharacter(filePath);
Directory.CreateDirectory("Raylib-cs");
File.WriteAllText("Raylib-cs/ " + filePath + ".cs", output);
}
/// <summary>
/// Process raylib examples
/// </summary>
public static void ProcessExamples()
{
// create directory in output folder with same layout as raylib examples
Directory.CreateDirectory("Examples");
var dirs = Directory.GetDirectories(ExamplesDirectory);
foreach (var dir in dirs)
{
var dirName = new DirectoryInfo(dir).Name;
var files = Directory.GetFiles(dir);
Directory.CreateDirectory("Examples\\" + dirName);
foreach (var file in files)
{
if (Path.GetExtension(file) != ".c")
continue;
var fileName = Path.GetFileNameWithoutExtension(file);
var text = File.ReadAllText(file);
// indent since example will be in Examples namespace
text = text.Indent(4);
// add template and fill in content
var output = exampleTemplate;
output = output.Replace("{{ CONTENT }}", text);
output = output.Replace("int main()", "public static int " + fileName + "()");
output = output.Replace("#include \"raylib.h\"", "");
// REGEX WHYYYYYYY!!!
//if (fileName == "core_2d_camera")
{
// remove #include lines
// #define x y -> private const int x = y;
output = output.ReplaceEx(@"#define (\w+).*?(\d+)", "private const int $1 = $2;");
// (Type){...} -> new Type(...);
// output = output.ReplaceEx(@"(\((\w+)\).*?{.*})", @"");
// output = output.ReplaceEx(@"\((\w +)\).*{ (.*)}", @"new $1($2)");
}
//output = output.ReplaceEx(@"#define (\w+) (\w+)", @"struct 1 public 2 public 3 public 4");
var path = "Examples\\" + dirName + "\\" + fileName + ".cs";
File.WriteAllText(path, output);
}
}
}
}
}

View File

@ -4,15 +4,13 @@
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{3B25D9D6-17A6-4A32-B9D1-C637002BD554}</ProjectGuid>
<ProjectGuid>{063F21F1-12D3-41C6-B598-125C725955B1}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Raylibcs</RootNamespace>
<AssemblyName>Raylibcs</AssemblyName>
<RootNamespace>Generator</RootNamespace>
<AssemblyName>Generator</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -33,74 +31,15 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="CppSharp, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.dll</HintPath>
</Reference>
<Reference Include="CppSharp.AST, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.AST.dll</HintPath>
</Reference>
<Reference Include="CppSharp.Generator, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.Generator.dll</HintPath>
</Reference>
<Reference Include="CppSharp.Parser, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.Parser.dll</HintPath>
</Reference>
<Reference Include="CppSharp.Parser.CLI, Version=0.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.Parser.CLI.dll</HintPath>
</Reference>
<Reference Include="CppSharp.Parser.CSharp, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.Parser.CSharp.dll</HintPath>
</Reference>
<Reference Include="CppSharp.Runtime, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>packages\CppSharp.0.8.20\lib\CppSharp.Runtime.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Generator.cs" />
@ -109,18 +48,6 @@
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="packages\Baseclass.Contrib.Nuget.Output.2.4.3\build\Baseclass.Contrib.Nuget.Output.targets" Condition="Exists('packages\Baseclass.Contrib.Nuget.Output.2.4.3\build\Baseclass.Contrib.Nuget.Output.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Baseclass.Contrib.Nuget.Output.2.4.3\build\Baseclass.Contrib.Nuget.Output.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Baseclass.Contrib.Nuget.Output.2.4.3\build\Baseclass.Contrib.Nuget.Output.targets'))" />
</Target>
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@ -1,16 +1,16 @@
using System;
using CppSharp;
namespace Raylibcs
{
static class Program
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Raylib-cs binding generator");
ConsoleDriver.Run(new SampleLibrary());
Console.WriteLine("Raylib-cs generator");
// Generator.Process("raylib.h", "RLAPI");
Generator.ProcessExamples();
Console.WriteLine("Press enter to exit");
Console.ReadLine();
Console.Read();
}
}
}
}

View File

@ -5,11 +5,11 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Raylibcs")]
[assembly: AssemblyTitle("Generator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Raylibcs")]
[assembly: AssemblyProduct("Generator")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@ -20,7 +20,7 @@ using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3b25d9d6-17a6-4a32-b9d1-c637002bd554")]
[assembly: Guid("063f21f1-12d3-41c6-b598-125c725955b1")]
// Version information for an assembly consists of the following four values:
//

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Baseclass.Contrib.Nuget.Output" version="2.4.3" targetFramework="net461" />
<package id="CppSharp" version="0.8.20" targetFramework="net461" developmentDependency="true" />
</packages>