public void Unindent()
{
if (indent_level > 0)
+ {
--indent_level;
+ }
}
public void Write(WriteOptions options, string value)
if (options != WriteOptions.NoIndent)
{
for (int i = indent_level; i > 0; i--)
+ {
sw.Write(" ");
+ }
}
}
int top = Console.CursorTop;
Console.Write(text);
for (int i = text.Length; i < 80; i++)
+ {
Console.Write(" ");
+ }
Console.WriteLine();
Console.SetCursorPosition(left, top);
}
{
Console.WriteLine("Writing bindings to {0}", Settings.OutputPath);
if (!Directory.Exists(Settings.OutputPath))
+ {
Directory.CreateDirectory(Settings.OutputPath);
+ }
string temp_enums_file = Path.GetTempFileName();
string temp_wrappers_file = Path.GetTempFileName();
sw.WriteLine("static partial class {0}", Settings.OutputClass);
}
else
+ {
sw.WriteLine("namespace {0}", Settings.EnumsOutput);
+ }
sw.WriteLine("{");
string output_core = Path.Combine(Settings.OutputPath, Settings.ImportsFile);
string output_wrappers = Path.Combine(Settings.OutputPath, Settings.WrappersFile);
- if (File.Exists(output_enums)) File.Delete(output_enums);
- if (File.Exists(output_delegates)) File.Delete(output_delegates);
- if (File.Exists(output_core)) File.Delete(output_core);
- if (File.Exists(output_wrappers)) File.Delete(output_wrappers);
+ if (File.Exists(output_enums))
+ {
+ File.Delete(output_enums);
+ }
+ if (File.Exists(output_delegates))
+ {
+ File.Delete(output_delegates);
+ }
+ if (File.Exists(output_core))
+ {
+ File.Delete(output_core);
+ }
+ if (File.Exists(output_wrappers))
+ {
+ File.Delete(output_wrappers);
+ }
File.Move(temp_enums_file, output_enums);
File.Move(temp_wrappers_file, output_wrappers);
else if (!String.IsNullOrEmpty(f.Version))
{
if (f.Category.StartsWith("VERSION"))
+ {
category = String.Format("[requires: {0}]", "v" + f.Version);
+ }
else
+ {
category = String.Format("[requires: {0}]", "v" + f.Version + " or " + f.Category);
+ }
}
// Write function summary
sw.Write(str);
if (!String.IsNullOrEmpty(str))
+ {
sw.WriteLine(",");
+ }
}
}
//sw.WriteLine();
if ((Settings.Compatibility & Settings.Legacy.NestedEnums) != Settings.Legacy.None)
+ {
Trace.WriteLine(String.Format("Writing enums to:\t{0}.{1}.{2}", Settings.OutputNamespace, Settings.OutputClass, Settings.NestedEnumsClass));
+ }
else
+ {
Trace.WriteLine(String.Format("Writing enums to:\t{0}", Settings.EnumsOutput));
+ }
if ((Settings.Compatibility & Settings.Legacy.ConstIntEnums) == Settings.Legacy.None)
{
}
if (@enum.IsObsolete)
+ {
sw.WriteLine("[Obsolete(\"{0}\")]", @enum.Obsolete);
+ }
if (!@enum.CLSCompliant)
+ {
sw.WriteLine("[CLSCompliant(false)]");
+ }
if (@enum.IsFlagCollection)
+ {
sw.WriteLine("[Flags]");
+ }
sw.WriteLine("public enum " + @enum.Name + " : " + @enum.Type);
sw.WriteLine("{");
sw.Indent();
sb.Append(d.Unsafe ? "unsafe " : "");
if (is_delegate)
+ {
sb.Append("delegate ");
+ }
sb.Append(GetDeclarationString(d.ReturnType, Settings.Legacy.ConstIntEnums));
sb.Append(" ");
sb.Append(Settings.FunctionPrefix);
{
int ret = String.Compare(c1.Value, c2.Value);
if (ret == 0)
+ {
return String.Compare(c1.Name, c2.Name);
+ }
return ret;
});
if (e.IsFlagCollection)
+ {
sb.AppendLine("[Flags]");
+ }
sb.Append("public enum ");
sb.Append(e.Name);
sb.Append(" : ");
sb.Append(" ");
sb.Append(declaration);
if (!String.IsNullOrEmpty(declaration))
+ {
sb.AppendLine(",");
+ }
}
sb.Append("}");
foreach (Parameter p in f.Parameters)
{
if (p.Generic)
+ {
sb.AppendLine(String.Format(" where {0} : struct", p.CurrentType));
+ }
}
}
StringBuilder sb = new StringBuilder();
if (p.Flow == FlowDirection.Out)
+ {
sb.Append("[OutAttribute] ");
+ }
else if (p.Flow == FlowDirection.Undefined)
+ {
sb.Append("[InAttribute, OutAttribute] ");
+ }
if (p.Reference)
{
if (p.Flow == FlowDirection.Out)
+ {
sb.Append("out ");
+ }
else
+ {
sb.Append("ref ");
+ }
}
if (!override_unsafe_setting && ((Settings.Compatibility & Settings.Legacy.NoPublicUnsafeFunctions) != Settings.Legacy.None))
public DocProcessor(IBind generator)
{
if (generator == null)
+ {
throw new ArgumentNullException();
+ }
Generator = generator;
foreach (string file in Directory.GetFiles(Settings.DocPath).Concat(
{
var file = Settings.FunctionPrefix + f.WrappedDelegate.Name + ".xml";
if (!DocumentationFiles.ContainsKey(file))
+ {
file = Settings.FunctionPrefix + f.TrimmedName + ".xml";
+ }
if (!DocumentationFiles.ContainsKey(file))
+ {
file = Settings.FunctionPrefix + f.TrimmedName.TrimEnd(numbers) + ".xml";
+ }
docs =
(DocumentationFiles.ContainsKey(file) ? ProcessFile(DocumentationFiles[file], processor) : null) ??
string text;
if (LastFile == file)
+ {
return Cached;
+ }
LastFile = file;
text = File.ReadAllText(file);
private Documentation ToInlineDocs(XDocument doc, EnumProcessor enum_processor)
{
if (doc == null || enum_processor == null)
+ {
throw new ArgumentNullException();
+ }
var no_const_processing = Settings.Legacy.NoAdvancedEnumProcessing | Settings.Legacy.ConstIntEnums;
if (!Generator.Settings.IsEnabled(no_const_processing))
public EnumProcessor(IBind generator, IEnumerable<string> overrides)
{
if (generator == null)
+ {
throw new ArgumentNullException("generator");
+ }
if (overrides == null)
+ {
throw new ArgumentNullException("overrides");
+ }
Generator = generator;
Overrides = overrides;
public static string GetOverridesPath(string apiname, string enumeration)
{
if (enumeration == null)
+ {
throw new ArgumentNullException("enumeration");
+ }
var path = new StringBuilder();
path.Append("/signatures/replace");
public string TranslateEnumName(string name)
{
if (String.IsNullOrEmpty(name))
+ {
return name;
+ }
if (Utilities.CSharpKeywords.Contains(name))
+ {
return name;
+ }
if (!IsAlreadyProcessed(name))
{
if (Char.IsDigit(name[0]))
+ {
name = Settings.ConstantPrefix + name;
+ }
StringBuilder translator = new StringBuilder(name);
}
if (is_after_underscore_or_number)
+ {
char_to_add = Char.ToUpper(c);
+ }
else if (is_previous_uppercase)
+ {
char_to_add = Char.ToLower(c);
+ }
else
+ {
char_to_add = c;
+ }
translator.Append(char_to_add);
name = translator.ToString();
if (name.StartsWith(Settings.EnumPrefix))
+ {
name = name.Substring(Settings.EnumPrefix.Length);
+ }
}
return name;
public string TranslateConstantName(string s, bool isValue)
{
if (String.IsNullOrEmpty(s))
+ {
return s;
+ }
StringBuilder translator = new StringBuilder(s.Length);
bool is_after_digit = false;
if (!isValue && Char.IsDigit(s[0]))
+ {
s = Settings.ConstantPrefix + s;
+ }
foreach (char c in s)
{
translator[0] = Char.ToUpper(translator[0]);
}
else
+ {
translator.Append(s);
+ }
}
return translator.ToString();
{
// Trim the unsigned or long specifiers used in C constants ('u' or 'ull').
if (value.ToLower().EndsWith("ull"))
+ {
value = value.Substring(0, value.Length - 3);
+ }
if (value.ToLower().EndsWith("u"))
+ {
value = value.Substring(0, value.Length - 1);
+ }
}
// Strip the prefix, if any.
if (value.StartsWith(Settings.ConstantPrefix))
+ {
value = value.Substring(Settings.ConstantPrefix.Length);
+ }
return TranslateConstantName(value, IsValue(value));
}
public FuncProcessor(IBind generator, IEnumerable<string> overrides)
{
if (generator == null)
+ {
throw new ArgumentNullException("generator");
+ }
if (overrides == null)
+ {
throw new ArgumentNullException("overrides");
+ }
Generator = generator;
Overrides = overrides;
{
// For consistency - many overrides use string instead of String.
if (enum_override.Value == "string")
+ {
type.QualifiedType = "String";
+ }
else if (enum_override.Value == "StringBuilder")
+ {
type.QualifiedType = "StringBuilder";
+ }
else
+ {
type.CurrentType = enum_override.Value;
+ }
}
if (type.CurrentType == "IntPtr" && String.IsNullOrEmpty(type.PreviousType))
+ {
type.Pointer = 0;
+ }
if (type.Pointer >= 3)
{
string extensionless_name = GetTrimmedExtension(d.Name, ext);
function_overload = nav.Select(GetOverloadsPath(apiname, apiversion, d.Name, ext));
if (function_overload.Count != 0)
+ {
break;
+ }
function_overload = nav.Select(GetOverloadsPath(apiname, apiversion, extensionless_name, ext));
if (function_overload.Count != 0)
+ {
break;
+ }
function_overload = nav.Select(GetOverloadsPath(apiname, apiversion, trimmed_name, ext));
if (function_overload.Count != 0)
+ {
break;
+ }
}
return function_overload;
}
case "count":
int count;
if (Int32.TryParse(node.Value, out count))
+ {
d.Parameters[i].ElementCount = count;
+ }
break;
}
}
if (d.ReturnType.CurrentType.Contains("GLenum"))
{
if ((Settings.Compatibility & Settings.Legacy.ConstIntEnums) == Settings.Legacy.None)
+ {
d.ReturnType.QualifiedType = String.Format("{0}{1}{2}",
Settings.EnumsOutput, Settings.NamespaceSeparator, Settings.CompleteEnumName);
+ }
else
+ {
d.ReturnType.QualifiedType = "int";
+ }
}
if (d.ReturnType.CurrentType.ToLower().Contains("bool"))
{
TranslateParameter(d.Parameters[i], function_override, nav, enum_processor, enums, d.Category, apiname);
if (d.Parameters[i].CurrentType == "UInt16" && d.Name.Contains("LineStipple"))
+ {
d.Parameters[i].WrapperType |= WrapperTypes.UncheckedParameter;
+ }
}
}
}
if (Utilities.CSharpKeywords.Contains(p.Name))
+ {
p.Name = Settings.KeywordEscapeCharacter + p.Name;
+ }
// This causes problems with bool arrays
//if (CurrentType.ToLower().Contains("bool"))
{
cls.Parameters[i].CurrentType = GetCLSCompliantType(cls.Parameters[i]);
if (cls.Parameters[i].CurrentType != f.Parameters[i].CurrentType)
+ {
modified = true;
+ }
}
// Only add a cls-compliant overload if we have
for (k = 0; k < wrappers[i].Parameters.Count; k++)
{
if (wrappers[i].Parameters[k].CurrentType != wrappers[j].Parameters[k].CurrentType)
+ {
break;
+ }
if (wrappers[i].Parameters[k].DiffersOnlyOnReference(wrappers[j].Parameters[k]))
+ {
if (wrappers[i].Parameters[k].Reference)
+ {
function_i_is_problematic = true;
+ }
else
+ {
function_j_is_problematic = true;
+ }
+ }
}
if (k == wrappers[i].Parameters.Count)
{
if (function_i_is_problematic)
+ {
must_remove.Add(i);
+ }
if (function_j_is_problematic)
+ {
must_remove.Add(j);
+ }
}
}
}
if (!type.CLSCompliant)
{
if (type.Pointer != 0 && Settings.Compatibility == Settings.Legacy.Tao)
+ {
return "IntPtr";
+ }
switch (type.CurrentType)
{
public Generator(Settings settings)
{
if (settings == null)
+ {
throw new ArgumentNullException("settings");
+ }
Settings = settings.Clone();
val = val.ToLower();
bool enable = !opt.StartsWith("-");
if (val.StartsWith("+") || val.StartsWith("-"))
+ {
val = val.Substring(1);
+ }
var settings = Settings.Legacy.None;
switch (val)
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
+ {
return OutputNamespace + NamespaceSeparator + OutputClass + NamespaceSeparator + NestedEnumsClass;
+ }
else
+ {
return String.IsNullOrEmpty(EnumsNamespace) ? OutputNamespace : OutputNamespace + NamespaceSeparator + EnumsNamespace;
+ }
}
}
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
+ {
return OutputNamespace + NamespaceSeparator + GLClass + NamespaceSeparator + NestedEnumsClass;
+ }
else
+ {
return OutputNamespace + NamespaceSeparator + EnumsNamespace;
+ }
}
}
public bool DropMultipleTokens
{
get { return (Compatibility & Legacy.NoDropMultipleTokens) == Legacy.None; }
- set { if (value) Compatibility |= Legacy.NoDropMultipleTokens; else Compatibility &= ~Legacy.NoDropMultipleTokens; }
+ set { if (value)
+ {
+ Compatibility |= Legacy.NoDropMultipleTokens;
+ }
+ else
+ {
+ Compatibility &= ~Legacy.NoDropMultipleTokens;
+ }
+ }
}
public string WindowsGDI = "OpenTK.Platform.Windows.API";
set
{
if (String.IsNullOrEmpty(value))
+ {
throw new ArgumentNullException("value");
+ }
if (OriginalName == null)
+ {
OriginalName = _name;
+ }
_name = value;
}
set
{
if (String.IsNullOrEmpty(value))
+ {
throw new ArgumentNullException("value");
+ }
_value = value;
}
public static bool TranslateConstantWithReference(Constant c, EnumCollection enums)
{
if (c == null)
+ {
throw new ArgumentNullException("c");
+ }
if (enums == null)
+ {
throw new ArgumentNullException("enums");
+ }
if (!String.IsNullOrEmpty(c.Reference))
{
{
int ret = Value.CompareTo(other.Value);
if (ret == 0)
+ {
return Name.CompareTo(other.Name);
+ }
return ret;
}
}
get
{
if (cls_compliance_overriden != null)
+ {
return (bool)cls_compliance_overriden;
+ }
if (Unsafe)
+ {
return false;
+ }
if (!ReturnType.CLSCompliant)
+ {
return false;
+ }
foreach (Parameter p in Parameters)
{
if (!p.CLSCompliant)
+ {
return false;
+ }
}
return true;
}
// TODO: Add special cases for (Get)ShaderSource.
if (ReturnType.WrapperType != WrapperTypes.None)
+ {
return true;
+ }
foreach (Parameter p in Parameters)
{
if (p.WrapperType != WrapperTypes.None)
+ {
return true;
+ }
}
return false;
// return false;
if (ReturnType.Pointer != 0)
+ {
return true;
+ }
foreach (Parameter p in Parameters)
{
{
int ret = Name.CompareTo(other.Name);
if (ret == 0)
+ {
ret = Parameters.CompareTo(other.Parameters);
+ }
if (ret == 0)
+ {
ret = ReturnType.CompareTo(other.ReturnType);
+ }
return ret;
}
set
{
if (value == null)
+ {
throw new ArgumentNullException("value");
+ }
_constant_collection.Clear();
foreach (var item in value)
// empty check, let's try to remove first Arb, then Ext from the strings.
int ret = PreferEmpty(ext1, ext2);
if (ret != 0)
+ {
return ret;
+ }
ext1 = ext1.Replace("Arb", ""); ext2 = ext2.Replace("Arb", "");
ret = PreferEmpty(ext1, ext2);
if (ret != 0)
+ {
return ret;
+ }
ext1 = ext1.Replace("Ext", ""); ext2 = ext2.Replace("Ext", "");
return PreferEmpty(ext1, ext2);
private int PreferEmpty(string ext1, string ext2)
{
if (String.IsNullOrEmpty(ext1) && !String.IsNullOrEmpty(ext2))
+ {
return -1;
+ }
else if (String.IsNullOrEmpty(ext2) && !String.IsNullOrEmpty(ext1))
+ {
return 1;
+ }
else
+ {
return 0;
+ }
}
public void Add(Enum e)
{
int ret = Name.CompareTo(other.Name);
if (ret == 0)
+ {
ret = Parameters.CompareTo(other.Parameters);
+ }
if (ret == 0)
+ {
ret = ReturnType.CompareTo(other.ReturnType);
+ }
return ret;
}
}
public void Unindent()
{
if (indent.Length > 4)
+ {
indent = indent.Substring(4);
+ }
else
+ {
indent = String.Empty;
+ }
}
new public void Add(string s)
public override string ToString()
{
if (Count == 0)
+ {
return String.Empty;
+ }
StringBuilder sb = new StringBuilder(Count);
: base(p)
{
if (p == null)
+ {
return;
+ }
Name = p.Name;
Unchecked = p.Unchecked;
{
int result = base.CompareTo(other);
if (result == 0)
+ {
result = Name.CompareTo(other.Name);
+ }
return result;
}
public ParameterCollection(IEnumerable<Parameter> parameters)
{
foreach (Parameter p in parameters)
+ {
Add(new Parameter(p));
+ }
}
private void BuildCache()
foreach (Parameter p in this)
{
if (p.Pointer != 0 || p.CurrentType.Contains("IntPtr"))
+ {
hasPointerParameters = true;
+ }
if (p.Reference)
+ {
hasReferenceParameters = true;
+ }
if (p.Unsigned)
+ {
hasUnsignedParameters = true;
+ }
if (p.Generic)
+ {
hasGenericParameters = true;
+ }
}
}
sb.Replace(", ", ")", sb.Length - 2, 2);
}
else
+ {
sb.Append(")");
+ }
return sb.ToString();
}
public bool ContainsType(string type)
{
foreach (Parameter p in this)
+ {
if (p.CurrentType == type)
+ {
return true;
+ }
+ }
return false;
}
{
int result = this[i].CompareTo(other[i]);
if (result != 0)
+ {
return result;
+ }
}
return 0;
}
public bool Equals(ParameterCollection other)
{
if (Count != other.Count)
+ {
return false;
+ }
bool result = true;
for (int i = 0; i < Count && result; i++)
set
{
if (String.IsNullOrEmpty(value))
+ {
throw new ArgumentNullException();
+ }
int qualifier_end = value.LastIndexOf('.');
if (qualifier_end > -1)
set
{
if (String.IsNullOrEmpty(value))
+ {
throw new ArgumentException();
+ }
if (!String.IsNullOrEmpty(type))
+ {
PreviousType = type;
+ }
if (!String.IsNullOrEmpty(value))
+ {
type = value.Trim();
+ }
while (type.EndsWith("*"))
{
// DelegateCollection.Add that depends on this fact.
int result = this.CurrentType.CompareTo(other.CurrentType);
if (result == 0)
+ {
result = Pointer.CompareTo(other.Pointer); // Must come after array/ref, see issue [#1098]
+ }
if (result == 0)
+ {
result = Reference.CompareTo(other.Reference);
+ }
if (result == 0)
+ {
result = Array.CompareTo(other.Array);
+ }
// Note: CLS-compliance and element counts
// are used for comparison calculations, in order
// to maintain a stable sorting order, even though
// they are not used in equality calculations.
if (result == 0)
+ {
result = CLSCompliant.CompareTo(other.CLSCompliant);
+ }
if (result == 0)
+ {
result = ElementCount.CompareTo(other.ElementCount);
+ }
return result;
}
internal static StreamReader OpenSpecFile(string folder, string file)
{
if (String.IsNullOrEmpty(folder) || String.IsNullOrEmpty(file))
+ {
return null;
+ }
Console.WriteLine(folder);
Console.WriteLine(file);
public XmlSpecReader(Settings settings)
{
if (settings == null)
+ {
throw new ArgumentNullException("settings");
+ }
Settings = settings;
}
foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_delete))
{
foreach (XPathNavigator node in nav.SelectChildren("function", String.Empty))
+ {
delegates.Remove(node.GetAttribute("name", String.Empty));
+ }
}
foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_add))
{
foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_delete))
{
foreach (XPathNavigator node in nav.SelectChildren("enum", String.Empty))
+ {
enums.Remove(node.GetAttribute("name", String.Empty));
+ }
}
foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_add))
{
Dictionary<string, string> GLTypes = new Dictionary<string, string>();
if (sr == null)
+ {
return GLTypes;
+ }
do
{
string line = sr.ReadLine();
if (String.IsNullOrEmpty(line) || line.StartsWith("#"))
+ {
continue;
+ }
string[] words = line.Split(" ,*\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
{
string line = sr.ReadLine();
if (String.IsNullOrEmpty(line) || line.StartsWith("#"))
+ {
continue;
+ }
string[] words = line.Split(" ,\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (words.Length < 2)
+ {
continue;
+ }
if (((Settings.Compatibility & Settings.Legacy.NoBoolParameters) != Settings.Legacy.None) && words[1] == "bool")
+ {
words[1] = "Int32";
+ }
CSTypes.Add(words[0], words[1]);
}
// so we add them anyway (which is desirable).
if (!String.IsNullOrEmpty(version) && !String.IsNullOrEmpty(apiversion) &&
Decimal.Parse(version) > Decimal.Parse(apiversion))
+ {
continue;
+ }
// Check whether we are adding to an existing delegate or creating a new one.
var d = new Delegate
Obsolete = node.GetAttribute("obsolete", String.Empty).Trim()
};
if (!extensions.Contains(d.Extension))
+ {
extensions.Add(d.Extension);
+ }
foreach (XPathNavigator param in node.SelectChildren(XPathNodeType.Element))
{
e.Obsolete = node.GetAttribute("obsolete", String.Empty).Trim();
if (String.IsNullOrEmpty(e.Name))
+ {
throw new InvalidOperationException(String.Format("Empty name for enum element {0}", node.ToString()));
+ }
// It seems that all flag collections contain "Mask" in their names.
// This looks like a heuristic, but it holds 100% in practice
var version = (e.Attribute("version") ?? new XAttribute("version", String.Empty)).Value;
var key = name + version;
if (!elements.ContainsKey(key))
+ {
elements.Add(key, e);
+ }
else
+ {
elements[key].Add(e.Elements());
+ }
}
return elements.Values;
{
var api = (e.Attribute("api") ?? new XAttribute("api", "default")).Value;
if (!enums.ContainsKey(api))
+ {
enums.Add(api, new SortedDictionary<string, string>());
+ }
enums[api].Add(
TrimName(e.Attribute("name").Value),
{
var key = apiname + version;
if (!APIs.ContainsKey(key))
+ {
APIs.Add(
key,
new XElement(
"api",
new XAttribute("name", apiname),
String.IsNullOrEmpty(version) ? null : new XAttribute("version", version)));
+ }
var api = APIs[key];
var enum_name = TrimName(feature.Attribute("name").Value);
var key = apiname + cmd_version;
if (!APIs.ContainsKey(key))
+ {
APIs.Add(
key,
new XElement(
- "api",
- new XAttribute("name", apiname),
- new XAttribute("version", cmd_version)));
+ "api",
+ new XAttribute("name", apiname),
+ new XAttribute("version", cmd_version)));
+ }
var api = APIs[key];
foreach (var command in feature.Elements("require").Elements("command"))
ExtensionRegex.Match(cmd_name).Value ??
(feature.Name == "extension" ? category.Substring(0, category.IndexOf("_")) : "Core");
if (String.IsNullOrEmpty(cmd_extension))
+ {
cmd_extension = "Core";
+ }
XElement function = TranslateCommand(commands[cmd_name]);
function.Add(new XAttribute("category", cmd_category));
function.Add(new XAttribute("extension", cmd_extension));
if (!String.IsNullOrEmpty(cmd_version))
+ {
function.Add(new XAttribute("version", cmd_version));
+ }
Merge(api, function);
}
// Sanity check: one function cannot belong to two different extensions
if (f.Attribute("extension").Value != function.Attribute("extension").Value)
+ {
throw new InvalidOperationException("Different extensions for the same function");
-
+ }
}
else
{
{
var words = ret.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (words[0] == "struct" || words[0] == "const")
- words[1] = group.Value;
+ {
+ words[1] = @group.Value;
+ }
else
- words[0] = group.Value;
+ {
+ words[0] = @group.Value;
+ }
ret = String.Join(" ", words);
}
private static string Join(string left, string right)
{
if (!String.IsNullOrEmpty(left) && !String.IsNullOrEmpty(right))
+ {
return left + "|" + right;
+ }
else if (!String.IsNullOrEmpty(left))
+ {
return left;
+ }
else if (!String.IsNullOrEmpty(right))
+ {
return right;
+ }
else
+ {
return String.Empty;
+ }
}
private static XAttribute Lookup(IDictionary<string, XElement> categories, string cmd_name, string attribute)
foreach (var e in entries)
{
if (e.Value.Name.LocalName != "enum")
+ {
continue;
+ }
var tokens = e.Value.Elements()
.OrderBy(t => (string)t.Attribute("name"))
.ToList();
public string TrimName(string name)
{
if (name.StartsWith(EnumPrefix))
+ {
return name.Remove(0, EnumPrefix.Length);
+ }
else if (name.StartsWith(FuncPrefix))
+ {
return name.Remove(0, FuncPrefix.Length);
+ }
else
+ {
return name;
+ }
}
}
}
{
// Pretend there is no slots if we want to force everything to work through DllImport (Android & iOS)
if (dllimport)
+ {
return -1;
+ }
var slot_attribute = signature.CustomAttributes
.FirstOrDefault(a => a.AttributeType.Name == "SlotAttribute");
byte retval = _aglSetCurrentContext(context);
if (retval != 0)
+ {
return true;
+ }
else
+ {
return false;
+ }
}
[DllImport(agl)] internal static extern AGLContext aglGetCurrentContext();
int[] glrect = new int[4];
if (XOffset != null)
+ {
glrect[0] = rect.X + XOffset();
+ }
else
+ {
glrect[0] = rect.X;
+ }
if (YOffset != null)
+ {
glrect[1] = rect.Y + YOffset();
+ }
else
+ {
glrect[1] = rect.Y;
+ }
glrect[2] = rect.Width;
glrect[3] = rect.Height;
Agl.AglError err = Agl.GetError();
if (err != Agl.AglError.NoError)
+ {
throw new Exception(String.Format(
"AGL Error from function {0}: {1} {2}",
function, err, Agl.ErrorString(err)));
+ }
}
private bool firstSwap = true;
public void MakeCurrent(IWindowInfo window)
{
if (Agl.aglSetCurrentContext(Context.Handle) == false)
+ {
MyAGLReportError("aglSetCurrentContext");
+ }
}
public bool IsCurrent
set
{
if (!Agl.aglSetInteger(Context.Handle, Agl.ParameterNames.AGL_SWAP_INTERVAL, ref value))
+ {
MyAGLReportError("aglSetInteger");
+ }
}
}
private void Dispose(bool disposing)
{
if (IsDisposed || Context.Handle == IntPtr.Zero)
+ {
return;
+ }
Debug.Print("Disposing of AGL context.");
Agl.aglSetCurrentContext(IntPtr.Zero);
public GLControl(GraphicsMode mode, int major, int minor, GraphicsContextFlags flags)
{
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
// SDL does not currently support embedding
// on external windows. If Open.Toolkit is not yet
private void ValidateState()
{
if (IsDisposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (!IsHandleCreated)
+ {
CreateControl();
+ }
if (implementation == null || context == null || context.IsDisposed)
+ {
RecreateHandle();
+ }
}
/// <summary>
protected override void OnHandleCreated(EventArgs e)
{
if (context != null)
+ {
context.Dispose();
+ }
if (implementation != null)
+ {
implementation.WindowInfo.Dispose();
+ }
if (design_mode)
+ {
implementation = new DummyGLControl();
+ }
else
+ {
implementation = new GLControlFactory().CreateGLControl(format, this);
+ }
context = implementation.CreateContext(major, minor, flags);
MakeCurrent();
if (!design_mode)
+ {
((IGraphicsContextInternal)Context).LoadAll();
+ }
// Deferred setting of vsync mode. See VSync property for more information.
if (initial_vsync_value.HasValue)
ValidateState();
if (design_mode)
+ {
e.Graphics.Clear(BackColor);
+ }
base.OnPaint(e);
}
BeginInvoke(delay); //Need the native window to resize first otherwise our control will be in the wrong place.
}
else if (context != null)
+ {
context.Update (Implementation.WindowInfo);
+ }
base.OnResize(e);
}
public void PerformContextUpdate()
{
if (context != null)
+ {
context.Update (Implementation.WindowInfo);
+ }
}
/// <summary>
protected override void OnParentChanged(EventArgs e)
{
if (context != null)
+ {
context.Update(Implementation.WindowInfo);
+ }
base.OnParentChanged(e);
}
public IGLControl CreateGLControl(GraphicsMode mode, Control control)
{
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
if (control == null)
+ {
throw new ArgumentNullException("control");
+ }
- if (Configuration.RunningOnSdl2) return new Sdl2GLControl(mode, control);
- else if (Configuration.RunningOnWindows) return new WinGLControl(mode, control);
- else if (Configuration.RunningOnMacOS) return new CarbonGLControl(mode, control);
- else if (Configuration.RunningOnX11) return new X11GLControl(mode, control);
- else throw new PlatformNotSupportedException();
+ if (Configuration.RunningOnSdl2)
+ {
+ return new Sdl2GLControl(mode, control);
+ }
+ else if (Configuration.RunningOnWindows)
+ {
+ return new WinGLControl(mode, control);
+ }
+ else if (Configuration.RunningOnMacOS)
+ {
+ return new CarbonGLControl(mode, control);
+ }
+ else if (Configuration.RunningOnX11)
+ {
+ return new X11GLControl(mode, control);
+ }
+ else
+ {
+ throw new PlatformNotSupportedException();
+ }
}
}
}
{
symbol = NSLookupAndBindSymbol(function);
if (symbol != IntPtr.Zero)
+ {
symbol = NSAddressOfSymbol(symbol);
+ }
}
return symbol;
}
internal X11GLControl(GraphicsMode mode, Control control)
{
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
if (control == null)
+ {
throw new ArgumentNullException("control");
+ }
// Note: the X11 window is created with a default XVisualInfo,
// that is not necessarily compatible with the desired GraphicsMode.
mode.Buffers,
mode.Stereo);
- if (xplatui == null) throw new PlatformNotSupportedException(
+ if (xplatui == null)
+ {
+ throw new PlatformNotSupportedException(
"System.Windows.Forms.XplatUIX11 missing. Unsupported platform or Mono runtime version, aborting.");
+ }
// get the required handles from the X11 API.
display = (IntPtr)GetStaticFieldValue(xplatui, "DisplayHandle");
private static void OnGraphicsContextInitialized()
{
if (GraphicsContextInitialized != null)
+ {
GraphicsContextInitialized(null, EventArgs.Empty);
+ }
}
/// <summary>
private static void OnGraphicsContextShuttingDown()
{
if (GraphicsContextShuttingDown != null)
+ {
GraphicsContextShuttingDown(null, EventArgs.Empty);
+ }
}
/// <summary>
protected virtual void OnInitialized()
{
if (Initialized != null)
+ {
Initialized(this, EventArgs.Empty);
+ }
}
/// <summary>
protected virtual void OnRenderFrame()
{
if (RenderFrame != null)
+ {
RenderFrame(this, EventArgs.Empty);
+ }
}
/// <summary>
protected virtual void OnShuttingDown()
{
if (ShuttingDown != null)
+ {
ShuttingDown(this, EventArgs.Empty);
+ }
}
#if GTK3
#endif
{
if (!_Initialized)
+ {
Initialize();
+ }
else
+ {
_GraphicsContext.MakeCurrent(_WindowInfo);
+ }
#if GTK3
var result = base.OnDrawn(cr);
bool result = base.OnConfigureEvent(evnt);
if (_GraphicsContext != null)
+ {
_GraphicsContext.Update(_WindowInfo);
+ }
return result;
}
ColorBPP = 32;
if (DepthBPP == 0)
+ {
DepthBPP = 16;
+ }
}
ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);
int buffers = 2;
if (SingleBuffer)
+ {
buffers--;
+ }
GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);
if (Configuration.RunningOnWindows)
+ {
Console.WriteLine("OpenTK running on windows");
+ }
else if (Configuration.RunningOnMacOS)
+ {
Console.WriteLine("OpenTK running on OSX");
+ }
else
+ {
Console.WriteLine("OpenTK running on X11");
+ }
#if GTK3
IntPtr widgetWindowHandle = this.Window.Handle;
// IWindowInfo
if (Configuration.RunningOnWindows)
+ {
_WindowInfo = WinWindowsInfoInitializer.Initialize(widgetWindowHandle);
+ }
else if (Configuration.RunningOnMacOS)
+ {
_WindowInfo = OSXWindowInfoInitializer.Initialize(widgetWindowHandle);
+ }
else
+ {
_WindowInfo = XWindowInfoInitializer.Initialize(graphicsMode, this.Display.Handle, this.Screen.Number, widgetWindowHandle, this.Screen.RootWindow.Handle);
+ }
// GraphicsContext
_GraphicsContext = new GraphicsContext(graphicsMode, _WindowInfo, GlVersionMajor, GlVersionMinor, GraphicsContextFlags);
public AudioCapture(string deviceName, int frequency, ALFormat sampleFormat, int bufferSize)
{
if (!AudioDeviceEnumerator.IsOpenALSupported)
+ {
throw new DllNotFoundException("openal32.dll");
+ }
if (frequency <= 0)
+ {
throw new ArgumentOutOfRangeException("frequency");
+ }
if (bufferSize <= 0)
+ {
throw new ArgumentOutOfRangeException("bufferSize");
+ }
// Try to open specified device. If it fails, try to open default device.
CurrentDevice = deviceName;
where TBuffer : struct
{
if (buffer == null)
+ {
throw new ArgumentNullException("buffer");
+ }
int buffer_size = BlittableValueType<TBuffer>.Stride * buffer.Length;
// This is more of a heuristic than a 100% valid check. However, it will work
// be produced with compressed sample formats (which are very rare).
// Still, this is better than no check at all.
if (sampleCount * GetSampleSize(SampleFormat) > buffer_size)
+ {
throw new ArgumentOutOfRangeException("sampleCount");
+ }
GCHandle buffer_ptr = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try { ReadSamples(buffer_ptr.AddrOfPinnedObject(), sampleCount); }
if (this.Handle != IntPtr.Zero)
{
if (this.IsRunning)
+ {
this.Stop();
+ }
Alc.CaptureCloseDevice(this.Handle);
}
private void CreateContext(string device, int freq, int refresh, bool sync, bool enableEfx, MaxAuxiliarySends efxAuxiliarySends)
{
if (!AudioDeviceEnumerator.IsOpenALSupported)
+ {
throw new DllNotFoundException("openal32.dll");
+ }
if (AudioDeviceEnumerator.Version == AudioDeviceEnumerator.AlcVersion.Alc1_1 && AudioDeviceEnumerator.AvailablePlaybackDevices.Count == 0) // Alc 1.0 does not support device enumeration.
+ {
throw new NotSupportedException("No audio hardware is available.");
- if (context_exists) throw new NotSupportedException("Multiple AudioContexts are not supported.");
- if (freq < 0) throw new ArgumentOutOfRangeException("freq", freq, "Should be greater than zero.");
- if (refresh < 0) throw new ArgumentOutOfRangeException("refresh", refresh, "Should be greater than zero.");
+ }
+ if (context_exists)
+ {
+ throw new NotSupportedException("Multiple AudioContexts are not supported.");
+ }
+ if (freq < 0)
+ {
+ throw new ArgumentOutOfRangeException("freq", freq, "Should be greater than zero.");
+ }
+ if (refresh < 0)
+ {
+ throw new ArgumentOutOfRangeException("refresh", refresh, "Should be greater than zero.");
+ }
if (!String.IsNullOrEmpty(device))
// an old OpenAL version is detect - it may affect outdated OpenAL versions different than OpenAL SI,
// but it looks like a good compromise for now.
if (AudioDeviceEnumerator.AvailablePlaybackDevices.Count > 0)
+ {
MakeCurrent();
+ }
CheckErrors();
lock (audio_context_lock)
{
if (!Alc.MakeContextCurrent(context != null ? context.context_handle : ContextHandle.Zero))
+ {
throw new AudioContextException(String.Format("ALC {0} error detected at {1}.",
Alc.GetError(context != null ? (IntPtr)context.context_handle : IntPtr.Zero).ToString(),
context != null ? context.ToString() : "null"));
+ }
}
}
lock (audio_context_lock)
{
if (available_contexts.Count == 0)
+ {
return false;
+ }
else
{
return AudioContext.CurrentContext == this;
}
set
{
- if (value) AudioContext.MakeCurrent(this);
- else AudioContext.MakeCurrent(null);
+ if (value)
+ {
+ AudioContext.MakeCurrent(this);
+ }
+ else
+ {
+ AudioContext.MakeCurrent(null);
+ }
}
}
public void CheckErrors()
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
new AudioDeviceErrorChecker(Device).Dispose();
}
get
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
return Alc.GetError(Device);
}
public void MakeCurrent()
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
AudioContext.MakeCurrent(this);
}
get
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
return is_processing;
}
get
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
return is_synchronized;
}
public void Process()
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
Alc.ProcessContext(this.context_handle);
IsProcessing = true;
public void Suspend()
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
Alc.SuspendContext(this.context_handle);
IsProcessing = false;
public bool SupportsExtension(string extension)
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
return Alc.IsExtensionPresent(this.Device, extension);
}
get
{
if (disposed)
+ {
throw new ObjectDisposedException(this.GetType().FullName);
+ }
return device_name;
}
lock (audio_context_lock)
{
if (available_contexts.Count == 0)
+ {
return null;
+ }
else
{
AudioContext context;
if (!disposed)
{
if (this.IsCurrent)
+ {
this.IsCurrent = false;
+ }
if (context_handle != ContextHandle.Zero)
{
}
if (Device != IntPtr.Zero)
+ {
Alc.CloseDevice(Device);
+ }
if (manual)
{
}
AlcError playback_err = Alc.GetError(dummy_device);
if (playback_err != AlcError.NoError)
+ {
throw new AudioContextException("Alc Error occured when querying available playback devices. " + playback_err.ToString());
+ }
// Get a list of all known recording devices, at least ALC_ENUMERATION_EXT is needed too
if (Version == AlcVersion.Alc1_1 && Alc.IsExtensionPresent(IntPtr.Zero, "ALC_EXT_CAPTURE"))
}
AlcError record_err = Alc.GetError(dummy_device);
if (record_err != AlcError.NoError)
+ {
throw new AudioContextException("Alc Error occured when querying available recording devices. " + record_err.ToString());
+ }
#if DEBUG
Debug.WriteLine("Found playback devices:");
foreach (string s in available_playback_devices)
+ {
Debug.WriteLine(s);
+ }
Debug.WriteLine("Default playback device: " + DefaultPlaybackDevice);
Debug.WriteLine("Found recording devices:");
foreach (string s in available_recording_devices)
+ {
Debug.WriteLine(s);
+ }
Debug.WriteLine("Default recording device: " + DefaultRecordingDevice);
#endif
// clean up the dummy context
Alc.MakeContextCurrent(ContextHandle.Zero);
if (dummy_context != ContextHandle.Zero && dummy_context.Handle != IntPtr.Zero)
+ {
Alc.DestroyContext(dummy_context);
+ }
if (dummy_device != IntPtr.Zero)
+ {
Alc.CloseDevice(dummy_device);
+ }
}
catch
{
public AudioDeviceErrorChecker(IntPtr device)
{
if (device == IntPtr.Zero)
+ {
throw new AudioDeviceException();
+ }
Device = device;
}
[CLSCompliant(false)]
public static void DeleteSources(uint[] sources)
{
- if (sources == null) throw new ArgumentNullException();
- if (sources.Length == 0) throw new ArgumentOutOfRangeException();
+ if (sources == null)
+ {
+ throw new ArgumentNullException();
+ }
+ if (sources.Length == 0)
+ {
+ throw new ArgumentOutOfRangeException();
+ }
DeleteBuffers(sources.Length, ref sources[0]);
}
/// <param name="sources">An array of source names identifying the sources to be deleted.</param>
public static void DeleteSources(int[] sources)
{
- if (sources == null) throw new ArgumentNullException();
- if (sources.Length == 0) throw new ArgumentOutOfRangeException();
+ if (sources == null)
+ {
+ throw new ArgumentNullException();
+ }
+ if (sources.Length == 0)
+ {
+ throw new ArgumentOutOfRangeException();
+ }
DeleteBuffers(sources.Length, ref sources[0]);
}
/// <param name="numEntries">The number of buffers to be unqueued.</param>
public static int[] SourceUnqueueBuffers(int sid, int numEntries)
{
- if (numEntries <= 0) throw new ArgumentOutOfRangeException("numEntries", "Must be greater than zero.");
+ if (numEntries <= 0)
+ {
+ throw new ArgumentOutOfRangeException("numEntries", "Must be greater than zero.");
+ }
int[] buf = new int[numEntries];
SourceUnqueueBuffers(sid, numEntries, buf);
return buf;
[CLSCompliant(false)]
public static void DeleteBuffers(uint[] buffers)
{
- if (buffers == null) throw new ArgumentNullException();
- if (buffers.Length == 0) throw new ArgumentOutOfRangeException();
+ if (buffers == null)
+ {
+ throw new ArgumentNullException();
+ }
+ if (buffers.Length == 0)
+ {
+ throw new ArgumentOutOfRangeException();
+ }
DeleteBuffers(buffers.Length, ref buffers[0]);
}
/// <param name="buffers">Pointer to an array of buffer names identifying the buffers to be deleted.</param>
public static void DeleteBuffers(int[] buffers)
{
- if (buffers == null) throw new ArgumentNullException();
- if (buffers.Length == 0) throw new ArgumentOutOfRangeException();
+ if (buffers == null)
+ {
+ throw new ArgumentNullException();
+ }
+ if (buffers.Length == 0)
+ {
+ throw new ArgumentOutOfRangeException();
+ }
DeleteBuffers(buffers.Length, ref buffers[0]);
}
where TBuffer : struct
{
if (!BlittableValueType.Check(buffer))
+ {
throw new ArgumentException("buffer");
+ }
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try { BufferData(bid, format, handle.AddrOfPinnedObject(), size, freq); }
/// </remarks>
public int[] GenEffects(int n)
{
- if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ if (n <= 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ }
int[] effects = new int[n];
GenEffects(n, out effects[0]);
return effects;
/// <param name="effects">Pointer to n Effect object identifiers.</param>
public void DeleteEffects(int[] effects)
{
- if (effects == null) throw new ArgumentNullException("effects");
+ if (effects == null)
+ {
+ throw new ArgumentNullException("effects");
+ }
DeleteEffects(effects.Length, ref effects[0]);
}
[CLSCompliant(false)]
public void DeleteEffects(uint[] effects)
{
- if (effects == null) throw new ArgumentNullException("effects");
+ if (effects == null)
+ {
+ throw new ArgumentNullException("effects");
+ }
DeleteEffects(effects.Length, ref effects[0]);
}
public int[] GenFilters(int n)
{
- if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ if (n <= 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ }
int[] filters = new int[n];
GenFilters(filters.Length, out filters[0]);
return filters;
[CLSCompliant(false)]
public void DeleteFilters(uint[] filters)
{
- if (filters == null) throw new ArgumentNullException("filters");
+ if (filters == null)
+ {
+ throw new ArgumentNullException("filters");
+ }
DeleteFilters(filters.Length, ref filters[0]);
}
/// <param name="filters">Pointer to an filter name/handle identifying the Filter Object to be deleted.</param>
public void DeleteFilters(int[] filters)
{
- if (filters == null) throw new ArgumentNullException("filters");
+ if (filters == null)
+ {
+ throw new ArgumentNullException("filters");
+ }
DeleteFilters(filters.Length, ref filters[0]);
}
/// <returns>Pointer addressing sufficient memory to store n Effect Slot object identifiers.</returns>
public int[] GenAuxiliaryEffectSlots(int n)
{
- if (n <= 0) throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ if (n <= 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be higher than 0.");
+ }
int[] slots = new int[n];
GenAuxiliaryEffectSlots(slots.Length, out slots[0]);
return slots;
/// <param name="slots">Pointer to n Effect Slot object identifiers.</param>
public void DeleteAuxiliaryEffectSlots(int[] slots)
{
- if (slots == null) throw new ArgumentNullException("slots");
+ if (slots == null)
+ {
+ throw new ArgumentNullException("slots");
+ }
DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]);
}
[CLSCompliant(false)]
public void DeleteAuxiliaryEffectSlots(uint[] slots)
{
- if (slots == null) throw new ArgumentNullException("slots");
+ if (slots == null)
+ {
+ throw new ArgumentNullException("slots");
+ }
DeleteAuxiliaryEffectSlots(slots.Length, ref slots[0]);
}
IsInitialized = false;
if (AudioContext.CurrentContext == null)
+ {
throw new InvalidOperationException("AL.LoadAll() needs a current AudioContext.");
+ }
if (!AudioContext.CurrentContext.SupportsExtension("ALC_EXT_EFX"))
{
{ // Query if Extension supported and retrieve Tokens/Pointers if it is.
IsInitialized = false;
if (AL.IsExtensionPresent("EAX-RAM") == false)
+ {
return;
+ }
AL_EAX_RAM_SIZE = AL.GetEnumValue("AL_EAX_RAM_SIZE");
AL_EAX_RAM_FREE = AL.GetEnumValue("AL_EAX_RAM_FREE");
int tempresult = Imported_GetBufferMode(buffer, IntPtr.Zero); // IntPtr.Zero due to the parameter being unused/reserved atm
if (tempresult == AL_STORAGE_ACCESSIBLE)
+ {
return XRamStorage.Accessible;
+ }
if (tempresult == AL_STORAGE_HARDWARE)
+ {
return XRamStorage.Hardware;
+ }
// default:
return XRamStorage.Automatic;
}
protected static void MarshalPtrToStringBuilder(IntPtr ptr, StringBuilder sb)
{
if (ptr == IntPtr.Zero)
+ {
throw new ArgumentException("ptr");
+ }
if (sb == null)
+ {
throw new ArgumentNullException("sb");
+ }
sb.Length = 0;
for (int i = 0; ; i++)
public static bool Check(Type type)
{
if (!CheckStructLayoutAttribute(type))
+ {
Debug.Print("Warning: type {0} does not specify a StructLayoutAttribute with Pack=1. The memory layout of the struct may change between platforms.", type.Name);
+ }
return CheckType(type);
}
{
//Debug.Print("Checking type {0} (size: {1} bytes).", type.Name, Marshal.SizeOf(type));
if (type.IsPrimitive)
+ {
return true;
+ }
if (!type.IsValueType)
+ {
return false;
+ }
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Debug.Indent();
foreach (FieldInfo field in fields)
{
if (!CheckType(field.FieldType))
+ {
return false;
+ }
}
Debug.Unindent();
if ((attr == null) ||
(attr != null && attr.Length > 0 && attr[0].Value != LayoutKind.Explicit && attr[0].Pack != 1))
+ {
return false;
+ }
return true;
}
public static int StrideOf<T>(T type)
{
if (!Check(type))
+ {
throw new ArgumentException("type");
+ }
return BlittableValueType<T>.Stride;
}
public static int StrideOf<T>(T[] type)
{
if (!Check(type))
+ {
throw new ArgumentException("type");
+ }
return BlittableValueType<T>.Stride;
}
public static int StrideOf<T>(T[,] type)
{
if (!Check(type))
+ {
throw new ArgumentException("type");
+ }
return BlittableValueType<T>.Stride;
}
public static int StrideOf<T>(T[, ,] type)
{
if (!Check(type))
+ {
throw new ArgumentException("type");
+ }
return BlittableValueType<T>.Stride;
}
public override bool Equals(object obj)
{
if (obj is ContextHandle)
+ {
return this.Equals((ContextHandle)obj);
+ }
return false;
}
internal set
{
if (value && primary_display != null && primary_display != this)
+ {
primary_display.IsPrimary = false;
+ }
lock (display_lock)
{
primary = value;
if (value)
+ {
primary_display = this;
+ }
}
}
}
{
DisplayResolution resolution = FindResolution(width, height, bitsPerPixel, refreshRate);
if (resolution == null)
+ {
resolution = FindResolution(width, height, bitsPerPixel, 0);
+ }
if (resolution == null)
+ {
resolution = FindResolution(width, height, 0, 0);
+ }
if (resolution == null)
+ {
return current_resolution;
+ }
return resolution;
}
public void ChangeResolution(DisplayResolution resolution)
{
if (resolution == null)
+ {
this.RestoreResolution();
+ }
if (resolution == current_resolution)
+ {
return;
+ }
//effect.FadeOut();
if (implementation.TryChangeResolution(this, resolution))
{
if (OriginalResolution == null)
+ {
OriginalResolution = current_resolution;
+ }
current_resolution = resolution;
}
- else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to change resolution to {1}.",
+ else
+ {
+ throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to change resolution to {1}.",
this, resolution));
+ }
//effect.FadeIn();
}
current_resolution = OriginalResolution;
OriginalResolution = null;
}
- else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to restore resolution.", this));
+ else
+ {
+ throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to restore resolution.", this));
+ }
//effect.FadeIn();
}
internal DisplayResolution(int x, int y, int width, int height, int bitsPerPixel, float refreshRate)
{
// Refresh rate may be zero, since this information may not be available on some platforms.
- if (width <= 0) throw new ArgumentOutOfRangeException("width", "Must be greater than zero.");
- if (height <= 0) throw new ArgumentOutOfRangeException("height", "Must be greater than zero.");
- if (bitsPerPixel <= 0) throw new ArgumentOutOfRangeException("bitsPerPixel", "Must be greater than zero.");
- if (refreshRate < 0) throw new ArgumentOutOfRangeException("refreshRate", "Must be greater than, or equal to zero.");
+ if (width <= 0)
+ {
+ throw new ArgumentOutOfRangeException("width", "Must be greater than zero.");
+ }
+ if (height <= 0)
+ {
+ throw new ArgumentOutOfRangeException("height", "Must be greater than zero.");
+ }
+ if (bitsPerPixel <= 0)
+ {
+ throw new ArgumentOutOfRangeException("bitsPerPixel", "Must be greater than zero.");
+ }
+ if (refreshRate < 0)
+ {
+ throw new ArgumentOutOfRangeException("refreshRate", "Must be greater than, or equal to zero.");
+ }
this.bounds = new Rectangle(x, y, width, height);
this.BitsPerPixel = bitsPerPixel;
/// <returns>True if the System.Object is an equal DisplayResolution; false otherwise.</returns>
public override bool Equals(object obj)
{
- if (obj == null) return false;
+ if (obj == null)
+ {
+ return false;
+ }
if (this.GetType() == obj.GetType())
{
DisplayResolution res = (DisplayResolution)obj;
public static bool operator== (DisplayResolution left, DisplayResolution right)
{
if (((object)left) == null && ((object)right) == null)
+ {
return true;
+ }
else if ((((object)left) == null && ((object)right) != null) ||
(((object)left) != null && ((object)right) == null))
+ {
return false;
+ }
return left.Equals(right);
}
internal set
{
if (value <= 0)
+ {
throw new ArgumentOutOfRangeException();
+ }
elapsed = value;
}
}
try
{
if (updates_per_second < 0.0 || updates_per_second > 200.0)
+ {
throw new ArgumentOutOfRangeException("updates_per_second", updates_per_second,
- "Parameter should be inside the range [0.0, 200.0]");
+ "Parameter should be inside the range [0.0, 200.0]");
+ }
if (frames_per_second < 0.0 || frames_per_second > 200.0)
+ {
throw new ArgumentOutOfRangeException("frames_per_second", frames_per_second,
- "Parameter should be inside the range [0.0, 200.0]");
+ "Parameter should be inside the range [0.0, 200.0]");
+ }
if (updates_per_second != 0)
{
{
ProcessEvents();
if (Exists && !IsExiting)
+ {
DispatchUpdateAndRenderFrame(this, EventArgs.Empty);
+ }
else
+ {
return;
+ }
}
}
finally
{
EnsureUndisposed();
if (render_period == 0.0)
+ {
return 1.0;
+ }
return 1.0 / render_period;
}
}
{
EnsureUndisposed();
if (TargetRenderPeriod == 0.0)
+ {
return 0.0;
+ }
return 1.0 / TargetRenderPeriod;
}
set
{
TargetRenderPeriod = 1.0 / value;
}
- else Debug.Print("Target render frequency clamped to {0}Hz.", MaxFrequency);
+ else
+ {
+ Debug.Print("Target render frequency clamped to {0}Hz.", MaxFrequency);
+ }
}
}
{
target_render_period = value;
}
- else Debug.Print("Target render period clamped to 1.0 seconds.");
+ else
+ {
+ Debug.Print("Target render period clamped to 1.0 seconds.");
+ }
}
}
{
EnsureUndisposed();
if (TargetUpdatePeriod == 0.0)
+ {
return 0.0;
+ }
return 1.0 / TargetUpdatePeriod;
}
set
{
TargetUpdatePeriod = 1.0 / value;
}
- else Debug.Print("Target render frequency clamped to {0}Hz.", MaxFrequency);
+ else
+ {
+ Debug.Print("Target render frequency clamped to {0}Hz.", MaxFrequency);
+ }
}
}
{
target_update_period = value;
}
- else Debug.Print("Target update period clamped to 1.0 seconds.");
+ else
+ {
+ Debug.Print("Target update period clamped to 1.0 seconds.");
+ }
}
}
{
EnsureUndisposed();
if (update_period == 0.0)
+ {
return 1.0;
+ }
return 1.0 / update_period;
}
}
Debug.Print("Updating Context after setting WindowState to {0}", value);
if (Context != null)
+ {
Context.Update(WindowInfo);
+ }
}
}
/// <summary>
OnLoad(e);
}
- private void OnRenderFrameInternal(FrameEventArgs e) { if (Exists && !isExiting) OnRenderFrame(e); }
+ private void OnRenderFrameInternal(FrameEventArgs e) { if (Exists && !isExiting)
+ {
+ OnRenderFrame(e);
+ }
+ }
private void OnUnloadInternal(EventArgs e) { OnUnload(e); }
- private void OnUpdateFrameInternal(FrameEventArgs e) { if (Exists && !isExiting) OnUpdateFrame(e); }
+ private void OnUpdateFrameInternal(FrameEventArgs e) { if (Exists && !isExiting)
+ {
+ OnUpdateFrame(e);
+ }
+ }
private void OnWindowInfoChangedInternal(EventArgs e)
{
public override bool Equals(object obj)
{
if (!(obj is Color4))
+ {
return false;
+ }
return Equals((Color4)obj);
}
public ColorFormat(int bpp)
{
if (bpp < 0)
+ {
throw new ArgumentOutOfRangeException("bpp", "Must be greater or equal to zero.");
+ }
red = green = blue = alpha = 0;
BitsPerPixel = bpp;
IsIndexed = false;
public ColorFormat(int red, int green, int blue, int alpha)
{
if (red < 0 || green < 0 || blue < 0 || alpha < 0)
+ {
throw new ArgumentOutOfRangeException("Arguments must be greater or equal to zero.");
+ }
this.red = (byte)red;
this.green = (byte)green;
this.blue = (byte)blue;
this.BitsPerPixel = red + green + blue + alpha;
this.IsIndexed = false;
if (this.BitsPerPixel < 15 && this.BitsPerPixel != 0)
+ {
this.IsIndexed = true;
+ }
}
/// <summary>Gets the bits per pixel for the Red channel.</summary>
{
int result = BitsPerPixel.CompareTo(other.BitsPerPixel);
if (result != 0)
+ {
return result;
+ }
result = IsIndexed.CompareTo(other.IsIndexed);
if (result != 0)
+ {
return result;
+ }
result = Alpha.CompareTo(other.Alpha);
return result;
}
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
unsafe
{
fixed (Vector2* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector3* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector4* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Matrix4* ptr = &matrix)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
unsafe
{
fixed (Vector2* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector3* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector4* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Matrix4* ptr = &matrix)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
{
var context = GraphicsContext.CurrentContext as IGraphicsContextInternal;
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
return context != null ? context.GetAddress(funcname) : IntPtr.Zero;
}
IGraphicsContext context = GraphicsContext.CurrentContext;
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
IGraphicsContextInternal context_internal = context as IGraphicsContextInternal;
unsafe
{
bool designMode = false;
if (mode == null && window == null)
+ {
designMode = true;
- else if (mode == null) throw new ArgumentNullException("mode", "Must be a valid GraphicsMode.");
- else if (window == null) throw new ArgumentNullException("window", "Must point to a valid window.");
+ }
+ else if (mode == null)
+ {
+ throw new ArgumentNullException("mode", "Must be a valid GraphicsMode.");
+ }
+ else if (window == null)
+ {
+ throw new ArgumentNullException("window", "Must point to a valid window.");
+ }
// Silently ignore invalid major and minor versions.
if (major <= 0)
+ {
major = 1;
+ }
if (minor < 0)
+ {
minor = 0;
+ }
// Angle needs an embedded context
const GraphicsContextFlags useAngleFlag = GraphicsContextFlags.Angle
public GraphicsContext(ContextHandle handle, GetAddressDelegate getAddress, GetCurrentContextDelegate getCurrent)
{
if (getAddress == null || getCurrent == null)
+ {
throw new ArgumentNullException();
+ }
// Make sure OpenTK has been initialized.
// Fixes https://github.com/opentk/opentk/issues/52
// making this return null even if another valid context exists.
// The workaround is to simply ignore null targets.
if (target != null)
+ {
return target;
+ }
}
}
return null;
public static void Assert()
{
if (GraphicsContext.CurrentContext == null)
+ {
throw new GraphicsContextMissingException();
+ }
}
internal static GetCurrentContextDelegate GetCurrentContext;
{
ContextHandle handle = CurrentContextHandle;
if (handle.Handle != IntPtr.Zero)
+ {
return (IGraphicsContext)available_contexts[handle];
+ }
}
return null;
}
public void LoadAll()
{
if (GraphicsContext.CurrentContext != this)
+ {
throw new GraphicsContextException();
+ }
implementation.LoadAll();
}
{
Debug.Print("Disposing context {0}.", (this as IGraphicsContextInternal).Context.ToString());
if (implementation != null)
+ {
implementation.Dispose();
+ }
}
else
{
set
{
if (value && SwapInterval <= 0)
+ {
SwapInterval = 1;
+ }
else if (!value && SwapInterval > 0)
+ {
SwapInterval = 0;
+ }
}
}
internal GraphicsMode(IntPtr? index, ColorFormat color, int depth, int stencil, int samples, ColorFormat accum,
int buffers, bool stereo)
{
- if (depth < 0) throw new ArgumentOutOfRangeException("depth", "Must be greater than, or equal to zero.");
- if (stencil < 0) throw new ArgumentOutOfRangeException("stencil", "Must be greater than, or equal to zero.");
- if (buffers < 0) throw new ArgumentOutOfRangeException("buffers", "Must be greater than, or equal to zero.");
- if (samples < 0) throw new ArgumentOutOfRangeException("samples", "Must be greater than, or equal to zero.");
+ if (depth < 0)
+ {
+ throw new ArgumentOutOfRangeException("depth", "Must be greater than, or equal to zero.");
+ }
+ if (stencil < 0)
+ {
+ throw new ArgumentOutOfRangeException("stencil", "Must be greater than, or equal to zero.");
+ }
+ if (buffers < 0)
+ {
+ throw new ArgumentOutOfRangeException("buffers", "Must be greater than, or equal to zero.");
+ }
+ if (samples < 0)
+ {
+ throw new ArgumentOutOfRangeException("samples", "Must be greater than, or equal to zero.");
+ }
this.Index = index;
this.ColorFormat = color;
{
int result = x.ColorFormat.CompareTo(y.ColorFormat);
if (result != 0)
+ {
return result;
+ }
result = x.Depth.CompareTo(y.Depth);
if (result != 0)
+ {
return result;
+ }
result = x.Stencil.CompareTo(y.Stencil);
if (result != 0)
+ {
return result;
+ }
result = x.Samples.CompareTo(y.Samples);
if (result != 0)
+ {
return result;
+ }
result = x.Stereo.CompareTo(y.Stereo);
if (result != 0)
+ {
return result;
+ }
result = x.Buffers.CompareTo(y.Buffers);
if (result != 0)
+ {
return result;
+ }
return x.AccumulatorFormat.CompareTo(y.AccumulatorFormat);
}
}
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
unsafe
{
fixed (Vector2* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector3* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector4* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Matrix4* ptr = &matrix)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector2d* ptr = &vector)
+ {
GetDouble(pname, (double*)ptr);
+ }
}
}
unsafe
{
fixed (Vector3d* ptr = &vector)
+ {
GetDouble(pname, (double*)ptr);
+ }
}
}
unsafe
{
fixed (Vector4d* ptr = &vector)
+ {
GetDouble(pname, (double*)ptr);
+ }
}
}
unsafe
{
fixed (Matrix4d* ptr = &matrix)
+ {
GetDouble(pname, (double*)ptr);
+ }
}
}
public ErrorHelper(IGraphicsContext context)
{
if (context == null)
+ {
throw new GraphicsContextMissingException();
+ }
Context = (GraphicsContext)context;
lock (SyncRoot)
{
if (!ContextErrors.ContainsKey(Context))
+ {
ContextErrors.Add(Context, new List<ErrorCode>());
+ }
}
ResetErrors();
}
sb.Append(", ");
}
else
+ {
break;
+ }
}
sb.Remove(sb.Length - 2, 2); // Remove the last comma
unsafe
{
fixed (Vector2* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector3* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Vector4* ptr = &vector)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
unsafe
{
fixed (Matrix4* ptr = &matrix)
+ {
GetFloat(pname, (float*)ptr);
+ }
}
}
public static GamePadCapabilities GetCapabilities(int index)
{
if (index < 0)
+ {
throw new IndexOutOfRangeException();
+ }
return driver.GetCapabilities(index);
}
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (A == ButtonState.Pressed)
+ {
sb.Append("A");
+ }
if (B == ButtonState.Pressed)
+ {
sb.Append("B");
+ }
if (X == ButtonState.Pressed)
+ {
sb.Append("X");
+ }
if (Y == ButtonState.Pressed)
+ {
sb.Append("Y");
+ }
if (Back == ButtonState.Pressed)
+ {
sb.Append("Bk");
+ }
if (Start == ButtonState.Pressed)
+ {
sb.Append("St");
+ }
if (BigButton == ButtonState.Pressed)
+ {
sb.Append("Gd");
+ }
if (Back == ButtonState.Pressed)
+ {
sb.Append("Bk");
+ }
if (LeftShoulder == ButtonState.Pressed)
+ {
sb.Append("L");
+ }
if (RightShoulder == ButtonState.Pressed)
+ {
sb.Append("R");
+ }
if (LeftStick == ButtonState.Pressed)
+ {
sb.Append("Ls");
+ }
if (RightStick == ButtonState.Pressed)
+ {
sb.Append("Rs");
+ }
return sb.ToString();
}
internal JoystickCapabilities(int axis_count, int button_count, int hat_count, bool is_connected)
{
if (axis_count < 0 || axis_count > JoystickState.MaxAxes)
+ {
Debug.Print("[{0}] Axis count {1} out of range (0, {2})",
typeof(JoystickCapabilities).Name, axis_count, JoystickState.MaxAxes);
+ }
if (button_count < 0 || button_count > JoystickState.MaxButtons)
+ {
Debug.Print("[{0}] Button count {1} out of range (0, {2})",
typeof(JoystickCapabilities).Name, button_count, JoystickState.MaxButtons);
+ }
if (hat_count < 0 || hat_count > JoystickState.MaxHats)
+ {
Debug.Print("[{0}] Hat count {1} out of range (0, {2})",
typeof(JoystickCapabilities).Name, hat_count, JoystickState.MaxHats);
+ }
axis_count = MathHelper.Clamp(axis_count, 0, JoystickState.MaxAxes);
button_count = MathHelper.Clamp(button_count, 0, JoystickState.MaxButtons);
internal JoystickDevice(int id, int axes, int buttons)
{
if (axes < 0)
+ {
throw new ArgumentOutOfRangeException("axes");
+ }
if (buttons < 0)
+ {
throw new ArgumentOutOfRangeException("buttons");
+ }
Id = id;
Axis = new JoystickAxisCollection(axes);
button_args.Button = button;
Button[button] = button_args.Pressed = @value;
if (@value)
+ {
ButtonDown(this, button_args);
+ }
else
+ {
ButtonUp(this, button_args);
+ }
}
}
}
internal JoystickButtonCollection(int numButtons)
{
if (numButtons < 0)
+ {
throw new ArgumentOutOfRangeException("numButtons");
+ }
button_state = new bool[numButtons];
}
internal JoystickAxisCollection(int numAxes)
{
if (numAxes < 0)
+ {
throw new ArgumentOutOfRangeException("numAxes");
+ }
axis_state = new float[numAxes];
}
{
int index = axis;
if (index < 0 || index >= MaxAxes)
+ {
throw new ArgumentOutOfRangeException("axis");
+ }
unsafe
{
internal void SetButton(int button, bool value)
{
if (button < 0 || button >= MaxButtons)
+ {
throw new ArgumentOutOfRangeException("button");
+ }
if (value)
{
public static KeyboardState GetState(int index)
{
if (index < 0)
+ {
throw new ArgumentOutOfRangeException("index");
+ }
lock (SyncRoot)
{
{
int hashcode = 0;
for (int i = 0; i < NumInts; i++)
+ {
hashcode ^= (k + i)->GetHashCode();
+ }
return hashcode;
}
}
fixed (int* k1 = Keys)
{
for (int i = 0; i < NumInts; i++)
+ {
*(k1 + i) |= *(k2 + i);
+ }
}
}
IsConnected |= other.IsConnected;
private static void ValidateOffset(int offset)
{
if (offset < 0 || offset >= NumInts * IntSize)
+ {
throw new ArgumentOutOfRangeException();
+ }
}
/// <summary>
fixed (int* k1 = Keys)
{
for (int i = 0; equal && i < NumInts; i++)
+ {
equal &= *(k1 + i) == *(k2 + i);
+ }
}
}
return equal;
public static MouseState GetState(int index)
{
if (index < 0)
+ {
throw new ArgumentOutOfRangeException("index");
+ }
lock (SyncRoot)
{
internal void SetButton(MouseButton button, ButtonState state)
{
if (button < 0 || button > MouseButton.LastButton)
+ {
throw new ArgumentOutOfRangeException();
+ }
switch (state)
{
internal ButtonState GetButton(MouseButton button)
{
if (button < 0 || button > MouseButton.LastButton)
+ {
throw new ArgumentOutOfRangeException();
+ }
return
state.ReadBit((int)button) ?
internal set
{
if (value)
+ {
EnableBit((int)button);
+ }
else
+ {
DisableBit((int)button);
+ }
}
}
private static void ValidateOffset(int offset)
{
if (offset < 0 || offset >= 16)
+ {
throw new ArgumentOutOfRangeException("offset");
+ }
}
/// <summary>
public BezierCurve(IEnumerable<Vector2> points)
{
if (points == null)
+ {
throw new ArgumentNullException("points", "Must point to a valid list of Vector2 structures.");
+ }
this.points = new List<Vector2>(points);
this.Parallel = 0.0f;
public BezierCurve(params Vector2[] points)
{
if (points == null)
+ {
throw new ArgumentNullException("points", "Must point to a valid list of Vector2 structures.");
+ }
this.points = new List<Vector2>(points);
this.Parallel = 0.0f;
public BezierCurve(float parallel, params Vector2[] points)
{
if (points == null)
+ {
throw new ArgumentNullException("points", "Must point to a valid list of Vector2 structures.");
+ }
this.Parallel = parallel;
this.points = new List<Vector2>(points);
public BezierCurve(float parallel, IEnumerable<Vector2> points)
{
if (points == null)
+ {
throw new ArgumentNullException("points", "Must point to a valid list of Vector2 structures.");
+ }
this.Parallel = parallel;
this.points = new List<Vector2>(points);
}
if (parallel == 0.0f)
+ {
return r;
+ }
Vector2 perpendicular = new Vector2();
if (t != 0.0f)
+ {
perpendicular = r - BezierCurve.CalculatePointOfDerivative(points, t);
+ }
else
+ {
perpendicular = points[1] - points[0];
+ }
return r + Vector2.Normalize(perpendicular).PerpendicularRight * parallel;
}
+ EndAnchor.Y * t * t * t;
if (Parallel == 0.0f)
+ {
return r;
+ }
Vector2 perpendicular = new Vector2();
if (t == 0.0f)
+ {
perpendicular = FirstControlPoint - StartAnchor;
+ }
else
+ {
perpendicular = r - CalculatePointOfDerivative(t);
+ }
return r + Vector2.Normalize(perpendicular).PerpendicularRight * Parallel;
}
r.Y = (c * c * StartAnchor.Y) + (2 * t * c * ControlPoint.Y) + (t * t * EndAnchor.Y);
if (Parallel == 0.0f)
+ {
return r;
+ }
Vector2 perpendicular = new Vector2();
if (t == 0.0f)
+ {
perpendicular = ControlPoint - StartAnchor;
+ }
else
+ {
perpendicular = r - CalculatePointOfDerivative(t);
+ }
return r + Vector2.Normalize(perpendicular).PerpendicularRight * Parallel;
}
if (throwOnError)
{
// handle cases that cause overflow rather than silently ignoring it
- if (f > Half.MaxValue) throw new ArithmeticException("Half: Positive maximum value exceeded.");
- if (f < -Half.MaxValue) throw new ArithmeticException("Half: Negative minimum value exceeded.");
+ if (f > Half.MaxValue)
+ {
+ throw new ArithmeticException("Half: Positive maximum value exceeded.");
+ }
+ if (f < -Half.MaxValue)
+ {
+ throw new ArithmeticException("Half: Negative minimum value exceeded.");
+ }
// handle cases that make no sense
- if (Single.IsNaN(f)) throw new ArithmeticException("Half: Input is not a number (NaN).");
- if (Single.IsPositiveInfinity(f)) throw new ArithmeticException("Half: Input is positive infinity.");
- if (Single.IsNegativeInfinity(f)) throw new ArithmeticException("Half: Input is negative infinity.");
+ if (Single.IsNaN(f))
+ {
+ throw new ArithmeticException("Half: Input is not a number (NaN).");
+ }
+ if (Single.IsPositiveInfinity(f))
+ {
+ throw new ArithmeticException("Half: Input is positive infinity.");
+ }
+ if (Single.IsNegativeInfinity(f))
+ {
+ throw new ArithmeticException("Half: Input is negative infinity.");
+ }
}
}
}
// exponent overflow
- if (exponent > 30) throw new ArithmeticException("Half: Hardware floating-point overflow.");
+ if (exponent > 30)
+ {
+ throw new ArithmeticException("Half: Hardware floating-point overflow.");
+ }
// Assemble the half from S, E and M.
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
+ {
aInt = (short)(0x8000 - aInt);
+ }
// Make bInt lexicographically ordered as a twos-complement int
if (bInt < 0)
+ {
bInt = (short)(0x8000 - bInt);
+ }
short intDiff = System.Math.Abs((short)(aInt - bInt));
if (intDiff <= maxUlps)
+ {
return true;
+ }
return false;
}
/// <returns>The next power of two.</returns>
public static long NextPowerOfTwo(long n)
{
- if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ if (n < 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ }
return (long)System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2)));
}
/// <returns>The next power of two.</returns>
public static int NextPowerOfTwo(int n)
{
- if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ if (n < 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ }
return (int)System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2)));
}
/// <returns>The next power of two.</returns>
public static float NextPowerOfTwo(float n)
{
- if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ if (n < 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ }
return (float)System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2)));
}
/// <returns>The next power of two.</returns>
public static double NextPowerOfTwo(double n)
{
- if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ if (n < 0)
+ {
+ throw new ArgumentOutOfRangeException("n", "Must be positive.");
+ }
return System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2)));
}
long result = 1;
for (; n > 1; n--)
+ {
result *= n;
+ }
return result;
}
// we use longs here, otherwise we run into a two's complement problem, causing this to fail with -2 and 2.0
long aInt = FloatToInt32Bits(a);
if (aInt < 0)
+ {
aInt = Int32.MinValue - aInt;
+ }
long bInt = FloatToInt32Bits(b);
if (bInt < 0)
+ {
bInt = Int32.MinValue - bInt;
+ }
long intDiff = Math.Abs(aInt - bInt);
return intDiff <= (1 << maxDeltaBits);
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
float det = mat.Determinant;
if (det == 0)
+ {
throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
+ }
float invDet = 1f / det;
public override bool Equals(object obj)
{
if (!(obj is Matrix2))
+ {
return false;
+ }
return this.Equals((Matrix2)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
double det = mat.Determinant;
if (det == 0)
+ {
throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
+ }
double invDet = 1f / det;
public override bool Equals(object obj)
{
if (!(obj is Matrix2d))
+ {
return false;
+ }
return this.Equals((Matrix2d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix2x3))
+ {
return false;
+ }
return this.Equals((Matrix2x3)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix2x3d))
+ {
return false;
+ }
return this.Equals((Matrix2x3d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix2x4))
+ {
return false;
+ }
return this.Equals((Matrix2x4)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix2x4d))
+ {
return false;
+ }
return this.Equals((Matrix2x4d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
{
Matrix3 m = this;
if (m.Determinant != 0)
+ {
m.Invert();
+ }
return m;
}
float oneOverPivot = 1.0f / pivot;
inverse[icol, icol] = 1.0f;
for (int k = 0; k < 3; ++k)
+ {
inverse[icol, k] *= oneOverPivot;
+ }
for (int j = 0; j < 3; ++j)
{
float f = inverse[j, icol];
inverse[j, icol] = 0.0f;
for (int k = 0; k < 3; ++k)
+ {
inverse[j, k] -= inverse[icol, k] * f;
+ }
}
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3))
+ {
return false;
+ }
return this.Equals((Matrix3)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
{
Matrix3d m = this;
if (m.Determinant != 0)
+ {
m.Invert();
+ }
return m;
}
double oneOverPivot = 1.0 / pivot;
inverse[icol, icol] = 1.0;
for (int k = 0; k < 3; ++k)
+ {
inverse[icol, k] *= oneOverPivot;
+ }
for (int j = 0; j < 3; ++j)
{
double f = inverse[j, icol];
inverse[j, icol] = 0.0;
for (int k = 0; k < 3; ++k)
+ {
inverse[j, k] -= inverse[icol, k] * f;
+ }
}
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3d))
+ {
return false;
+ }
return this.Equals((Matrix3d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3x2))
+ {
return false;
+ }
return this.Equals((Matrix3x2)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3x2d))
+ {
return false;
+ }
return this.Equals((Matrix3x2d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3x4))
+ {
return false;
+ }
return this.Equals((Matrix3x4)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix3x4d))
+ {
return false;
+ }
return this.Equals((Matrix3x4d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
{
Matrix4 m = this;
if (m.Determinant != 0)
+ {
m.Invert();
+ }
return m;
}
public static void CreatePerspectiveFieldOfView(float fovy, float aspect, float zNear, float zFar, out Matrix4 result)
{
if (fovy <= 0 || fovy > Math.PI)
+ {
throw new ArgumentOutOfRangeException("fovy");
+ }
if (aspect <= 0)
+ {
throw new ArgumentOutOfRangeException("aspect");
+ }
if (zNear <= 0)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
if (zFar <= 0)
+ {
throw new ArgumentOutOfRangeException("zFar");
+ }
float yMax = zNear * (float)System.Math.Tan(0.5f * fovy);
float yMin = -yMax;
public static void CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float zNear, float zFar, out Matrix4 result)
{
if (zNear <= 0)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
if (zFar <= 0)
+ {
throw new ArgumentOutOfRangeException("zFar");
+ }
if (zNear >= zFar)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
float x = (2.0f * zNear) / (right - left);
float y = (2.0f * zNear) / (top - bottom);
float oneOverPivot = 1.0f / pivot;
inverse[icol, icol] = 1.0f;
for (int k = 0; k < 4; ++k)
+ {
inverse[icol, k] *= oneOverPivot;
+ }
// Do elimination of non-diagonal elements
for (int j = 0; j < 4; ++j)
float f = inverse[j, icol];
inverse[j, icol] = 0.0f;
for (int k = 0; k < 4; ++k)
+ {
inverse[j, k] -= inverse[icol, k] * f;
+ }
}
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4))
+ {
return false;
+ }
return this.Equals((Matrix4)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
{
Matrix4d m = this;
if (m.Determinant != 0)
+ {
m.Invert();
+ }
return m;
}
public static void CreatePerspectiveFieldOfView(double fovy, double aspect, double zNear, double zFar, out Matrix4d result)
{
if (fovy <= 0 || fovy > Math.PI)
+ {
throw new ArgumentOutOfRangeException("fovy");
+ }
if (aspect <= 0)
+ {
throw new ArgumentOutOfRangeException("aspect");
+ }
if (zNear <= 0)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
if (zFar <= 0)
+ {
throw new ArgumentOutOfRangeException("zFar");
+ }
double yMax = zNear * System.Math.Tan(0.5 * fovy);
double yMin = -yMax;
public static void CreatePerspectiveOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4d result)
{
if (zNear <= 0)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
if (zFar <= 0)
+ {
throw new ArgumentOutOfRangeException("zFar");
+ }
if (zNear >= zFar)
+ {
throw new ArgumentOutOfRangeException("zNear");
+ }
double x = (2.0 * zNear) / (right - left);
double y = (2.0 * zNear) / (top - bottom);
double oneOverPivot = 1.0 / pivot;
inverse[icol, icol] = 1.0;
for (int k = 0; k < 4; ++k)
+ {
inverse[icol, k] *= oneOverPivot;
+ }
// Do elimination of non-diagonal elements
for (int j = 0; j < 4; ++j)
double f = inverse[j, icol];
inverse[j, icol] = 0.0;
for (int k = 0; k < 4; ++k)
+ {
inverse[j, k] -= inverse[icol, k] * f;
+ }
}
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4d))
+ {
return false;
+ }
return this.Equals((Matrix4d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4x2))
+ {
return false;
+ }
return this.Equals((Matrix4x2)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4x2d))
+ {
return false;
+ }
return this.Equals((Matrix4x2d)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4x3))
+ {
return false;
+ }
return this.Equals((Matrix4x3)obj);
}
{
get
{
- if (rowIndex == 0) return Row0[columnIndex];
- else if (rowIndex == 1) return Row1[columnIndex];
- else if (rowIndex == 2) return Row2[columnIndex];
- else if (rowIndex == 3) return Row3[columnIndex];
+ if (rowIndex == 0)
+ {
+ return Row0[columnIndex];
+ }
+ else if (rowIndex == 1)
+ {
+ return Row1[columnIndex];
+ }
+ else if (rowIndex == 2)
+ {
+ return Row2[columnIndex];
+ }
+ else if (rowIndex == 3)
+ {
+ return Row3[columnIndex];
+ }
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
- if (rowIndex == 0) Row0[columnIndex] = value;
- else if (rowIndex == 1) Row1[columnIndex] = value;
- else if (rowIndex == 2) Row2[columnIndex] = value;
- else if (rowIndex == 3) Row3[columnIndex] = value;
- else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ if (rowIndex == 0)
+ {
+ Row0[columnIndex] = value;
+ }
+ else if (rowIndex == 1)
+ {
+ Row1[columnIndex] = value;
+ }
+ else if (rowIndex == 2)
+ {
+ Row2[columnIndex] = value;
+ }
+ else if (rowIndex == 3)
+ {
+ Row3[columnIndex] = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Matrix4x3d))
+ {
return false;
+ }
return this.Equals((Matrix4x3d)obj);
}
{
Quaternion q = this;
if (Math.Abs(q.W) > 1.0f)
+ {
q.Normalize();
+ }
Vector4 result = new Vector4();
public static Quaternion FromAxisAngle(Vector3 axis, float angle)
{
if (axis.LengthSquared == 0.0f)
+ {
return Identity;
+ }
Quaternion result = Identity;
Quaternion result = new Quaternion(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W);
if (result.LengthSquared > 0.0f)
+ {
return Normalize(result);
+ }
else
+ {
return Identity;
+ }
}
/// <summary>
/// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns>
public override bool Equals(object other)
{
- if (other is Quaternion == false) return false;
- return this == (Quaternion)other;
+ if (other is Quaternion == false)
+ {
+ return false;
+ }
+ return this == (Quaternion)other;
}
/// <summary>
{
Quaterniond q = this;
if (Math.Abs(q.W) > 1.0f)
+ {
q.Normalize();
+ }
Vector4d result = new Vector4d();
public static Quaterniond FromAxisAngle(Vector3d axis, double angle)
{
if (axis.LengthSquared == 0.0f)
+ {
return Identity;
+ }
Quaterniond result = Identity;
Quaterniond result = new Quaterniond(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W);
if (result.LengthSquared > 0.0f)
+ {
return Normalize(result);
+ }
else
+ {
return Identity;
+ }
}
/// <summary>
/// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns>
public override bool Equals(object other)
{
- if (other is Quaterniond == false) return false;
+ if (other is Quaterniond == false)
+ {
+ return false;
+ }
return this == (Quaterniond)other;
}
/// </summary>
public float this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector2))
+ {
return false;
+ }
return this.Equals((Vector2)obj);
}
/// </summary>
public double this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector2d))
+ {
return false;
+ }
return this.Equals((Vector2d)obj);
}
/// </summary>
public float this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
- else if(index == 2) return Z;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
+ else if(index == 2)
+ {
+ return Z;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else if(index == 2) Z = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else if(index == 2)
+ {
+ Z = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector3))
+ {
return false;
+ }
return this.Equals((Vector3)obj);
}
/// </summary>
public double this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
- else if(index == 2) return Z;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
+ else if(index == 2)
+ {
+ return Z;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else if(index == 2) Z = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else if(index == 2)
+ {
+ Z = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector3d))
+ {
return false;
+ }
return this.Equals((Vector3d)obj);
}
/// </summary>
public float this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
- else if(index == 2) return Z;
- else if(index == 3) return W;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
+ else if(index == 2)
+ {
+ return Z;
+ }
+ else if(index == 3)
+ {
+ return W;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else if(index == 2) Z = value;
- else if(index == 3) W = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else if(index == 2)
+ {
+ Z = value;
+ }
+ else if(index == 3)
+ {
+ W = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector4))
+ {
return false;
+ }
return this.Equals((Vector4)obj);
}
/// </summary>
public double this[int index] {
get{
- if(index == 0) return X;
- else if(index == 1) return Y;
- else if(index == 2) return Z;
- else if(index == 3) return W;
+ if(index == 0)
+ {
+ return X;
+ }
+ else if(index == 1)
+ {
+ return Y;
+ }
+ else if(index == 2)
+ {
+ return Z;
+ }
+ else if(index == 3)
+ {
+ return W;
+ }
throw new IndexOutOfRangeException("You tried to access this vector at index: " + index);
} set{
- if(index == 0) X = value;
- else if(index == 1) Y = value;
- else if(index == 2) Z = value;
- else if(index == 3) W = value;
- else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ if(index == 0)
+ {
+ X = value;
+ }
+ else if(index == 1)
+ {
+ Y = value;
+ }
+ else if(index == 2)
+ {
+ Z = value;
+ }
+ else if(index == 3)
+ {
+ W = value;
+ }
+ else
+ {
+ throw new IndexOutOfRangeException("You tried to set this vector at index: " + index);
+ }
}
}
public override bool Equals(object obj)
{
if (!(obj is Vector4d))
+ {
return false;
+ }
return this.Equals((Vector4d)obj);
}
: base(width, height, data)
{
if (hotx < 0 || hotx >= Width || hoty < 0 || hoty >= Height)
+ {
throw new ArgumentOutOfRangeException();
+ }
X = hotx;
Y = hoty;
: base(width, height, data)
{
if (hotx < 0 || hotx >= Width || hoty < 0 || hoty >= Height)
+ {
throw new ArgumentOutOfRangeException();
+ }
X = hotx;
Y = hoty;
{
// TODO: Should a constraint be added for the position?
if (width < 1)
+ {
throw new ArgumentOutOfRangeException("width", "Must be greater than zero.");
+ }
if (height < 1)
+ {
throw new ArgumentOutOfRangeException("height", "Must be greater than zero.");
+ }
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
this.options = options;
this.device = device;
/// </exception>
protected void EnsureUndisposed()
{
- if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
+ if (IsDisposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
}
/// <summary>
{
throw new InvalidOperationException("ProcessEvents must be called on the same thread that created the window.");
}
- if (!retainEvents && !events) Events = true;
+ if (!retainEvents && !events)
+ {
+ Events = true;
+ }
implementation.ProcessEvents();
}
int result_min, int result_max)
{
if (value_min >= value_max || result_min >= result_max)
+ {
throw new ArgumentOutOfRangeException();
+ }
MathHelper.Clamp(value, value_min, value_max);
int range = result_max - result_min;
public virtual DisplayDevice GetDisplay(DisplayIndex index)
{
if (index == DisplayIndex.Primary)
+ {
return Primary;
+ }
else if ((int)index >= 0 && (int)index < AvailableDevices.Count)
+ {
return AvailableDevices[(int)index];
+ }
else
+ {
return null;
+ }
}
}
}
{
IntPtr ptr = eglCreateContext(dpy, config, share_context, attrib_list);
if (ptr == IntPtr.Zero)
+ {
throw new GraphicsContextException(String.Format("Failed to create EGL context, error: {0}.", Egl.GetError()));
+ }
return ptr;
}
int major, int minor, GraphicsContextFlags flags)
{
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
EglContext shared = GetSharedEglContext(sharedContext);
Renderable);
if (!Mode.Index.HasValue)
+ {
throw new GraphicsModeException("Invalid or unsupported GraphicsMode.");
+ }
IntPtr config = Mode.Index.Value;
if (window.Surface == IntPtr.Zero)
int major, int minor, GraphicsContextFlags flags)
{
if (handle == ContextHandle.Zero)
+ {
throw new ArgumentException("handle");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
Handle = handle;
}
if (window != null)
{
if (window is EglWindowInfo)
+ {
WindowInfo = (EglWindowInfo) window;
- #if !ANDROID
+ }
+#if !ANDROID
else if (window is IAngleWindowInfoInternal)
+ {
WindowInfo = ((IAngleWindowInfoInternal) window).EglWindowInfo;
- #endif
+ }
+#endif
if (!Egl.MakeCurrent(WindowInfo.Display, WindowInfo.Surface, WindowInfo.Surface, HandleAsEGLContext))
{
}
if (Egl.SwapInterval(WindowInfo.Display, value))
+ {
swap_interval = value;
+ }
else
+ {
Debug.Print("[Warning] Egl.SwapInterval({0}, {1}) failed. Error: {2}",
WindowInfo.Display, value, Egl.GetError());
+ }
}
}
if (manual)
{
if (IsCurrent)
+ {
Egl.MakeCurrent(WindowInfo.Display, WindowInfo.Surface, WindowInfo.Surface, IntPtr.Zero);
+ }
Egl.DestroyContext(WindowInfo.Display, HandleAsEGLContext);
}
IsDisposed = true;
{
IntPtr display = Egl.GetDisplay(dc);
if (display == IntPtr.Zero)
+ {
display = Egl.GetDisplay(IntPtr.Zero);
+ }
return display;
}
if (Display != IntPtr.Zero)
{
if (!Egl.Terminate(Display))
+ {
Debug.Print("[Warning] Failed to terminate display {0}.", Display);
+ }
Display = IntPtr.Zero;
}
}
// Create regular platform backend
#if SDL2
- if (Configuration.RunningOnSdl2) Default = new SDL2.Sdl2Factory();
- #endif
+ if (Configuration.RunningOnSdl2)
+ {
+ Default = new SDL2.Sdl2Factory();
+ }
+#endif
#if WIN32
- else if (Configuration.RunningOnWindows) Default = new Windows.WinFactory();
- #endif
+ else if (Configuration.RunningOnWindows)
+ {
+ Default = new Windows.WinFactory();
+ }
+#endif
#if CARBON
- else if (Configuration.RunningOnMacOS) Default = new MacOS.MacOSFactory();
- #endif
+ else if (Configuration.RunningOnMacOS)
+ {
+ Default = new MacOS.MacOSFactory();
+ }
+#endif
#if X11
- else if (Configuration.RunningOnX11) Default = new X11.X11Factory();
- else if (Configuration.RunningOnLinux) Default = new Linux.LinuxFactory();
- #endif
+ else if (Configuration.RunningOnX11)
+ {
+ Default = new X11.X11Factory();
+ }
+ else if (Configuration.RunningOnLinux)
+ {
+ Default = new Linux.LinuxFactory();
+ }
+#endif
if (Default == null)
+ {
Default = new UnsupportedPlatform();
+ }
// Create embedded platform backend for EGL / OpenGL ES.
// Todo: we could probably delay this until the embedded
#else
else if (Egl.Egl.IsSupported)
{
- if (Configuration.RunningOnLinux) Embedded = Default;
- #if X11
- else if (Configuration.RunningOnX11) Embedded = new Egl.EglX11PlatformFactory();
- #endif
+ if (Configuration.RunningOnLinux)
+ {
+ Embedded = Default;
+ }
+#if X11
+ else if (Configuration.RunningOnX11)
+ {
+ Embedded = new Egl.EglX11PlatformFactory();
+ }
+#endif
#if WIN32
- else if (Configuration.RunningOnWindows) Embedded = new Egl.EglWinPlatformFactory();
- #endif
+ else if (Configuration.RunningOnWindows)
+ {
+ Embedded = new Egl.EglWinPlatformFactory();
+ }
+#endif
#if CARBON
- else if (Configuration.RunningOnMacOS) Embedded = new Egl.EglMacPlatformFactory();
- #endif
+ else if (Configuration.RunningOnMacOS)
+ {
+ Embedded = new Egl.EglMacPlatformFactory();
+ }
+#endif
#if ANDROID
else if (Configuration.RunningOnAndroid) Embedded = new Android.AndroidFactory();
#endif
- else Embedded = new UnsupportedPlatform();
+ else
+ {
+ Embedded = new UnsupportedPlatform();
+ }
- #if ANDROID
+#if ANDROID
Angle = new UnsupportedPlatform();
#else
Angle = new Egl.EglAnglePlatformFactory(Embedded);
}
if (Default is UnsupportedPlatform && !(Embedded is UnsupportedPlatform))
+ {
Default = Embedded;
+ }
}
public static IPlatformFactory Default { get; private set; }
CloseRestrictedCallback close_restricted)
{
if (open_restricted == null || close_restricted == null)
+ {
throw new ArgumentNullException();
+ }
open = Marshal.GetFunctionPointerForDelegate(open_restricted);
close = Marshal.GetFunctionPointerForDelegate(close_restricted);
get
{
if (Crtc == IntPtr.Zero)
+ {
throw new InvalidOperationException();
+ }
unsafe
{
// Find corresponding encoder
ModeEncoder* encoder = GetEncoder(fd, c);
if (encoder == null)
+ {
return false;
+ }
ModeCrtc* crtc = GetCrtc(fd, encoder);
if (crtc == null)
+ {
return false;
+ }
display = new LinuxDisplay(fd, (IntPtr)c, (IntPtr)encoder, (IntPtr)crtc);
return true;
: base(mode, window, sharedContext, major, minor, flags)
{
if (mode.Buffers < 1)
+ {
throw new ArgumentException();
+ }
fd = window.FD;
PageFlip = HandlePageFlip;
{
fds.revents = 0;
if (Libc.poll(ref fds, 1, timeout) < 0)
+ {
break;
+ }
if ((fds.revents & (PollFlags.Hup | PollFlags.Error)) != 0)
+ {
break;
+ }
if ((fds.revents & PollFlags.In) != 0)
+ {
Drm.HandleEvent(fd, ref evctx);
+ }
else
+ {
break;
+ }
}
// Page flip has taken place, update buffer objects
{
LinuxWindowInfo wnd = WindowInfo as LinuxWindowInfo;
if (wnd == null)
+ {
throw new InvalidOperationException();
+ }
unsafe
{
{
LinuxWindowInfo wnd = WindowInfo as LinuxWindowInfo;
if (wnd == null)
+ {
throw new InvalidOperationException();
+ }
unsafe
{
private int GetFramebuffer(BufferObject bo)
{
if (bo == BufferObject.Zero)
+ {
goto fail;
+ }
int bo_handle = bo.Handle;
if (bo_handle == 0)
{
fd = Libc.open(path, OpenFlags.NonBlock);
if (fd == -1)
+ {
return null;
+ }
unsafe
{
{
length = (long)Libc.read(js.FileDescriptor, (void*)events, (UIntPtr)(sizeof(InputEvent) * EventCount));
if (length <= 0)
+ {
break;
+ }
// Only mark the joystick as connected when we actually start receiving events.
// Otherwise, the Xbox wireless receiver will register 4 joysticks even if no
else
{
if (cursor_custom != BufferObject.Zero)
+ {
cursor_custom.Dispose();
+ }
cursor_custom = CreateCursor(window.BufferManager, cursor);
bo = cursor_custom;
}
Egl.GetConfigAttrib(display, mode.Index.Value,
Egl.NATIVE_VISUAL_ID, out format);
if ((SurfaceFormat)format != 0)
+ {
return (SurfaceFormat)format;
+ }
Debug.Print("[KMS] Failed to retrieve EGL visual from GBM surface. Error: {0}",
Egl.GetError());
int a = mode.ColorFormat.Alpha;
if (mode.ColorFormat.IsIndexed)
+ {
return SurfaceFormat.C8;
+ }
if (r == 3 && g == 3 && b == 2 && a == 0)
+ {
return SurfaceFormat.RGB332;
+ }
if (r == 5 && g == 6 && b == 5 && a == 0)
+ {
return SurfaceFormat.RGB565;
+ }
if (r == 5 && g == 6 && b == 5 && a == 0)
+ {
return SurfaceFormat.RGB565;
+ }
if (r == 8 && g == 8 && b == 8 && a == 0)
+ {
return SurfaceFormat.RGB888;
+ }
if (r == 5 && g == 5 && b == 5 && a == 1)
+ {
return SurfaceFormat.RGBA5551;
+ }
if (r == 10 && g == 10 && b == 10 && a == 2)
+ {
return SurfaceFormat.RGBA1010102;
+ }
if (r == 4 && g == 4 && b == 4 && a == 4)
+ {
return SurfaceFormat.RGBA4444;
+ }
if (r == 8 && g == 8 && b == 8 && a == 8)
+ {
return SurfaceFormat.RGBA8888;
+ }
return SurfaceFormat.RGBA8888;
}
: base(IntPtr.Zero, display, IntPtr.Zero)
{
if (display_device == null)
+ {
throw new ArgumentNullException();
+ }
FD = fd;
BufferManager = gbm;
private void Dispose(bool disposing)
{
if (disposed)
+ {
return;
+ }
if (disposing)
{
public static IntPtr ToNSString(string str)
{
if (str == null)
+ {
return IntPtr.Zero;
+ }
unsafe
{
{
var indirect = NS.GetSymbol(handle, symbol);
if (indirect == IntPtr.Zero)
+ {
return IntPtr.Zero;
+ }
var actual = Marshal.ReadIntPtr(indirect);
if (actual == IntPtr.Zero)
+ {
return IntPtr.Zero;
+ }
return actual;
}
cocoaWindow = (CocoaWindowInfo)window;
if (shareContext is CocoaContext)
+ {
shareContextRef = ((CocoaContext)shareContext).Handle.Handle;
+ }
if (shareContext is GraphicsContext)
{
public CocoaContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int majorVersion, int minorVersion)
{
if (handle == ContextHandle.Zero)
+ {
throw new ArgumentException("handle");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
Handle = handle;
cocoaWindow = (CocoaWindowInfo)window;
Debug.Write("Attribute array: ");
for (int i = 0; i < attributes.Count; i++)
+ {
Debug.Write(attributes[i].ToString() + " ");
+ }
Debug.WriteLine("");
// Create pixel format
protected override void Dispose(bool disposing)
{
if (IsDisposed || Handle.Handle == IntPtr.Zero)
+ {
return;
+ }
Debug.Print("Disposing of Cocoa context.");
if (!NSApplication.IsUIThread)
+ {
return;
+ }
if (IsCurrent)
+ {
Cocoa.SendVoid(NSOpenGLContext, Selector.Get("clearCurrentContext"));
+ }
Cocoa.SendVoid(Handle.Handle, Selector.Get("clearDrawable"));
Cocoa.SendVoid(Handle.Handle, Selector.Get("release"));
}
if (suppressResize == 0)
+ {
OnResize(EventArgs.Empty);
+ }
}
private void ApplicationQuit(object sender, CancelEventArgs e)
private KeyModifiers GetModifiers(NSEventModifierMask mask)
{
OpenTK.Input.KeyModifiers modifiers = 0;
- if ((mask & NSEventModifierMask.ControlKeyMask) != 0) modifiers |= OpenTK.Input.KeyModifiers.Control;
- if ((mask & NSEventModifierMask.ShiftKeyMask) != 0) modifiers |= OpenTK.Input.KeyModifiers.Shift;
- if ((mask & NSEventModifierMask.AlternateKeyMask) != 0) modifiers |= OpenTK.Input.KeyModifiers.Alt;
+ if ((mask & NSEventModifierMask.ControlKeyMask) != 0)
+ {
+ modifiers |= OpenTK.Input.KeyModifiers.Control;
+ }
+ if ((mask & NSEventModifierMask.ShiftKeyMask) != 0)
+ {
+ modifiers |= OpenTK.Input.KeyModifiers.Shift;
+ }
+ if ((mask & NSEventModifierMask.AlternateKeyMask) != 0)
+ {
+ modifiers |= OpenTK.Input.KeyModifiers.Alt;
+ }
return modifiers;
}
private MouseButton GetMouseButton(int cocoaButtonIndex)
{
- if (cocoaButtonIndex == 0) return MouseButton.Left;
- if (cocoaButtonIndex == 1) return MouseButton.Right;
- if (cocoaButtonIndex == 2) return MouseButton.Middle;
+ if (cocoaButtonIndex == 0)
+ {
+ return MouseButton.Left;
+ }
+ if (cocoaButtonIndex == 1)
+ {
+ return MouseButton.Right;
+ }
+ if (cocoaButtonIndex == 2)
+ {
+ return MouseButton.Middle;
+ }
if (cocoaButtonIndex >= (int)MouseButton.LastButton)
+ {
return MouseButton.LastButton;
+ }
return (MouseButton)cocoaButtonIndex;
}
var e = Cocoa.SendIntPtr(NSApplication.Handle, selNextEventMatchingMask, uint.MaxValue, IntPtr.Zero, NSDefaultRunLoopMode, true);
if (e == IntPtr.Zero)
+ {
break;
+ }
var type = (NSEventType)Cocoa.SendInt(e, selType);
switch (type)
{
var oldState = windowState;
if (oldState == value)
+ {
return;
+ }
RestoreWindowState();
}
if (windowBorder == value)
+ {
return;
+ }
SetWindowBorder(value);
OnWindowBorderChanged(EventArgs.Empty);
protected override void Dispose(bool disposing)
{
if (disposed)
+ {
return;
+ }
Debug.Print("Disposing of CocoaNativeWindow (disposing={0}).", disposing);
if (!NSApplication.IsUIThread)
+ {
return;
+ }
NSApplication.Quit -= ApplicationQuit;
private void CloseWindow(bool shutdown)
{
if (!Exists)
+ {
return;
+ }
exists = false;
private void Dispose(bool disposing)
{
if (disposed)
+ {
return;
+ }
if (disposing)
{
RunLoop = CF.CFRunLoopGetMain();
if (RunLoop == IntPtr.Zero)
+ {
RunLoop = CF.CFRunLoopGetCurrent();
+ }
if (RunLoop == IntPtr.Zero)
{
Debug.Print("[Error] No CFRunLoop found for {0}", GetType().FullName);
{
symbol = LookupAndBindSymbol(function);
if (symbol != IntPtr.Zero)
+ {
symbol = AddressOfSymbol(symbol);
+ }
}
return symbol;
}
get
{
if (index >= Count || index < 0)
+ {
throw new IndexOutOfRangeException();
+ }
return CF.CFArrayGetValueAtIndex(Ref, index);
}
opentk_dev_available_res.Add(thisRes);
if (current)
+ {
opentk_dev_current_res = thisRes;
-
+ }
}
NSRect bounds = CG.DisplayBounds(currentDisplay);
AvailableDevices.Add(opentk_dev);
if (primary)
+ {
Primary = opentk_dev;
+ }
}
Debug.Unindent();
public static int PeepEvents(Event[] e, int count, EventAction action, EventType min, EventType max)
{
if (e == null)
+ {
throw new ArgumentNullException();
+ }
if (count <= 0 || count > e.Length)
+ {
throw new ArgumentOutOfRangeException();
+ }
unsafe
{
AvailableDevices.Add(device);
if (d == 0)
+ {
Primary = device;
+ }
}
}
{
// Check again inside the lock
if (inputDriver == null)
+ {
inputDriver = new Sdl2InputDriver();
+ }
}
}
private OpenTK.Input.HatPosition TranslateHat(HatPosition value)
{
if ((value & HatPosition.LeftUp) == HatPosition.LeftUp)
+ {
return OpenTK.Input.HatPosition.UpLeft;
+ }
if ((value & HatPosition.RightUp) == HatPosition.RightUp)
+ {
return OpenTK.Input.HatPosition.UpRight;
+ }
if ((value & HatPosition.LeftDown) == HatPosition.LeftDown)
+ {
return OpenTK.Input.HatPosition.DownLeft;
+ }
if ((value & HatPosition.RightDown) == HatPosition.RightDown)
+ {
return OpenTK.Input.HatPosition.DownRight;
+ }
if ((value & HatPosition.Up) == HatPosition.Up)
+ {
return OpenTK.Input.HatPosition.Up;
+ }
if ((value & HatPosition.Right) == HatPosition.Right)
+ {
return OpenTK.Input.HatPosition.Right;
+ }
if ((value & HatPosition.Down) == HatPosition.Down)
+ {
return OpenTK.Input.HatPosition.Down;
+ }
if ((value & HatPosition.Left) == HatPosition.Left)
+ {
return OpenTK.Input.HatPosition.Left;
+ }
return OpenTK.Input.HatPosition.Centered;
}
{
//UpdateModifiers(); // Fixme
if (index == 0)
+ {
return state;
+ }
else
+ {
return new KeyboardState();
+ }
}
public string GetDeviceName(int index)
public MouseState GetState(int index)
{
if (index == 0)
+ {
return GetState();
+ }
else
+ {
return new MouseState();
+ }
}
public MouseState GetCursorState()
if ((flags & WindowFlags.FULLSCREEN_DESKTOP) != 0 ||
(flags & WindowFlags.FULLSCREEN) != 0)
+ {
window_state = WindowState.Fullscreen;
+ }
if ((flags & WindowFlags.RESIZABLE) == 0)
+ {
window_border = WindowBorder.Fixed;
+ }
IntPtr handle;
lock (SDL.Sync)
if ((flags & GameWindowFlags.Fullscreen) != 0)
{
if (Sdl2Factory.UseFullscreenDesktop)
+ {
windowFlags |= WindowFlags.FULLSCREEN_DESKTOP;
+ }
else
+ {
windowFlags |= WindowFlags.FULLSCREEN;
+ }
}
if ((flags & GameWindowFlags.FixedWindow) == 0)
+ {
windowFlags |= WindowFlags.RESIZABLE;
+ }
return windowFlags;
}
// Calculate the length of the typed text string
int length;
for (length = 0; length < TextInputEvent.TextSize && ev.Text[length] != '\0'; length++)
+ {
;
+ }
// Make sure we have enough space to decode this string
int decoded_length = Encoding.UTF8.GetCharCount(ev.Text, length);
if (Exists)
{
if (value)
+ {
SDL.ShowWindow(window.Handle);
+ }
else
+ {
SDL.HideWindow(window.Handle);
+ }
}
}
}
}
if (!CursorVisible)
+ {
GrabCursor(true);
+ }
}
}
}
int supported = 0;
Type extensions_class = type.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (extensions_class == null)
+ {
throw new InvalidOperationException("The specified type does not have any loadable extensions.");
+ }
FieldInfo[] delegates = extensions_class.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (delegates == null)
+ {
throw new InvalidOperationException("The specified type does not have any loadable extensions.");
+ }
MethodInfo load_delegate_method_info = type.GetMethod("LoadDelegate", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (load_delegate_method_info == null)
+ {
throw new InvalidOperationException(type.ToString() + " does not contain a static LoadDelegate method.");
+ }
LoadDelegateFunction LoadDelegate = (LoadDelegateFunction)Delegate.CreateDelegate(
typeof(LoadDelegateFunction), load_delegate_method_info);
{
Delegate d = LoadDelegate(f.Name, f.FieldType);
if (d != null)
+ {
++supported;
+ }
f.SetValue(null, d);
}
FieldInfo rebuildExtensionList = type.GetField("rebuildExtensionList", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (rebuildExtensionList != null)
+ {
rebuildExtensionList.SetValue(null, true);
+ }
time.Stop();
Debug.Print("{0} extensions loaded in {1} ms.", supported, time.ElapsedMilliseconds);
f.SetValue(null, @new);
FieldInfo rebuildExtensionList = type.GetField("rebuildExtensionList", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (rebuildExtensionList != null)
+ {
rebuildExtensionList.SetValue(null, true);
+ }
}
return @new != null;
}
SetLastError(0);
if (IntPtr.Size == 4)
+ {
retval = new IntPtr(SetWindowLongInternal(handle, item, newValue.ToInt32()));
+ }
else
+ {
retval = SetWindowLongPtrInternal(handle, item, newValue);
+ }
if (retval == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
if (error != 0)
+ {
throw new PlatformException(String.Format("Failed to modify window border. Error: {0}", error));
+ }
}
return retval;
internal static UIntPtr GetWindowLong(IntPtr handle, GetWindowLongOffsets index)
{
if (IntPtr.Size == 4)
+ {
return (UIntPtr)GetWindowLongInternal(handle, index);
+ }
return GetWindowLongPtrInternal(handle, index);
}
get
{
if (index < 0 || index > Size * Count)
+ {
throw new ArgumentOutOfRangeException("index");
+ }
unsafe
{
fixed (byte* data = &RawData)
while (Functions.EnumDisplayDevices(null, device_count++, dev1, 0))
{
if ((dev1.StateFlags & DisplayDeviceStateFlags.AttachedToDesktop) == DisplayDeviceStateFlags.None)
+ {
continue;
+ }
DeviceMode monitor_mode = new DeviceMode();
// Set the original resolution if the DisplayDevice was previously available.
foreach (DisplayDevice existingDevice in previousDevices)
+ {
if ((string)existingDevice.Id == (string)opentk_dev.Id)
+ {
opentk_dev.OriginalResolution = existingDevice.OriginalResolution;
+ }
+ }
AvailableDevices.Add(opentk_dev);
if (opentk_dev_primary)
+ {
Primary = opentk_dev;
+ }
Debug.Print("DisplayDevice {0} ({1}) supports {2} resolutions.",
device_count, opentk_dev.IsPrimary ? "primary" : "secondary", opentk_dev.AvailableResolutions.Count);
Debug.WriteLine("[WGL] Creating temporary context to load extensions");
if (native == null)
+ {
throw new ArgumentNullException();
+ }
// Create temporary context and load WGL entry points
// First, set a compatible pixel format to the device context
lock (LoadLock)
{
if (window == null)
+ {
throw new ArgumentNullException("window", "Must point to a valid window.");
+ }
if (window.Handle == IntPtr.Zero)
+ {
throw new ArgumentException("window", "Must be a valid window.");
+ }
IntPtr current_context = Wgl.GetCurrentContext();
INativeWindow temp_window = null;
sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero,
attributes.ToArray()));
if (Handle == ContextHandle.Zero)
+ {
Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error());
+ }
}
catch (Exception e) { Debug.Print(e.ToString()); }
}
Debug.Write("Falling back to GL2... ");
Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
if (Handle == ContextHandle.Zero)
+ {
Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
+ }
if (Handle == ContextHandle.Zero)
+ {
throw new GraphicsContextException(
String.Format("Context creation failed. Wgl.CreateContext() error: {0}.",
Marshal.GetLastWin32Error()));
+ }
}
Debug.WriteLine(String.Format("success! (id: {0})", Handle));
int major, int minor, GraphicsContextFlags flags)
{
if (handle == ContextHandle.Zero)
+ {
throw new ArgumentException("handle");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
Handle = handle;
}
public override void SwapBuffers()
{
if (!Functions.SwapBuffers(DeviceContext))
+ {
throw new GraphicsContextException(String.Format(
"Failed to swap buffers for context {0} current. Error: {1}", this, Marshal.GetLastWin32Error()));
+ }
}
public override void MakeCurrent(IWindowInfo window)
if (wnd != null)
{
if (wnd.Handle == IntPtr.Zero)
+ {
throw new ArgumentException("window", "Must point to a valid window.");
+ }
success = Wgl.MakeCurrent(wnd.DeviceContext, Handle.Handle);
DeviceContext = wnd.DeviceContext;
lock (LoadLock)
{
if (vsync_supported)
+ {
return Wgl.Ext.GetSwapInterval();
+ }
else
+ {
return 0;
+ }
}
}
set
{
Debug.Write("Setting pixel format... ");
if (window == null)
+ {
throw new ArgumentNullException("window", "Must point to a valid window.");
+ }
if (!mode.Index.HasValue)
{
{
// This will fail if the user calls Dispose() on thread X when the context is current on thread Y.
if (!Wgl.DeleteContext(Handle.Handle))
+ {
Debug.Print("Failed to destroy OpenGL context {0}. Error: {1}",
Handle.ToString(), Marshal.GetLastWin32Error());
+ }
}
catch (AccessViolationException e)
{
// wParam: The low-order word specifies whether the window is being activated or deactivated.
bool new_focused_state = Focused;
if (IntPtr.Size == 4)
+ {
focused = (wParam.ToInt32() & 0xFFFF) != 0;
+ }
else
+ {
focused = (wParam.ToInt64() & 0xFFFF) != 0;
+ }
if (new_focused_state != Focused)
+ {
OnFocusedChanged(EventArgs.Empty);
+ }
}
private void HandleEnterModalLoop(IntPtr handle, WindowMessage message, IntPtr wParam, IntPtr lParam)
StartTimer(handle);
if (!CursorVisible)
+ {
UngrabCursor();
+ }
}
private void HandleExitModalLoop(IntPtr handle, WindowMessage message, IntPtr wParam, IntPtr lParam)
// Ensure cursor remains grabbed
if (!CursorVisible)
+ {
GrabCursor();
+ }
}
private void HandleWindowPositionChanged(IntPtr handle, WindowMessage message, IntPtr wParam, IntPtr lParam)
SetWindowPosFlags.NOACTIVATE | SetWindowPosFlags.NOSENDCHANGING);
if (suppress_resize <= 0)
+ {
OnResize(EventArgs.Empty);
+ }
}
if (!is_in_modal_loop)
// handled inside [ENTER|EXIT]SIZEMOVE case above.
// If not, then we have to handle cursor grabbing here.
if (!CursorVisible)
+ {
GrabCursor();
+ }
}
}
}
{
WindowStyle style = ((StyleStruct*)lParam)->New;
if ((style & WindowStyle.Popup) != 0)
+ {
new_border = WindowBorder.Hidden;
+ }
else if ((style & WindowStyle.ThickFrame) != 0)
+ {
new_border = WindowBorder.Resizable;
+ }
else if ((style & ~(WindowStyle.ThickFrame | WindowStyle.MaximizeBox)) != 0)
+ {
new_border = WindowBorder.Fixed;
+ }
}
}
{
// Ensure cursor remains grabbed
if (!CursorVisible)
+ {
GrabCursor();
+ }
windowBorder = new_border;
OnWindowBorderChanged(EventArgs.Empty);
// Ensure cursor remains grabbed
if (!CursorVisible)
+ {
GrabCursor();
+ }
}
}
{
char c;
if (IntPtr.Size == 4)
+ {
c = (char)wParam.ToInt32();
+ }
else
+ {
c = (char)wParam.ToInt64();
+ }
if (!Char.IsControl(c))
{
for (i = 0; i < points; ++i)
{
if (movePoints[i].Time < mouse_last_timestamp)
+ {
break;
+ }
if (movePoints[i].Time == mouse_last_timestamp &&
movePoints[i].X == currentScreenPosition.X &&
movePoints[i].Y == currentScreenPosition.Y)
+ {
break;
+ }
}
// Now move the mouse to each point before the one just found.
me.Flags = TrackMouseEventFlags.LEAVE;
if (!Functions.TrackMouseEvent(ref me))
+ {
Debug.Print("[Warning] Failed to enable mouse tracking, error: {0}.",
Marshal.GetLastWin32Error());
+ }
}
private void StartTimer(IntPtr handle)
{
timer_handle = Functions.SetTimer(handle, new UIntPtr(1), ModalLoopTimerPeriod, null);
if (timer_handle == UIntPtr.Zero)
+ {
Debug.Print("[Warning] Failed to set modal loop timer callback ({0}:{1}->{2}).",
GetType().Name, handle, Marshal.GetLastWin32Error());
+ }
}
}
if (timer_handle != UIntPtr.Zero)
{
if (!Functions.KillTimer(handle, timer_handle))
+ {
Debug.Print("[Warning] Failed to kill modal loop timer callback ({0}:{1}->{2}).",
GetType().Name, handle, Marshal.GetLastWin32Error());
+ }
timer_handle = UIntPtr.Zero;
}
}
ushort atom = Functions.RegisterClassEx(ref wc);
if (atom == 0)
+ {
throw new PlatformException(String.Format("Failed to register window class. Error: {0}", Marshal.GetLastWin32Error()));
+ }
class_registered = true;
}
parentHandle, IntPtr.Zero, Instance, IntPtr.Zero);
if (handle == IntPtr.Zero)
+ {
throw new PlatformException(String.Format("Failed to create window. Error: {0}", Marshal.GetLastWin32Error()));
+ }
return handle;
}
rect.top = pos.Y;
rect.bottom = pos.Y + ClientRectangle.Height;
if (!Functions.ClipCursor(ref rect))
+ {
Debug.WriteLine(String.Format("Failed to grab cursor. Error: {0}",
Marshal.GetLastWin32Error()));
+ }
}
private void UngrabCursor()
{
if (!Functions.ClipCursor(IntPtr.Zero))
+ {
Debug.WriteLine(String.Format("Failed to ungrab cursor. Error: {0}",
Marshal.GetLastWin32Error()));
+ }
}
public override Rectangle Bounds
{
sb_title.Remove(0, sb_title.Length);
if (Functions.GetWindowText(window.Handle, sb_title, sb_title.Capacity) == 0)
+ {
Debug.Print("Failed to retrieve window title (window:{0}, reason:{1}).", window.Handle, Marshal.GetLastWin32Error());
+ }
return sb_title.ToString();
}
set
if (Title != value)
{
if (!Functions.SetWindowText(window.Handle, value))
+ {
Debug.Print("Failed to change window title (window:{0}, new title:{1}, reason:{2}).", window.Handle, value, Marshal.GetLastWin32Error());
+ }
OnTitleChanged(EventArgs.Empty);
}
}
set
{
if (WindowState == value)
+ {
return;
+ }
ShowWindowCommand command = 0;
bool exiting_fullscreen = false;
// If we are leaving fullscreen mode we need to restore the border.
if (WindowState == WindowState.Fullscreen)
+ {
exiting_fullscreen = true;
+ }
break;
case WindowState.Maximized:
}
if (command != 0)
+ {
Functions.ShowWindow(window.Handle, command);
+ }
// Restore previous window border or apply pending border change when leaving fullscreen mode.
if (exiting_fullscreen)
}
if (windowBorder == value)
+ {
return;
+ }
// We wish to avoid making an invisible window visible just to change the border.
// However, it's a good idea to make a visible window invisible temporarily, to
// This avoids leaving garbage on the background window.
if (was_visible)
+ {
Visible = false;
+ }
Functions.SetWindowLong(window.Handle, GetWindowLongOffsets.STYLE, (IntPtr)(int)new_style);
Functions.SetWindowPos(window.Handle, IntPtr.Zero, 0, 0, rect.Width, rect.Height,
// already visible (invisible windows will change borders when
// they become visible, so no need to make them visiable prematurely).
if (was_visible)
+ {
Visible = true;
+ }
WindowState = state;
public override Point PointToClient(Point point)
{
if (!Functions.ScreenToClient(window.Handle, ref point))
+ {
throw new InvalidOperationException(String.Format(
"Could not convert point {0} from screen to client coordinates. Windows error: {1}",
point.ToString(), Marshal.GetLastWin32Error()));
+ }
return point;
}
public override Point PointToScreen(Point point)
{
if (!Functions.ClientToScreen(window.Handle, ref point))
+ {
throw new InvalidOperationException(String.Format(
"Could not convert point {0} from screen to client coordinates. Windows error: {1}",
point.ToString(), Marshal.GetLastWin32Error()));
+ }
return point;
}
// Safe to clean managed resources
DestroyWindow();
if (Icon != null)
+ {
Icon.Dispose();
+ }
}
else
{
public WinGraphicsMode(IntPtr device)
{
if (device == IntPtr.Zero)
+ {
throw new ArgumentException();
+ }
Device = device;
}
valid &= pfd.PixelType == PixelType.RGBA; // indexed modes not currently supported
// heavily penalize single-buffered modes when the user requests double buffering
if ((pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) == 0 && mode.Buffers > 1)
+ {
dist += 1000;
+ }
valid &= Compare(pfd.ColorBits, mode.ColorFormat.BitsPerPixel, ref dist);
valid &= Compare(pfd.RedBits, mode.ColorFormat.Red, ref dist);
valid &= Compare(pfd.GreenBits, mode.ColorFormat.Green, ref dist);
{
IntPtr ret = WindowProcedure(handle, message, wParam, lParam);
if (ret == Unhandled)
+ {
return Functions.CallWindowProc(OldWndProc, handle, message, wParam, lParam);
+ }
else
+ {
return ret;
+ }
}
protected virtual IntPtr WindowProcedure(
case Key.Delete: key = Key.KeypadDecimal; break;
case Key.NumLock:
if (vkey == VirtualKeys.Last)
+ {
is_valid = false;
+ }
else if (vkey == VirtualKeys.PAUSE)
+ {
key = Key.Pause;
+ }
break;
}
}
new IntPtr((void*)&bdi), DeviceNotification.WINDOW_HANDLE);
}
if (dev_notify_handle == IntPtr.Zero)
+ {
Debug.Print("[Warning] Failed to register for device notifications. Error: {0}", Marshal.GetLastWin32Error());
+ }
return dev_notify_handle;
}
{
case RawInputDeviceType.KEYBOARD:
if (((WinRawKeyboard)KeyboardDriver).ProcessKeyboardEvent(lParam))
+ {
return IntPtr.Zero;
+ }
break;
case RawInputDeviceType.MOUSE:
if (((WinRawMouse)MouseDriver).ProcessMouseEvent(lParam))
+ {
return IntPtr.Zero;
+ }
break;
case RawInputDeviceType.HID:
if (((WinRawJoystick)JoystickDriver).ProcessEvent(lParam))
+ {
return IntPtr.Zero;
+ }
break;
}
}
int count = WinRawInput.DeviceCount;
RawInputDeviceList[] ridl = new RawInputDeviceList[count];
for (int i = 0; i < count; i++)
+ {
ridl[i] = new RawInputDeviceList();
+ }
Functions.GetRawInputDeviceList(ridl, ref count, API.RawInputDeviceListSize);
return ridl;
}
Debug.Indent();
if (window == IntPtr.Zero)
+ {
throw new ArgumentNullException("window");
+ }
DeviceTypes = new RawInputDevice[]
{
{
// Skip non-joystick devices
if (dev.Type != RawInputDeviceType.HID)
+ {
continue;
+ }
// We use the device handle as the hardware id.
// This works, but the handle will change whenever the
}
}
else
+ {
return false;
+ }
}
finally
{
int count = WinRawInput.DeviceCount;
RawInputDeviceList[] ridl = new RawInputDeviceList[count];
for (int i = 0; i < count; i++)
+ {
ridl[i] = new RawInputDeviceList();
+ }
Functions.GetRawInputDeviceList(ridl, ref count, API.RawInputDeviceListSize);
// Discover keyboard devices:
// keyboard device by qeurying the registry.
RegistryKey regkey = GetRegistryKey(name);
if (regkey == null)
+ {
continue;
+ }
string deviceDesc = (string)regkey.GetValue("DeviceDesc");
string deviceClass = (string)regkey.GetValue("Class");
}
if (keyboards.Count == 0)
+ {
return false;
+ }
// Note:For some reason, my Microsoft Digital 3000 keyboard reports 0
// as rin.Header.Device for the "zoom-in/zoom-out" buttons.
private static RegistryKey GetRegistryKey(string name)
{
if (name.Length < 4)
+ {
return null;
+ }
// remove the \??\
name = name.Substring(4);
string[] split = name.Split('#');
if (split.Length < 3)
+ {
return null;
+ }
string id_01 = split[0]; // ACPI (Class code)
string id_02 = split[1]; // PNP0303 (SubClass code)
lock (UpdateLock)
{
if (keyboards.Count > index)
+ {
return keyboards[index];
+ }
else
+ {
return new KeyboardState();
+ }
}
}
lock (UpdateLock)
{
if (names.Count > index)
+ {
return names[index];
+ }
else
+ {
return String.Empty;
+ }
}
}
}
Debug.Indent();
if (window == IntPtr.Zero)
+ {
throw new ArgumentNullException("window");
+ }
Window = window;
RefreshDevices();
// mouse device by qeurying the registry.
RegistryKey regkey = FindRegistryKey(name);
if (regkey == null)
+ {
continue;
+ }
string deviceDesc = (string)regkey.GetValue("DeviceDesc");
string deviceClass = (string)regkey.GetValue("Class") as string;
// Since the description is not vital information, use a dummy description
// when that happens.
if (String.IsNullOrEmpty(deviceDesc))
+ {
deviceDesc = "Windows Mouse " + mice.Count;
+ }
else
+ {
deviceDesc = deviceDesc.Substring(deviceDesc.LastIndexOf(';') + 1);
+ }
if (!String.IsNullOrEmpty(deviceClass) && deviceClass.ToLower().Equals("mouse"))
{
}
if (mice.Count == 0)
+ {
return false;
+ }
// Note:For some reason, my Microsoft Digital 3000 keyboard reports 0
// as rin.Header.Device for the "zoom-in/zoom-out" buttons.
}
if ((raw.ButtonFlags & RawInputMouseState.WHEEL) != 0)
+ {
mouse.SetScrollRelative(0, (short)raw.ButtonData / 120.0f);
+ }
if ((raw.ButtonFlags & RawInputMouseState.HWHEEL) != 0)
+ {
mouse.SetScrollRelative((short)raw.ButtonData / 120.0f, 0);
+ }
if ((raw.Flags & RawMouseFlags.MOUSE_MOVE_ABSOLUTE) != 0)
{
private static RegistryKey FindRegistryKey(string name)
{
if (name.Length < 4)
+ {
return null;
+ }
// remove the \??\
name = name.Substring(4);
string[] split = name.Split('#');
if (split.Length < 3)
+ {
return null;
+ }
string id_01 = split[0]; // ACPI (Class code)
string id_02 = split[1]; // PNP0303 (SubClass code)
lock (UpdateLock)
{
if (mice.Count > index)
+ {
return mice[index];
+ }
else
+ {
return new MouseState();
+ }
}
}
get
{
if (dc == IntPtr.Zero)
+ {
dc = Functions.GetDC(this.Handle);
- //dc = Functions.GetWindowDC(this.Handle);
+ }
+ //dc = Functions.GetWindowDC(this.Handle);
return dc;
}
}
/// <returns>True if <c>this</c> and <c>obj</c> reference the same win32 window; false otherwise.</returns>
public override bool Equals(object obj)
{
- if (obj == null) return false;
- if (this.GetType() != obj.GetType()) return false;
+ if (obj == null)
+ {
+ return false;
+ }
+ if (this.GetType() != obj.GetType())
+ {
+ return false;
+ }
WinWindowInfo info = (WinWindowInfo)obj;
- if (info == null) return false;
+ if (info == null)
+ {
+ return false;
+ }
// TODO: Assumes windows will always have unique handles.
return handle.Equals(info.handle);
}
if (!disposed)
{
if (this.dc != IntPtr.Zero)
+ {
if (!Functions.ReleaseDC(this.handle, this.dc))
+ {
Debug.Print("[Warning] Failed to release device context {0}. Windows error: {1}.", this.dc, Marshal.GetLastWin32Error());
+ }
+ }
if (manual)
{
if (Parent != null)
+ {
Parent.Dispose();
+ }
}
disposed = true;
dir =XInputButtons.DPadUp | XInputButtons.DPadLeft;
if ((buttons & dir) == dir)
+ {
return HatPosition.UpLeft;
+ }
dir = XInputButtons.DPadUp | XInputButtons.DPadRight;
if ((buttons & dir) == dir)
+ {
return HatPosition.UpRight;
+ }
dir = XInputButtons.DPadDown | XInputButtons.DPadLeft;
if ((buttons & dir) == dir)
+ {
return HatPosition.DownLeft;
+ }
dir = XInputButtons.DPadDown | XInputButtons.DPadRight;
if ((buttons & dir) == dir)
+ {
return HatPosition.DownRight;
+ }
dir = XInputButtons.DPadUp;
if ((buttons & dir) == dir)
+ {
return HatPosition.Up;
+ }
dir = XInputButtons.DPadRight;
if ((buttons & dir) == dir)
+ {
return HatPosition.Right;
+ }
dir = XInputButtons.DPadDown;
if ((buttons & dir) == dir)
+ {
return HatPosition.Down;
+ }
dir = XInputButtons.DPadLeft;
if ((buttons & dir) == dir)
+ {
return HatPosition.Left;
+ }
return HatPosition.Centered;
}
// The delegates below will be loaded dynamically from that dll
dll = Functions.LoadLibrary("XINPUT1_4");
if (dll == IntPtr.Zero)
+ {
dll = Functions.LoadLibrary("XINPUT1_3");
+ }
if (dll == IntPtr.Zero)
+ {
dll = Functions.LoadLibrary("XINPUT1_2");
+ }
if (dll == IntPtr.Zero)
+ {
dll = Functions.LoadLibrary("XINPUT1_1");
+ }
if (dll == IntPtr.Zero)
+ {
dll = Functions.LoadLibrary("XINPUT9_1_0");
+ }
if (dll == IntPtr.Zero)
+ {
throw new NotSupportedException("XInput was not found on this platform");
+ }
// Load the entry points we are interested in from that dll
GetCapabilities = (XInputGetCapabilities)Load("XInputGetCapabilities", typeof(XInputGetCapabilities));
{
IntPtr pfunc = Functions.GetProcAddress(dll, (IntPtr)ordinal);
if (pfunc != IntPtr.Zero)
+ {
return Marshal.GetDelegateForFunctionPointer(pfunc, type);
+ }
return null;
}
{
IntPtr pfunc = Functions.GetProcAddress(dll, name);
if (pfunc != IntPtr.Zero)
+ {
return Marshal.GetDelegateForFunctionPointer(pfunc, type);
+ }
return null;
}
DefaultDisplay = Functions.XOpenDisplay(IntPtr.Zero);
if (DefaultDisplay == IntPtr.Zero)
+ {
throw new PlatformException("Could not establish connection to the X-Server.");
+ }
using (new XLock(DefaultDisplay))
{
byte* data = (byte*)XRRSizes(dpy, screen, &count);//(byte*)ptr;
if (count == 0)
+ {
return null;
+ }
sizes = new XRRScreenSize[count];
for (int i = 0; i < count; i++)
{
{
short* data = (short*)XRRRates(dpy, screen, size_index, &count);
if (count == 0)
+ {
return null;
+ }
rates = new short[count];
for (int i = 0; i < count; i++)
+ {
rates[i] = *(data + i);
+ }
}
return rates;
}
int count;
int* data = XListDepths(display, screen_number, &count);
if (count == 0)
+ {
return null;
+ }
int[] depths = new int[count];
for (int i = 0; i < count; i++)
+ {
depths[i] = *(data + i);
+ }
return depths;
}
public static Pixmap XCreateBitmapFromData(Display display, Window d, byte[,] data)
{
if (data == null)
+ {
throw new ArgumentNullException("data");
+ }
unsafe
{
get
{
if (_display == IntPtr.Zero)
+ {
throw new InvalidOperationException("Internal error (XLockDisplay with IntPtr.Zero). Please report this at http://www.opentk.com/node/add/project-issue/opentk");
+ }
return _display;
}
set
{
if (value == IntPtr.Zero)
+ {
throw new ArgumentException();
+ }
_display = value;
}
}
get
{
if (i < 0 || i > 3)
+ {
throw new IndexOutOfRangeException();
+ }
unsafe
{
get
{
if (i < 0 || i > 31)
+ {
throw new IndexOutOfRangeException();
+ }
unsafe
{
get
{
if (i < 0 || i > 15)
+ {
throw new IndexOutOfRangeException();
+ }
unsafe
{
int offset = y * stride + (x >> 3);
if (image.GetPixel(x, y).A >= 128)
+ {
mask[offset] |= bit;
+ }
}
}
{
mask = (byte*)Marshal.AllocHGlobal(mask_len);
for (int i = 0; i < mask_len; i++)
+ {
mask[i] = (byte)((uint)m >> i*8);
+ }
}
}
private static DisplayDevice FindDefaultDevice(IEnumerable<DisplayDevice> devices)
{
foreach (DisplayDevice dev in devices)
+ {
if (dev.IsPrimary)
+ {
return dev;
+ }
+ }
throw new InvalidOperationException("No primary display found. Please file a bug at http://www.opentk.com");
}
// Note: some X servers (like Xming on Windows) do not report any rates other than 0.
// If we only have 1 rate, add it even if it is 0.
if (rate != 0 || rates.Length == 1)
+ {
foreach (int depth in depths)
+ {
available_res.Add(new DisplayResolution(0, 0, size.Width, size.Height, depth, (float)rate));
+ }
+ }
}
// Keep the index of this resolution - we will need it for resolution changes later.
foreach (int depth in depths)
// same resolution twice!
DisplayResolution res = new DisplayResolution(0, 0, size.Width, size.Height, depth, 0);
if (!screenResolutionToIndex[screen].ContainsKey(res))
+ {
screenResolutionToIndex[screen].Add(res, resolution_count);
+ }
}
++resolution_count;
try
{
if (!API.XF86VidModeQueryVersion(API.DefaultDisplay, out major, out minor))
+ {
return false;
+ }
}
catch (DllNotFoundException)
{
XRRScreenSize[] resolutions = null;
resolutions = Functions.XRRSizes(API.DefaultDisplay, screen);
if (resolutions == null)
+ {
throw new NotSupportedException("XRandR extensions not available.");
+ }
return resolutions;
}
int current_resolution_index = Functions.XRRConfigCurrentConfiguration(screen_config, out current_rotation);
int new_resolution_index;
if (resolution != null)
+ {
new_resolution_index = screenResolutionToIndex[screen]
[new DisplayResolution(0, 0, resolution.Width, resolution.Height, resolution.BitsPerPixel, 0)];
+ }
else
+ {
new_resolution_index = deviceToDefaultResolution[device];
+ }
Debug.Print("Changing size of screen {0} from {1} to {2}",
screen, current_resolution_index, new_resolution_index);
int major, int minor, GraphicsContextFlags flags)
{
if (mode == null)
+ {
throw new ArgumentNullException("mode");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
// Do not move this lower, as almost everything requires the Display
// property to be correctly set.
}
if (Handle != ContextHandle.Zero)
+ {
Debug.Print("Context created (id: {0}).", Handle);
+ }
else
+ {
throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
+ }
using (new XLock(Display))
{
if (!Glx.IsDirect(Display, Handle.Handle))
+ {
Debug.Print("Warning: Context is not direct.");
+ }
}
}
int major, int minor, GraphicsContextFlags flags)
{
if (handle == ContextHandle.Zero)
+ {
throw new ArgumentException("handle");
+ }
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
Handle = handle;
currentWindow = (X11WindowInfo)window;
}
if (context == IntPtr.Zero)
+ {
Debug.WriteLine("failed.");
+ }
else
+ {
Debug.WriteLine("success!");
+ }
}
return new ContextHandle(context);
set
{
if (value == IntPtr.Zero)
+ {
throw new ArgumentOutOfRangeException();
+ }
if (display != IntPtr.Zero)
+ {
throw new InvalidOperationException("The display connection may not be changed after being set.");
+ }
display = value;
}
}
private bool SupportsExtension(IntPtr display, X11WindowInfo window, string e)
{
if (window == null)
+ {
throw new ArgumentNullException("window");
+ }
if (e == null)
+ {
throw new ArgumentNullException("e");
+ }
if (window.Display != display)
+ {
throw new InvalidOperationException();
+ }
if (String.IsNullOrEmpty(extensions))
{
public override void SwapBuffers()
{
if (Display == IntPtr.Zero || currentWindow.Handle == IntPtr.Zero)
+ {
throw new InvalidOperationException(
String.Format("Window is invalid. Display ({0}), Handle ({1}).", Display, currentWindow.Handle));
+ }
using (new XLock(Display))
{
Glx.SwapBuffers(Display, currentWindow.Handle);
public override void MakeCurrent(IWindowInfo window)
{
if (window == currentWindow && IsCurrent)
+ {
return;
+ }
if (window != null && ((X11WindowInfo)window).Display != Display)
+ {
throw new InvalidOperationException("MakeCurrent() may only be called on windows originating from the same display that spawned this GL context.");
+ }
if (window == null)
{
Handle, System.Threading.Thread.CurrentThread.ManagedThreadId, Display, w.Screen, w.Handle));
if (Display == IntPtr.Zero || w.Handle == IntPtr.Zero || Handle == ContextHandle.Zero)
+ {
throw new InvalidOperationException("Invalid display, window or context.");
+ }
using (new XLock(Display))
{
}
if (!result)
+ {
throw new GraphicsContextException("Failed to make context current.");
+ }
else
+ {
Debug.WriteLine("done!");
+ }
}
currentWindow = (X11WindowInfo)window;
}
if (error_code == X11.ErrorCode.NO_ERROR)
+ {
sgi_swap_interval = value;
+ }
else
+ {
Debug.Print("VSync = {0} failed, error code: {1}.", value, error_code);
+ }
}
}
: this()
{
if (width <= 0)
+ {
throw new ArgumentOutOfRangeException("width", "Must be higher than zero.");
+ }
if (height <= 0)
+ {
throw new ArgumentOutOfRangeException("height", "Must be higher than zero.");
+ }
Debug.Indent();
CreateWindowArgs.InputOutput, window.VisualInfo.Visual, mask, attributes);
if (window.Handle == IntPtr.Zero)
+ {
throw new ApplicationException("XCreateWindow call failed (returned 0).");
+ }
if (title != null)
+ {
Functions.XStoreName(window.Display, window.Handle, title);
+ }
}
XSizeHints hints = new XSizeHints();
window.Display = Functions.XOpenDisplay(IntPtr.Zero);
//window.Display = API.DefaultDisplay;
if (window.Display == IntPtr.Zero)
+ {
throw new Exception("Could not open connection to X");
+ }
using (new XLock(window.Display))
{
hints.min_height = min_height;
}
else
+ {
hints.flags = (IntPtr)((int)hints.flags & ~(int)XSizeHintsFlags.PMinSize);
+ }
if (max_width > 0 || max_height > 0)
{
hints.max_height = max_height;
}
else
+ {
hints.flags = (IntPtr)((int)hints.flags & ~(int)XSizeHintsFlags.PMaxSize);
+ }
if (hints.flags != IntPtr.Zero)
{
{
// TODO: How to check if MotifWMHints decorations have been really disabled?
if (_decorations_hidden)
+ {
return true;
+ }
}
// Some WMs remove decorations when the transient_for hint is set. Most new ones do not (but those
IntPtr transient_for_parent;
Functions.XGetTransientForHint(window.Display, window.Handle, out transient_for_parent);
if (transient_for_parent != IntPtr.Zero)
+ {
return true;
+ }
return false;
}
bool previous_visible = visible;
visible = true;
if (visible != previous_visible)
+ {
OnVisibleChanged(EventArgs.Empty);
+ }
}
return;
bool previous_visible = visible;
visible = false;
if (visible != previous_visible)
+ {
OnVisibleChanged(EventArgs.Empty);
+ }
}
break;
bool previous_focus = has_focus;
has_focus = true;
if (has_focus != previous_focus)
+ {
OnFocusedChanged(EventArgs.Empty);
+ }
if (Focused && !CursorVisible)
{
bool previous_focus = has_focus;
has_focus = false;
if (has_focus != previous_focus)
+ {
OnFocusedChanged(EventArgs.Empty);
+ }
}
break;
set
{
if (value == icon)
+ {
return;
+ }
// Note: it seems that Gnome/Metacity does not respect the _NET_WM_ICON hint.
// For this reason, we'll also set the icon using XSetWMHints.
for (int y = 0; y < bitmap.Height; y++)
for (int x = 0; x < bitmap.Width; x++)
+ {
data[index++] = (IntPtr)bitmap.GetPixel(x, y).ToArgb();
+ }
using (new XLock(window.Display))
{
IntPtr wmHints_ptr = Functions.XGetWMHints(window.Display, window.Handle);
if (wmHints_ptr == IntPtr.Zero)
+ {
wmHints_ptr = Functions.XAllocWMHints();
+ }
XWMHints wmHints = (XWMHints)Marshal.PtrToStructure(wmHints_ptr, typeof(XWMHints));
if (atom == _atom_net_wm_state_maximized_horizontal ||
atom == _atom_net_wm_state_maximized_vertical)
+ {
maximized++;
+ }
else if (atom == _atom_net_wm_state_minimized)
+ {
minimized = true;
+ }
else if (atom == _atom_net_wm_state_fullscreen)
+ {
fullscreen = true;
+ }
}
using (new XLock(window.Display))
{
}
if (minimized)
+ {
return OpenTK.WindowState.Minimized;
+ }
else if (maximized == 2)
+ {
return OpenTK.WindowState.Maximized;
+ }
else if (fullscreen)
+ {
return OpenTK.WindowState.Fullscreen;
+ }
/*
attributes = new XWindowAttributes();
Functions.XGetWindowAttributes(window.Display, window.Handle, ref attributes);
}
if (current_state == value)
+ {
return;
+ }
Debug.Print("GameWindow {0} changing WindowState from {1} to {2}.", window.Handle.ToString(),
current_state.ToString(), value.ToString());
get
{
if (IsWindowBorderHidden || WindowState == OpenTK.WindowState.Fullscreen)
+ {
return WindowBorder.Hidden;
+ }
else if (!IsWindowBorderResizable)
+ {
return WindowBorder.Fixed;
+ }
else if (WindowState == OpenTK.WindowState.Maximized)
+ {
return _previous_window_border;
+ }
else
+ {
return WindowBorder.Resizable;
+ }
}
set
{
if (WindowBorder == value)
+ {
return;
+ }
// We cannot change the border of a fullscreen window.
// Record the new value and set it on the next WindowState
private void ChangeWindowBorder(WindowBorder value, int width, int height)
{
if (WindowBorder == WindowBorder.Hidden)
+ {
EnableWindowDecorations();
+ }
switch (value)
{
unsafe
{
if (value == cursor)
+ {
return;
+ }
using (new XLock(window.Display))
{
Functions.XFetchName(window.Display, window.Handle, ref name);
}
if (name != IntPtr.Zero)
+ {
return Marshal.PtrToStringAnsi(name);
+ }
return String.Empty;
}
// This is only supported on GLX 1.3 - if it fails, fall back to Glx.ChooseVisual.
fbconfig = SelectFBConfig(mode);
if (fbconfig != IntPtr.Zero)
+ {
visual = Glx.GetVisualFromFBConfig(display, fbconfig);
+ }
if (visual == IntPtr.Zero)
+ {
visual = SelectVisual(mode);
+ }
if (visual == IntPtr.Zero)
{
// Relax parameters and retry
if (!Utilities.RelaxGraphicsMode(ref mode))
+ {
throw new GraphicsModeException("Requested GraphicsMode not available.");
+ }
}
}
while (visual == IntPtr.Zero);
if (mode.ColorFormat.BitsPerPixel > 0)
{
if (!mode.ColorFormat.IsIndexed)
+ {
visualAttributes.Add((int)GLXAttribute.RGBA);
+ }
visualAttributes.Add((int)GLXAttribute.RED_SIZE);
visualAttributes.Add(mode.ColorFormat.Red);
visualAttributes.Add((int)GLXAttribute.GREEN_SIZE);
}
if (mode.Buffers > 1)
+ {
visualAttributes.Add((int)GLXAttribute.DOUBLEBUFFER);
+ }
if (mode.Stencil > 1)
{
}
if (mode.Stereo)
+ {
visualAttributes.Add((int)GLXAttribute.STEREO);
+ }
visualAttributes.Add(0);
// X11Keyboard supports a single keyboard only
ProcessEvents();
if (index == 0)
+ {
return state;
+ }
else
+ {
return new KeyboardState();
+ }
}
public string GetDeviceName(int index)
{
if (index == 0)
+ {
return name;
+ }
else
+ {
return String.Empty;
+ }
}
private void ProcessEvents()
ProcessEvents();
// X11Mouse supports only one device
if (index == 0)
+ {
return mouse;
+ }
else
+ {
return new MouseState();
+ }
}
public MouseState GetCursorState()
/// <returns>True if <c>this</c> and <c>obj</c> reference the same win32 window; false otherwise.</returns>
public override bool Equals(object obj)
{
- if (obj == null) return false;
- if (this.GetType() != obj.GetType()) return false;
+ if (obj == null)
+ {
+ return false;
+ }
+ if (this.GetType() != obj.GetType())
+ {
+ return false;
+ }
X11WindowInfo info = (X11WindowInfo)obj;
- if (info == null) return false;
+ if (info == null)
+ {
+ return false;
+ }
// TODO: Assumes windows will have unique handles per X11 display.
return object.Equals(display, info.display) &&
handle.Equals(info.handle);
}
if (!IsSupported(window.Display))
+ {
throw new NotSupportedException("XInput2 not supported.");
+ }
// Enable XI2 mouse/keyboard events
// Note: the input event loop blocks waiting for these events
{
Debug.WriteLine("\tAbsolute X movement");
if (d.MotionX.number == -1)
+ {
d.MotionX = *valuator;
+ }
}
else if (valuator->label == XI.AbsoluteY)
{
Debug.WriteLine("\tAbsolute X movement");
if (d.MotionY.number == -1)
+ {
d.MotionY = *valuator;
+ }
}
else
{
MouseButton button = X11KeyMap.TranslateButton(raw.detail, out dx, out dy);
mouse.State[button] = raw.evtype == XIEventType.RawButtonPress;
if (mouse.ScrollX.number == -1 && mouse.ScrollY.number == -1)
+ {
mouse.State.SetScrollRelative(dx, dy);
+ }
}
break;
double h = 0;
double v = 0;
if (d.MotionX.number != -1)
+ {
x = ReadRawValue(ref raw, d.MotionX.number);
+ }
if (d.MotionY.number != -1)
+ {
y = ReadRawValue(ref raw, d.MotionY.number);
+ }
if (d.ScrollX.number != -1)
+ {
h = ReadRawValue(ref raw, d.ScrollX.number) / d.ScrollX.increment;
+ }
if (d.ScrollY.number != -1)
+ {
v = ReadRawValue(ref raw, d.ScrollY.number) / d.ScrollY.increment;
+ }
if (d.MotionX.mode == XIMode.Relative)
+ {
d.State.X += (int)Math.Round(x);
+ }
else
+ {
d.State.X = (int)Math.Round(x);
+ }
if (d.MotionY.mode == XIMode.Relative)
+ {
d.State.Y += (int)Math.Round(y);
+ }
else
+ {
d.State.Y = (int)Math.Round(y);
+ }
// Note: OpenTK follows the windows scrolling convention where
// (+h, +v) = (right, up). XI2 uses (+h, +v) = (right, down)
private Toolkit(Factory factory)
{
if (factory == null)
+ {
throw new ArgumentNullException("factory");
+ }
platform_factory = factory;
}
public static Toolkit Init(ToolkitOptions options)
{
if (options == null)
+ {
throw new ArgumentNullException("options");
+ }
lock (InitLock)
{
private WindowIcon(int width, int height)
{
if (width < 0 || width > 256 || height < 0 || height > 256)
+ {
throw new ArgumentOutOfRangeException();
+ }
this.Width = width;
this.Height = height;
: this(width, height)
{
if (data == null)
+ {
throw new ArgumentNullException();
+ }
if (data.Length < Width * Height * 4)
+ {
throw new ArgumentOutOfRangeException();
+ }
this.Data = data;
}
: this(width, height)
{
if (data == IntPtr.Zero)
+ {
throw new ArgumentNullException();
+ }
// We assume that width and height are correctly set.
// If they are not, we will read garbage and probably