Exemple #1
0
        private void Constants()
        {
            StartBlock("internal static class Defines");
            foreach (var o in def.Consts)
            {
                var type = o.Type;
                type = Cleanup.ConvertType(type);

                var val = o.Val;

                // Don't need to ull in c#
                if (val.EndsWith("ull"))
                {
                    val = val.Replace("ull", "");
                }

                val = val.Replace("uint32", "uint");
                val = val.Replace("16U", "16");
                val = val.Replace("8U", "8");

                // we're not an actual typedef so can't cast like this
                val = val.Replace("( SteamItemInstanceID_t ) ~ 0", "~default(ulong)");

                // This is defined as 0xffffffff - which is too big for an int
                // It seems like the loop around is required, so we just hard code it
                if (o.Name == "HSERVERQUERY_INVALID" && val == "0xffffffff")
                {
                    val = "-1";
                }

                WriteLine($"internal static readonly {type} {o.Name} = {val};");
            }
            EndBlock();
        }
Exemple #2
0
            internal Function AddFunction(string funcName, string returnType, string args)
            {
                if (funcName == "Init")
                {
                    funcName = "DoInit";
                }
                if (funcName == "Shutdown")
                {
                    funcName = "DoShutdown";
                }

                var f = new Function
                {
                    Name       = funcName,
                    ReturnType = returnType
                };

                args = Regex.Replace(args, "", "");

                foreach (var arg in args.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var m = Regex.Match(arg.Trim(), @"(.+?[ |\*|\&])?([a-zA-Z0-9_]+?)( = (.+?))?$");

                    var t = m.Groups[1].Value.Trim();
                    var n = m.Groups[2].Value.Trim();

                    t = Cleanup.ConvertType(t);

                    f.Arguments.Add(n, t);
                }

                Functions.Add(f);

                return(f);
            }
        private void Types()
        {
            foreach (var o in def.typedefs.Where(x => !x.Name.Contains("::")))
            {
                var typeName = Cleanup.ConvertType(o.Name);

                if (!Cleanup.ShouldCreate(typeName))
                {
                    continue;
                }

                if (SkipTypes.Contains(o.Name))
                {
                    continue;
                }

                if (SkipTypesStartingWith.Any(x => o.Name.StartsWith(x)))
                {
                    continue;
                }

                StartBlock($"{Cleanup.Expose( typeName )} struct {typeName}");
                {
                    WriteLine($"public {ToManagedType( o.Type )} Value;");
                    WriteLine();
                    WriteLine($"public static implicit operator {typeName}( {ToManagedType( o.Type )} value ) => new {typeName}(){{ Value = value }};");
                    WriteLine($"public static implicit operator {ToManagedType( o.Type )}( {typeName} value ) => value.Value;");
                    WriteLine($"public override string ToString() => Value.ToString();");
                }
                EndBlock();
                WriteLine();
            }
        }
        public bool IsEnum(string name)
        {
            if (def.enums.Any(x => x.Name == name || Cleanup.ConvertType(x.Name) == name))
            {
                return(true);
            }

            return(false);
        }
        public bool IsCallback(string name)
        {
            if (def.callback_structs.Any(x => x.Name == name || Cleanup.ConvertType(x.Name) == name))
            {
                return(true);
            }

            return(false);
        }
        public bool IsTypeDef(string name)
        {
            if (def.typedefs.Any(x => x.Name == name || Cleanup.ConvertType(x.Name) == name))
            {
                return(true);
            }

            return(false);
        }
        private void Types()
        {
            foreach (var o in def.typedefs.Where(x => !x.Name.Contains("::")))
            {
                var typeName = Cleanup.ConvertType(o.Name);

                if (!Cleanup.ShouldCreate(typeName))
                {
                    continue;
                }

                if (SkipTypes.Contains(o.Name))
                {
                    continue;
                }

                if (SkipTypesStartingWith.Any(x => o.Name.StartsWith(x)))
                {
                    continue;
                }

                StartBlock($"{Cleanup.Expose( typeName )} struct {typeName} : IEquatable<{typeName}>, IComparable<{typeName}>");
                {
                    WriteLine($"public {ToManagedType( o.Type )} Value;");
                    WriteLine();
                    WriteLine($"public static implicit operator {typeName}( {ToManagedType( o.Type )} value ) => new {typeName}(){{ Value = value }};");
                    WriteLine($"public static implicit operator {ToManagedType( o.Type )}( {typeName} value ) => value.Value;");
                    WriteLine($"public override string ToString() => Value.ToString();");
                    WriteLine($"public override int GetHashCode() => Value.GetHashCode();");
                    WriteLine($"public override bool Equals( object p ) => this.Equals( ({typeName}) p );");
                    WriteLine($"public bool Equals( {typeName} p ) => p.Value == Value;");
                    WriteLine($"public static bool operator ==( {typeName} a, {typeName} b ) => a.Equals( b );");
                    WriteLine($"public static bool operator !=( {typeName} a, {typeName} b ) => !a.Equals( b );");

                    if (ToManagedType(o.Type) == "IntPtr")
                    {
                        WriteLine($"public int CompareTo( {typeName} other ) => Value.ToInt64().CompareTo( other.Value.ToInt64() );");
                    }
                    else
                    {
                        WriteLine($"public int CompareTo( {typeName} other ) => Value.CompareTo( other.Value );");
                    }
                }
                EndBlock();
                WriteLine();
            }
        }
        void Structs()
        {
            foreach (var c in def.structs)
            {
                var name = Cleanup.ConvertType(c.Name);

                if (!Cleanup.ShouldCreate(name))
                {
                    continue;
                }

                if (name.Contains("::"))
                {
                    continue;
                }

                var partial = "";
                if (c.Methods != null)
                {
                    partial = " partial";
                }

                //
                // Main struct
                //
                WriteLine($"[StructLayout( LayoutKind.Sequential, Pack = Platform.{(c.IsPack4OnWindows?"StructPackSize": "StructPlatformPackSize")} )]");
                StartBlock($"{Cleanup.Expose( name )}{partial} struct {name}");
                {
                    //
                    // The fields
                    //
                    StructFields(c.Fields);
                    WriteLine();

                    if (c.Enums != null)
                    {
                        foreach (var e in c.Enums)
                        {
                            WriteEnum(e, e.Name);
                        }
                    }
                }
                EndBlock();
                WriteLine();
            }
        }
        private void Enums()
        {
            foreach (var o in def.enums)
            {
                WriteLine($"//");
                WriteLine($"// {o.Name}");
                WriteLine($"//");
                var name = o.Name;

                // We're not interested in namespacing
                if (name.Contains("::"))
                {
                    name = o.Name.Substring(o.Name.LastIndexOf(":") + 1);
                }

                // Skip the E
                if (name[0] == 'E')
                {
                    name = name.Substring(1);
                }

                name = Cleanup.ConvertType(name);

                if (!Cleanup.ShouldCreate(name))
                {
                    continue;
                }

                var lowest  = o.Values.Min(x => long.Parse(x.Value));
                var highest = o.Values.Max(x => long.Parse(x.Value));

                var t = "int";

                if (highest > int.MaxValue)
                {
                    t = "uint";
                }

                WriteEnum(o, name, t);
            }
        }
        void CustomEnums()
        {
            StartBlock("public enum CallbackType");
            foreach (var c in def.callback_structs.OrderBy(x => x.CallbackId))
            {
                if (Cleanup.IsDeprecated(c.Name))
                {
                    Write("// ");
                }

                WriteLine($"{c.Name.Replace( "_t", "" ) } = {c.CallbackId},");
            }
            EndBlock();

            int last = -1;

            StartBlock("internal static partial class CallbackTypeFactory");
            StartBlock("internal static System.Collections.Generic.Dictionary<CallbackType, System.Type> All = new System.Collections.Generic.Dictionary<CallbackType, System.Type>");
            foreach (var c in def.callback_structs.OrderBy(x => x.CallbackId))
            {
                if (Cleanup.IsDeprecated(c.Name))
                {
                    continue;
                }

                if (last == c.CallbackId)
                {
                    Write("// ");
                }

                WriteLine($"{{ CallbackType.{c.Name.Replace( "_t", "" ) }, typeof( {Cleanup.ConvertType(c.Name)} )}},");

                last = c.CallbackId;
            }
            EndBlock(";");
            EndBlock();
        }
        void Structs()
        {
            var callbackList = new List <SteamApiDefinition.StructDef>();

            foreach (var c in def.structs)
            {
                var name = Cleanup.ConvertType(c.Name);

                if (SkipStructs.Contains(c.Name))
                {
                    continue;
                }

                if (!Cleanup.ShouldCreate(name))
                {
                    continue;
                }

                if (name.Contains("::"))
                {
                    continue;
                }

                int defaultPack = c.IsPack4OnWindows ? 4 : 8;

                var isCallback = !string.IsNullOrEmpty(c.CallbackId);

                //
                // Main struct
                //
                WriteLine("[StructLayout( LayoutKind.Sequential, Pack = 4 )]");
                StartBlock($"{Cleanup.Expose( name )} struct {name}");
                {
                    //
                    // The fields
                    //
                    StructFields(c.Fields);
                    WriteLine();

                    if (isCallback)
                    {
                        WriteLine("#region SteamCallback");
                        {
                            if (defaultPack == 4)
                            {
                                WriteLine($"internal static readonly int StructSize = System.Runtime.InteropServices.Marshal.SizeOf( typeof({name}) );");
                                WriteLine($"internal static {name} Fill( IntPtr p ) => (({name})({name}) Marshal.PtrToStructure( p, typeof({name}) ) );");
                            }
                            else
                            {
                                WriteLine($"internal static readonly int StructSize = System.Runtime.InteropServices.Marshal.SizeOf( Config.PackSmall ? typeof({name}) : typeof(Pack8) );");
                                WriteLine($"internal static {name} Fill( IntPtr p ) => Config.PackSmall ? (({name})({name}) Marshal.PtrToStructure( p, typeof({name}) )) : (({name})(Pack8) Marshal.PtrToStructure( p, typeof(Pack8) ));");
                            }
                            WriteLine();
                            WriteLine($"static Action<{name}> actionClient;");
                            WriteLine($"[MonoPInvokeCallback] static void OnClient( IntPtr thisptr, IntPtr pvParam ) => actionClient?.Invoke( Fill( pvParam ) );");

                            WriteLine($"static Action<{name}> actionServer;");
                            WriteLine($"[MonoPInvokeCallback] static void OnServer( IntPtr thisptr, IntPtr pvParam ) => actionServer?.Invoke( Fill( pvParam ) );");

                            StartBlock($"public static void Install( Action<{name}> action, bool server = false )");
                            {
                                StartBlock("if ( server )");
                                {
                                    WriteLine($"Event.Register( OnServer, StructSize, {c.CallbackId}, true );");
                                    WriteLine($"actionServer = action;");
                                }
                                Else();
                                {
                                    WriteLine($"Event.Register( OnClient, StructSize, {c.CallbackId}, false );");
                                    WriteLine($"actionClient = action;");
                                }
                                EndBlock();
                            }
                            EndBlock();

                            StartBlock($"public static async Task<{name}?> GetResultAsync( SteamAPICall_t handle )");
                            {
                                WriteLine($"bool failed = false;");
                                WriteLine();
                                StartBlock($"while ( !SteamUtils.IsCallComplete( handle, out failed ) )");
                                {
                                    WriteLine($"await Task.Delay( 1 );");
                                }
                                EndBlock();

                                WriteLine($"if ( failed ) return null;");
                                WriteLine($"");
                                WriteLine($"var ptr = Marshal.AllocHGlobal( StructSize );");
                                WriteLine($"");
                                WriteLine($"try");
                                WriteLine($"{{");
                                WriteLine($"	if ( !SteamUtils.Internal.GetAPICallResult( handle, ptr, StructSize, {c.CallbackId}, ref failed ) || failed )");
                                WriteLine($"		return null;");
                                WriteLine($"");
                                WriteLine($"	return Fill( ptr );");
                                WriteLine($"}}");
                                WriteLine($"finally");
                                WriteLine($"{{");
                                WriteLine($"	Marshal.FreeHGlobal( ptr );");
                                WriteLine($"}}");
                            }
                            EndBlock();
                        }
                        WriteLine("#endregion");
                    }
                    else
                    {
                        WriteLine("#region Marshalling");
                        {
                            if (defaultPack == 4)
                            {
                                //WriteLine( $"internal static int GetStructSize() => System.Runtime.InteropServices.Marshal.SizeOf( typeof({name}) );" );
                                WriteLine($"internal static {name} Fill( IntPtr p ) => (({name})({name}) Marshal.PtrToStructure( p, typeof({name}) ) );");
                            }
                            else
                            {
                                //WriteLine( $"internal static int GetStructSize() => System.Runtime.InteropServices.Marshal.SizeOf( Config.PackSmall ? typeof({name}) : typeof(Pack8) );" );
                                WriteLine($"internal static {name} Fill( IntPtr p ) => Config.PackSmall ? (({name})({name}) Marshal.PtrToStructure( p, typeof({name}) )) : (({name})(Pack8) Marshal.PtrToStructure( p, typeof(Pack8) ));");
                            }
                        }
                        WriteLine("#endregion");
                    }

                    if (defaultPack != 4)
                    {
                        WriteLine("#region Packed Versions");
                        {
                            //
                            // Windows Packed version
                            //
                            WriteLine();
                            WriteLine($"[StructLayout( LayoutKind.Sequential, Pack = {defaultPack} )]");
                            StartBlock($"public struct Pack8");
                            {
                                StructFields(c.Fields);

                                //
                                // Implicit convert from PackSmall to regular
                                //
                                WriteLine();
                                Write($"public static implicit operator {name} ( {name}.Pack8 d ) => ");
                                {
                                    Write($"new {name}{{ ");
                                    {
                                        foreach (var f in c.Fields)
                                        {
                                            Write($"{CleanMemberName( f.Name )} = d.{CleanMemberName( f.Name )},");
                                        }
                                    }
                                    WriteLine(" };");
                                }

                                Write($"public static implicit operator {name}.Pack8 ( {name} d ) => ");
                                {
                                    Write($"new {name}.Pack8{{ ");
                                    {
                                        foreach (var f in c.Fields)
                                        {
                                            Write($"{CleanMemberName( f.Name )} = d.{CleanMemberName( f.Name )},");
                                        }
                                    }
                                    WriteLine(" };");
                                }
                            }
                            EndBlock();
                        }
                        WriteLine("#endregion");
                    }

                    if (!string.IsNullOrEmpty(c.CallbackId))
                    {
                        callbackList.Add(c);
                    }
                }
                EndBlock();
                WriteLine();
            }
        }
        private void StructFields(SteamApiDefinition.StructDef.StructFields[] fields)
        {
            foreach (var m in fields)
            {
                var t = ToManagedType(m.Type);

                t = Cleanup.ConvertType(t);

                if (TypeDefs.ContainsKey(t))
                {
                    t = TypeDefs[t].ManagedType;
                }

                if (t == "bool")
                {
                    WriteLine("[MarshalAs(UnmanagedType.I1)]");
                }

                if (t.StartsWith("char ") && t.Contains("["))
                {
                    var num = t.Replace("char", "").Trim('[', ']', ' ');
                    t = "string";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValTStr, SizeConst = {num})]");
                }

                if (t.StartsWith("uint8 ") && t.Contains("["))
                {
                    var num = t.Replace("uint8", "").Trim('[', ']', ' ');
                    t = "byte[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num})] //  {m.Name}");
                }

                if (t.StartsWith("SteamId") && t.Contains("["))
                {
                    var num = t.Replace("SteamId", "").Trim('[', ']', ' ');
                    t = $"ulong[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U8)]");
                }

                if (t.StartsWith("PublishedFileId ") && t.Contains("["))
                {
                    var num = t.Replace("PublishedFileId", "").Trim('[', ']', ' ');
                    t = $"PublishedFileId[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U8)]");
                }

                if (t.StartsWith("uint32 ") && t.Contains("["))
                {
                    var num = t.Replace("uint32", "").Trim('[', ']', ' ');
                    t = $"uint[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U4)]");
                }

                if (t.StartsWith("float ") && t.Contains("["))
                {
                    var num = t.Replace("float", "").Trim('[', ']', ' ');
                    t = $"float[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.R4)]");
                }

                if (t == "const char **")
                {
                    t = "IntPtr";
                }

                if (t.StartsWith("AppId ") && t.Contains("["))
                {
                    var num = t.Replace("AppId", "").Trim('[', ']', ' ');
                    t = $"AppId[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U4)]");
                }

                WriteLine($"internal {t} {CleanMemberName( m.Name )}; // {m.Name} {m.Type}");
            }
        }
