|
| 1 | +# Copyright (c) 2021 Richard Smith and others |
| 2 | +# |
| 3 | +# This program and the accompanying materials are made available under the |
| 4 | +# terms of the Eclipse Public License 2.0 which is available at |
| 5 | +# http://www.eclipse.org/legal/epl-2.0. |
| 6 | +# |
| 7 | +# This Source Code may also be made available under the following Secondary |
| 8 | +# licenses when the conditions for such availability set forth in the Eclipse |
| 9 | +# Public License, v. 2.0 are satisfied: GNU General Public License, version 2 |
| 10 | +# with the GNU Classpath Exception which is |
| 11 | +# available at https://www.gnu.org/software/classpath/license.html. |
| 12 | +# |
| 13 | +# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 |
| 14 | +import re |
| 15 | +import weakref |
| 16 | +from array import array |
| 17 | + |
| 18 | +from raylib import rl, ffi |
| 19 | +from raylib.colors import * |
| 20 | + |
| 21 | +try: |
| 22 | + from raylib.defines import * |
| 23 | +except AttributeError: |
| 24 | + print("sorry deprecated enums dont work on dynamic version") |
| 25 | + |
| 26 | +from inspect import getmembers, isbuiltin |
| 27 | + |
| 28 | +current_module = __import__(__name__) |
| 29 | + |
| 30 | + |
| 31 | +def _underscore(word: str) -> str: |
| 32 | + word = re.sub('2D$', '_2d', word) |
| 33 | + word = re.sub('3D$', '_3d', word) |
| 34 | + word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word) |
| 35 | + word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word) |
| 36 | + word = word.replace("-", "_") |
| 37 | + return word.lower() |
| 38 | + |
| 39 | + |
| 40 | +def _wrap_function(original_func): |
| 41 | + c_args = [str(x) for x in ffi.typeof(original_func).args] |
| 42 | + number_of_args = len(c_args) |
| 43 | + c_arg_is_pointer = [x.kind == 'pointer' for x in ffi.typeof(original_func).args] |
| 44 | + c_arg_is_string = [str(x) == "<ctype 'char *'>" for x in ffi.typeof(original_func).args] |
| 45 | + # c_arg_is_void_pointer = [str(x) == "<ctype 'void *'>" for x in ffi.typeof(original_func).args] |
| 46 | + |
| 47 | + def wrapped_func(*args): |
| 48 | + args = list(args) # tuple is immutable, converting it to mutable list is faster than constructing new list! |
| 49 | + for i in range(number_of_args): |
| 50 | + try: |
| 51 | + arg = args[i] |
| 52 | + except IndexError: |
| 53 | + raise RuntimeError(f"function requires {number_of_args} arguments but you supplied {len(args)}") |
| 54 | + if c_arg_is_pointer[i]: |
| 55 | + if c_arg_is_string[i]: # we assume c_arg is 'const char *' |
| 56 | + try: # if it's a non-const 'char *' then user should be supplying a ctype pointer, not a Python |
| 57 | + # string |
| 58 | + args[i] = arg.encode('utf-8') # in that case this conversion will fail |
| 59 | + except AttributeError: # but those functions are uncommon, so quicker on average to try the |
| 60 | + # conversion |
| 61 | + pass # and ignore the exception |
| 62 | + # if user supplied a Python string but c_arg is a 'char *' not a 'const char *' then we ought to raise |
| 63 | + # exception because its an out |
| 64 | + # parameter and user should supply a ctype pointer, but we cant because cffi cant detect 'const' |
| 65 | + # so we would have to get the info from raylib.json |
| 66 | + elif c_args[i] == "<ctype 'char * *'>" and type(arg) is list: |
| 67 | + args[i] = [ffi.new("char[]", x.encode('utf-8')) for x in arg] |
| 68 | + elif is_cdata(arg) and "*" not in str(arg): |
| 69 | + args[i] = ffi.addressof(arg) |
| 70 | + elif arg is None: |
| 71 | + args[i] = ffi.NULL |
| 72 | + elif not is_cdata(arg): |
| 73 | + if c_args[i] == "<ctype '_Bool *'>": |
| 74 | + raise TypeError( |
| 75 | + f"Argument {i} ({arg}) must be a ctype bool, please create one with: pyray.ffi.new('bool " |
| 76 | + f"*', True)") |
| 77 | + elif c_args[i] == "<ctype 'int *'>": |
| 78 | + raise TypeError( |
| 79 | + f"Argument {i} ({arg}) must be a ctype int, please create one with: pyray.ffi.new('int " |
| 80 | + f"*', 1)") |
| 81 | + elif c_args[i] == "<ctype 'float *'>": |
| 82 | + raise TypeError( |
| 83 | + f"Argument {i} ({arg}) must be a ctype float, please create one with: pyray.ffi.new(" |
| 84 | + f"'float *', 1.0)") |
| 85 | + elif c_args[i] == "<ctype 'void *'>": |
| 86 | + # we could assume it's a string and try to convert it but we would have to be sure it's |
| 87 | + # const. that seems reasonable assumption for char* but i'm not confident it is for void* |
| 88 | + raise TypeError( |
| 89 | + f"Argument {i} ({arg}) must be a cdata pointer. Type is void so I don't know what type it " |
| 90 | + f"should be." |
| 91 | + "If it's a const string you can create it with pyray.ffi.new('char []', b\"whatever\") . " |
| 92 | + "If it's a float you can create it with pyray.ffi.new('float *', 1.0)") |
| 93 | + |
| 94 | + result = original_func(*args) |
| 95 | + if result is None: |
| 96 | + return |
| 97 | + elif is_cdata(result) and str(result).startswith("<cdata 'char *'"): |
| 98 | + if str(result) == "<cdata 'char *' NULL>": |
| 99 | + return "" |
| 100 | + else: |
| 101 | + return ffi.string(result).decode('utf-8') |
| 102 | + else: |
| 103 | + return result |
| 104 | + |
| 105 | + # apparently pypy and cpython produce different types so check for both |
| 106 | + def is_cdata(arg): |
| 107 | + return str(type(arg)) == "<class '_cffi_backend.__CDataOwn'>" or str( |
| 108 | + type(arg)) == "<class '_cffi_backend._CDataBase'>" |
| 109 | + |
| 110 | + return wrapped_func |
| 111 | + |
| 112 | + |
| 113 | +global_weakkeydict = weakref.WeakKeyDictionary() |
| 114 | + |
| 115 | + |
| 116 | +def _make_struct_constructor_function(struct): |
| 117 | + def func(*args): |
| 118 | + # print(struct, args) |
| 119 | + modified_args = [] |
| 120 | + for (field, arg) in zip(ffi.typeof(struct).fields, args): |
| 121 | + # print("arg:", str(arg), "field:", field[1], "field type:", field[1].type, "type(arg):", str(type(arg))) |
| 122 | + if arg is None: |
| 123 | + arg = ffi.NULL |
| 124 | + elif (field[1].type.kind == 'pointer' |
| 125 | + and (str(type(arg)) == "<class 'numpy.ndarray'>" |
| 126 | + or isinstance(arg, (array, bytes, bytearray, memoryview)))): |
| 127 | + arg = ffi.from_buffer(field[1].type, arg) |
| 128 | + modified_args.append(arg) |
| 129 | + s = ffi.new(f"struct {struct} *", modified_args)[0] |
| 130 | + global_weakkeydict[s] = modified_args |
| 131 | + return s |
| 132 | + |
| 133 | + return func |
| 134 | + |
| 135 | + |
| 136 | +for name, attr in getmembers(rl): |
| 137 | + # print(name, attr) |
| 138 | + uname = _underscore(name) |
| 139 | + if isbuiltin(attr) or str(type(attr)) == "<class '_cffi_backend.__FFIFunctionWrapper'>" or str( |
| 140 | + type(attr)) == "<class '_cffi_backend._CDataBase'>": |
| 141 | + # print(attr.__call__) |
| 142 | + # print(attr.__doc__) |
| 143 | + # print(dir(attr)) |
| 144 | + # print(dir(attr.__repr__)) |
| 145 | + f = _wrap_function(attr) |
| 146 | + setattr(current_module, uname, f) |
| 147 | + else: |
| 148 | + setattr(current_module, name, attr) |
| 149 | + |
| 150 | +for struct in ffi.list_types()[0]: |
| 151 | + f = _make_struct_constructor_function(struct) |
| 152 | + setattr(current_module, struct, f) |
| 153 | + |
| 154 | +# overwrite ffi enums with our own |
| 155 | +from raylib.enums import * |
| 156 | + |
| 157 | + |
| 158 | +def text_format(*args): |
| 159 | + raise RuntimeError("Use Python f-strings etc rather than calling text_format().") |
0 commit comments