Exemple #13
0
    public static BaseType Parse(string type, string varname = null, string callresult = null)
    {
        type = Cleanup.ConvertType(type);

        if (varname == "ppOutMessages")
        {
            return new PointerType {
                       NativeType = "void *", VarName = varname
            }
        }
        ;
        if (type == "SteamAPIWarningMessageHook_t")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (type == "SteamAPICall_t")
        {
            return new SteamApiCallType {
                       NativeType = type, VarName = varname, CallResult = callresult
            }
        }
        ;

        if (type == "void")
        {
            return new VoidType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (type.Replace(" ", "").StartsWith("constchar*"))
        {
            return new ConstCharType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (type == "char *")
        {
            return new FetchStringType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        var basicType = type.Replace("const ", "").Trim(' ', '*', '&');

        if (basicType == "void")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType.StartsWith("ISteam"))
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "const void")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "int32" || basicType == "int")
        {
            return new IntType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint")
        {
            return new UIntType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint8")
        {
            return new UInt8Type {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint16")
        {
            return new UInt16Type {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "unsigned short")
        {
            return new UInt16Type {
                       NativeType = type, VarName = varname
            }
        }
        ;

        // DANGER DANGER Danger
        if (basicType == "intptr_t")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "size_t")
        {
            return new UIntPtrType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (basicType == "uint64")
        {
            return new ULongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "int64")
        {
            return new LongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "bool")
        {
            return new BoolType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        //
        // Enum types are handled in a generic way, but we do need to clean up the name
        //
        if (Generator.CodeWriter.Current.IsEnum(basicType))
        {
            return(new BaseType {
                NativeType = Cleanup.CleanEnum(type), VarName = varname
            });
        }

        //
        // Structs are generally sent as plain old data, but need marshalling if they're expected as a pointer
        //
        if (Generator.CodeWriter.Current.IsStruct(basicType))
        {
            return(new StructType {
                NativeType = type, VarName = varname, StructName = basicType
            });
        }

        //
        // c# doesn't really have typerdefs, so we convert things like HSteamUser into structs
        // which from a memory point of view behave in the same way.
        //
        if (Generator.CodeWriter.Current.IsTypeDef(basicType))
        {
            return(new StructType {
                NativeType = type, VarName = varname, StructName = basicType
            });
        }

        return(new BaseType {
            NativeType = type, VarName = varname
        });
    }
        void Callbacks()
        {
            var callbackList = new List <SteamApiDefinition.StructDef>();

            foreach (var c in def.callback_structs)
            {
                var name = Cleanup.ConvertType(c.Name);

                if (!Cleanup.ShouldCreate(name))
                {
                    continue;
                }

                if (name.Contains("::"))
                {
                    continue;
                }

                var partial = "";
                if (c.Methods != null)
                {
                    partial = " partial";
                }

                int defaultPack = c.IsPack4OnWindows ? 4 : 8;

                var isCallback = true;
                var iface      = "";
                if (isCallback)
                {
                    iface = " : ICallbackData";
                }

                //
                // Main struct
                //
                WriteLine($"[StructLayout( LayoutKind.Sequential, Pack = Platform.{(c.IsPack4OnWindows?"StructPackSize": "StructPlatformPackSize")} )]");
                StartBlock($"{Cleanup.Expose( name )}{partial} struct {name}{iface}");
                {
                    //
                    // The fields
                    //
                    StructFields(c.Fields);
                    WriteLine();

                    if (isCallback)
                    {
                        WriteLine("#region SteamCallback");
                        {
                            WriteLine($"public static int _datasize = System.Runtime.InteropServices.Marshal.SizeOf( typeof({name}) );");
                            WriteLine($"public int DataSize => _datasize;");
                            WriteLine($"public CallbackType CallbackType => CallbackType.{name.Replace( "_t", "" )};");
                        }
                        WriteLine("#endregion");
                    }

                    if (c.Enums != null)
                    {
                        foreach (var e in c.Enums)
                        {
                            WriteEnum(e, e.Name);
                        }
                    }

                    // if (  c.CallbackId ) )
                    {
                        callbackList.Add(c);
                    }
                }
                EndBlock();
                WriteLine();
            }
        }
        private void StructFields(SteamApiDefinition.StructDef.StructFields[] fields)
        {
            foreach (var m in fields)
            {
                var t = ToManagedType(m.Type);

                t = Cleanup.ConvertType(t);

                if (TypeDefs.ContainsKey(t))
                {
                    t = TypeDefs[t].ManagedType;
                }

                if (t == "bool")
                {
                    WriteLine("[MarshalAs(UnmanagedType.I1)]");
                }

                if (t.StartsWith("char ") && t.Contains("["))
                {
                    WriteLine($"internal string {CleanMemberName( m.Name )}UTF8() => System.Text.Encoding.UTF8.GetString( {CleanMemberName( m.Name )}, 0, System.Array.IndexOf<byte>( {CleanMemberName( m.Name )}, 0 ) );");

                    var num = t.Replace("char", "").Trim('[', ']', ' ');
                    t = "byte[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num})] // {t} {m.Name}");
                }

                if (t.StartsWith("uint8 ") && t.Contains("["))
                {
                    var num = t.Replace("uint8", "").Trim('[', ']', ' ');
                    t = "byte[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num})] //  {m.Name}");
                }

                if (t.StartsWith("ushort ") && t.Contains("["))
                {
                    var num = t.Replace("ushort", "").Trim('[', ']', ' ');
                    t = $"ushort[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U2)]");
                }

                if (t.StartsWith("SteamId") && t.Contains("["))
                {
                    var num = t.Replace("SteamId", "").Trim('[', ']', ' ');
                    t = $"ulong[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U8)]");
                }

                if (t.StartsWith("PublishedFileId ") && t.Contains("["))
                {
                    var num = t.Replace("PublishedFileId", "").Trim('[', ']', ' ');
                    t = $"PublishedFileId[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U8)]");
                }

                if (t.StartsWith("uint32 ") && t.Contains("["))
                {
                    var num = t.Replace("uint32", "").Trim('[', ']', ' ');
                    t = $"uint[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U4)]");
                }

                if (t.StartsWith("uint ") && t.Contains("["))
                {
                    var num = t.Replace("uint", "").Trim('[', ']', ' ');
                    t = $"uint[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U4)]");
                }

                if (t.StartsWith("float ") && t.Contains("["))
                {
                    var num = t.Replace("float", "").Trim('[', ']', ' ');
                    t = $"float[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.R4)]");
                }

                if (t == "const char **")
                {
                    t = "IntPtr";
                }

                if (t.StartsWith("AppId ") && t.Contains("["))
                {
                    var num = t.Replace("AppId", "").Trim('[', ']', ' ');
                    t = $"AppId[]";
                    WriteLine($"[MarshalAs(UnmanagedType.ByValArray, SizeConst = {num}, ArraySubType = UnmanagedType.U4)]");
                }

                if (t == "SteamInputActionEvent_t.AnalogAction_t")
                {
                    Write("// ");
                }

                WriteLine($"internal {t} {CleanMemberName( m.Name )}; // {m.Name} {m.Type}");
            }
        }
        private string ToManagedType(string type)
        {
            type = type.Replace("ISteamHTMLSurface::", "");
            type = type.Replace("class ", "");
            type = type.Replace("struct ", "");
            type = type.Replace("const void", "void");
            type = type.Replace("union ", "");
            type = type.Replace("enum ", "");

            type = Cleanup.ConvertType(type);

            switch (type)
            {
            case "uint64": return("ulong");

            case "uint32": return("uint");

            case "int32": return("int");

            case "int32_t": return("int");

            case "int64": return("long");

            case "int64_t": return("long");

            case "void *": return("IntPtr");

            case "uint8 *": return("IntPtr");

            case "int16": return("short");

            case "uint8": return("byte");

            case "int8": return("char");

            case "unsigned short": return("ushort");

            case "unsigned int": return("uint");

            case "uint16": return("ushort");

            case "const char *": return("string");

            case "_Bool": return("bool");

            case "SteamId": return("ulong");

            case "SteamAPIWarningMessageHook_t": return("IntPtr");
            }

            //type = type.Trim( '*', ' ' );

            // Enums - skip the 'E'
            if (type[0] == 'E')
            {
                return(type.Substring(1));
            }

            if (type.StartsWith("ISteamMatchmak") && type.Contains("Response"))
            {
                return("IntPtr");
            }

            return(type);
        }
Exemple #17
0
    public static BaseType Parse(string type, string varname = null)
    {
        type = Cleanup.ConvertType(type);

        if (type == "SteamAPIWarningMessageHook_t")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (type == "SteamAPICall_t")
        {
            return new SteamApiCallType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (type == "void")
        {
            return new VoidType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (type.Replace(" ", "").StartsWith("constchar*"))
        {
            return new ConstCharType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (type == "char *")
        {
            return new StringBuilderType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        var basicType = type.Replace("const ", "").Trim(' ', '*', '&');

        if (basicType == "void")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType.StartsWith("ISteam"))
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "const void")
        {
            return new PointerType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "int32" || basicType == "int")
        {
            return new IntType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint32")
        {
            return new UIntType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint8")
        {
            return new UInt8Type {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "uint16")
        {
            return new UInt16Type {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "SteamId")
        {
            return new CSteamIdType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        // DANGER DANGER Danger
        if (basicType == "size_t")
        {
            return new ULongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "intptr_t")
        {
            return new LongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "ptrdiff_t")
        {
            return new LongType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (basicType == "uint64")
        {
            return new ULongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "int64")
        {
            return new LongType {
                       NativeType = type, VarName = varname
            }
        }
        ;
        if (basicType == "bool")
        {
            return new BoolType {
                       NativeType = type, VarName = varname
            }
        }
        ;

        if (basicType.EndsWith("_t"))
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "InventoryItemId")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "InventoryDefId")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "PingLocation")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "NetworkIdentity")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "NetworkAddress")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType == "ConnectionInfo")
        {
            return new StructType {
                       NativeType = type, VarName = varname, StructName = basicType
            }
        }
        ;
        if (basicType.StartsWith("E") && char.IsUpper(basicType[1]))
        {
            return new EnumType {
                       NativeType = type.Substring(1), VarName = varname
            }
        }
        ;

        return(new BaseType {
            NativeType = type, VarName = varname
        });
    }
Exemple #18
0
        void StructFunctions()
        {
            foreach (var c in def.structs.Union(def.callback_structs.Select(x => x as SteamApiDefinition.StructDef)).OrderBy(x => x.Name))
            {
                var name = Cleanup.ConvertType(c.Name);

                if (name.Contains("::"))
                {
                    continue;
                }

                if (c.Methods == null || c.Methods.Length == 0)
                {
                    continue;
                }

                //
                // Main struct
                //
                StartBlock($"{Cleanup.Expose( name )} partial struct {name}");
                {
                    foreach (var func in c.Methods)
                    {
                        if (func.Name.Contains("operator"))
                        {
                            func.Name = func.FlatName.Substring(func.FlatName.LastIndexOf('_') + 1);
                        }

                        var returnType = BaseType.Parse(func.ReturnType, null, func.CallResult);
                        returnType.Func = func.Name;

                        var args = func.Params.Select(x =>
                        {
                            var bt  = BaseType.Parse(x.ParamType, x.ParamName);
                            bt.Func = func.Name;
                            return(bt);
                        }).ToArray();

                        for (int i = 0; i < args.Length; i++)
                        {
                            if (args[i] is FetchStringType)
                            {
                                if (args[i + 1] is IntType || args[i + 1] is UIntType || args[i + 1] is UIntPtrType)
                                {
                                    if (string.IsNullOrEmpty(args[i + 1].Ref))
                                    {
                                        args[i + 1] = new LiteralType(args[i + 1], "(1024 * 32)");
                                    }
                                }
                                else
                                {
                                    throw new System.Exception($"String Builder Next Type Is {args[i + 1].GetType()}");
                                }
                            }
                        }

                        var delegateargstr = string.Join(", ", args.Select(x => x.AsNativeArgument()));

                        if (!string.IsNullOrEmpty(func.Desc))
                        {
                            WriteLine("/// <summary>");
                            WriteLine($"/// {func.Desc}");
                            WriteLine("/// </summary>");
                        }

                        if (returnType.ReturnAttribute != null)
                        {
                            WriteLine(returnType.ReturnAttribute);
                        }

                        var _unsafe  = "";
                        var firstArg = $"ref {name} self";

                        //
                        // If this is NetMsg then the ORIGINAL pointer address is important
                        // because we need to pass in the original pointer - not just the data
                        //
                        if (name == "NetMsg")
                        {
                            firstArg = $"{name}* self";
                            _unsafe  = " unsafe";
                        }

                        WriteLine($"[DllImport( Platform.LibraryName, EntryPoint = \"{func.FlatName}\", CallingConvention = Platform.CC)]");
                        WriteLine($"internal static{_unsafe} extern {returnType.TypeNameFrom} Internal{func.Name}( {firstArg}, {delegateargstr} );".Replace($"( {firstArg},  )", $"( {firstArg} )"));
                        WriteLine();
                    }
                }
                EndBlock();
                WriteLine();
            }
        }
        private void Enums()
        {
            foreach (var o in def.enums)
            {
                WriteLine($"//");
                WriteLine($"// {o.Name}");
                WriteLine($"//");
                var name = o.Name;

                // We're not interested in namespacing
                if (name.Contains("::"))
                {
                    name = o.Name.Substring(o.Name.LastIndexOf(":") + 1);
                }

                // Skip the E
                if (name[0] == 'E')
                {
                    name = name.Substring(1);
                }

                name = Cleanup.ConvertType(name);

                if (!Cleanup.ShouldCreate(name))
                {
                    continue;
                }

                StartBlock($"{Cleanup.Expose( name )} enum {name} : int");
                {
                    //
                    // If all the enum values start with the same
                    // string, remove it. This converts
                    // "k_EUserHasLicenseResultHasLicense" to "HasLicense" etc
                    //
                    int iFinished = int.MaxValue;
                    for (int i = 0; i < 4096; i++)
                    {
                        var c = o.Values.First().Name[i];
                        foreach (var entry in o.Values)
                        {
                            if (entry.Name[i] != c)
                            {
                                iFinished = i;
                                break;
                            }
                        }

                        if (iFinished != int.MaxValue)
                        {
                            break;
                        }
                    }

                    foreach (var entry in o.Values)
                    {
                        var ename = entry.Name;

                        if (iFinished != int.MaxValue)
                        {
                            ename = ename.Substring(iFinished);
                        }

                        //
                        // Names aren't allowed to start with a number
                        // So just stick the enum name on the front
                        //
                        if (char.IsNumber(ename[0]))
                        {
                            ename = name + ename;
                        }

                        WriteLine($"{ename} = {entry.Value},");
                    }
                }
                EndBlock();
                WriteLine();
            }
        }