GithubHelp home page GithubHelp logo

overdev / raylib-py Goto Github PK

View Code? Open in Web Editor NEW
191.0 5.0 19.0 33.07 MB

A Python binding for the great C library raylib.

License: Other

Python 100.00%
pygame arcade pyglet gamedev gamedev-library 2d 3d vr pbr-shading python3

raylib-py's Introduction

raylib-py

PyPI - Python Version GitHub release (latest by date) GitHub Release Date

PyPI - Wheel PyPI - License PyPI - Downloads

GitHub all releases GitHub release (by tag) GitHub forks

GitHub commit activity GitHub commits since tagged version

A python binding for the great C library raylib.

WARNING: This is a releases-only repository.

Please, read this issue for more information.

I intend to use this repository only to publish new raylib-py releases. The source in this repo is pretty much outdated and does not reflect the latest release.

Release Information:

The latest release published here was generated from another project, as mentioned in #45.

How to install:

From PyPI, in the CLI:

$ pip install raylib-py

You can also download the wheel from the releases page and install it with pip locally:

$ pip install path/to/raylib_py-5.0.0-py3-none-any.whl

How to use:

Try this (after installed raylib-py, create a new python file, save the code below into it, then run it):

from raylibpy import *


def main():

    init_window(800, 450, "raylib [core] example - basic window")

    set_target_fps(60)

    while not window_should_close():

        begin_drawing()
        clear_background(RAYWHITE)
        draw_text("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY)
        end_drawing()

    close_window()


if __name__ == '__main__':
    main()

API Documentation

Please refer to DOCS.md for v5.0.0b1

Features:

  • PEP8 naming convention only:

    Structure attributes are in snake_case, classes and other types in PascalCase.

  • Type hinting (not type annotation):

    def get_ray_collision_mesh(ray, mesh, transform):
        # type: (Ray, Mesh, Matrix) -> RayCollision
  • structures with functions as methods and properties:

    sound = Sound.load('my/resorces/sound.wav')     # same as load_sound(...)
    position = Vector(4.0, 10.0)
    
    # later...
    sound.play()                                    # same as play_sound(sound)
    length = position.length                        # same as vector2length(position); uses raymath.h functions
  • Vector{2,3,4}, Rectangle and Color have attribute swizzling;

    vec3 = Vector3(2.0, 5.0, 3.0)
    vec2 = vec3.zxy                 # vec2 is a Vector2, not a sequence type
    other_vec3 = vec2.xxy           # same thing: other_vec3 is a Vector3
    vec2.xy = vec3.y, other_vec3.z  # sequences can be set as values
    
    c_red = Color(255, 0, 0)
    c_yellow = c_red.rrb
    
    # Rectangles have aliases for width and height: w and h respectively:
    rect = Rectangle(10.0, 10.0, 320.0, 240.0)
    other_rect = rect.whxy          # swizzling is only allowed when using four attributes, not 3 nor 2
  • Pretty printing: most structures implement __str__() and __repr__() in a friendly way;

  • Context managers: begin_* and end_* functions can be called as context managers:

    Without context managers:

    # this example shows a rendering step
    
    begin_drawing()
    
    begin_texture_mode(minimap_texture)
    # render the "minimap"
    draw_line(2, 2, 5, 5, RED)
    end_texture_mode(minimap_texture)
    
    begin_mode2d(main_camera)
    # 2d drawing logic...
    draw_texture(minimap_texture, 10, 10, WHITE)
    end_mode2d()
    
    end_drawing()

    With context managers:

    # this example shows a rendering step
    
    with drawing():
    
        with texture_mode(minimap_texture):
            # render the minimap
            draw_line(2, 2, 5, 5, RED)
    
        with mode2d(main_camera):
            # 2d drawing logic...
            draw_texture(minimap_texture, 10, 10, WHITE)
  • Context managers for some structures: Camera{2,3}D, Shader and others;

    Folowing the example above:

    # this example shows a rendering step
    
    with drawing():
    
        with minimap_texture:
            # render the minimap
            draw_line(2, 2, 5, 5, RED)
    
        with main_camera:
            # 2d drawing logic...
            draw_texture(minimap_texture, 10, 10, WHITE)
  • RLGL and RayMath functions exposed

    Includes all symbols in raymath.h and rlgl.h

Issues:

  • Callback for logging will not work

    I've no good workaround for wrapping C functions with variable number of arguments. If you know how to solve this issue, your help would be appreciated.

  • Functions with vararg will not work

    For the reason above.

  • Avoid string manipulation functions

    For the reason above, also because some functions involve memory allocation and manual freeing of resources. Python string methods can provide you with same and more functionality.

  • Some examples are broken due to API changes

    There was some function renaming, some changes in the examples to update to newer releases.

Would you like to have a more customized binding for raylib?

Again, in issue 45 I explain the actual state of this project in more detail.

It my seems like bad news but actually it is the contrary.

Please, take a look at this project: raylibpyctbg

raylib-py's People

Contributors

cronos87 avatar flipcoder avatar memorix101 avatar overdev avatar pebaz avatar rfaile313 avatar tankorsmash avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

raylib-py's Issues

import error on raspberry pi

Hi,

I have a fresh install of the raspbian minimal image, installed all the necessary prerequisites and tried to run from raylibpy import * which failed with the following:

Traceback (most recent call last): File "main.py", line 1, in <module> from raylibpy import * File "/home/pi/.local/lib/python3.5/site-packages/raylibpy/__init__.py", line 3088 files: list = [] ^ SyntaxError: invalid syntax

using Python 3.5.3

thanks for looking into it and any help is appreciated!

Error importing

I just followed the instructions an got this error.

Traceback (most recent call last): File "G:\programming_projects\RaylibPyGame\main.py", line 5, in <module> import raylibpy File "G:\programming_projects\RaylibPyGame\.venv\lib\site-packages\raylibpy\__init__.py", line 71, in <module> _rl = CDLL(os.path.join(RAYLIB_BIN_PATH, _lib_filename[_platform])) File "C:\Python39\lib\ctypes\__init__.py", line 374, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid Win32 application

'_rl' is not defined

I'm trying to run one of the examples:

import os
os.environ["RAYLIB_BIN_PATH"] = "libraylib.dll"

from raylibpy import *

init_window(800, 450, "raylib [core] example - basic window")

set_target_fps(60)

while not window_should_close():

    begin_drawing()
    clear_background(RAYWHITE)
    draw_text("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY)
    end_drawing()

close_window()

and im getting the error:

Traceback (most recent call last):
  File "rlibtest.py", line 4, in <module>
    from raylibpy import *
  File "C:\Users\Mateus\AppData\Local\Programs\Python\Python37\lib\site-packages\raylibpy\__init__.py", line 2695, in <module>
    _rl.InitWindow.argtypes = [Int, Int, CharPtr]
NameError: name '_rl' is not defined

Bug in `_color`?

In the return it uses r for green as well. Is this a bug? Should I create a PR instead to solve this?

raylib-py/raylibpy/core.py

Lines 224 to 229 in 786efdc

def _color(seq: AnyRGB) -> 'Color':
if isinstance(seq, Color):
return seq
r, g, b, q = seq
rng = 0, 255
return Color(_int(r, rng), _int(r, rng), _int(b, rng), _int(q, rng))

To reproduce

  1. Get raylibpy-3.7 branch installed
  2. Write this code:
from raylibpy.colors import *
from raylibpy.consts import *
from raylibpy.pythonic import *
from raylibpy.spartan import clear_background, drawing

window = Window(800, 600, "Sum title")

while not window.should_close:
    with drawing():
        clear_background((255, 0, 0, 255))
  1. Run it

Expectations

Screen is red

Reality

Screen is yellow

MOUSE_*_BUTTON is deprecated, should use MOUSE_BUTTON_*

Comments in raylib indicate that the MOUSE_{LEFT,RIGHT,MIDDLE}_BUTTON enum is deprecated in favour of MOUSE_BUTTON_{LEFT,RIGHT,MIDDLE}

raylib.h

// Add backwards compatibility support for deprecated names
#define MOUSE_LEFT_BUTTON   MOUSE_BUTTON_LEFT
#define MOUSE_RIGHT_BUTTON  MOUSE_BUTTON_RIGHT
#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE

// Mouse buttons
typedef enum {
    MOUSE_BUTTON_LEFT    = 0,
    MOUSE_BUTTON_RIGHT   = 1,
    MOUSE_BUTTON_MIDDLE  = 2,
    MOUSE_BUTTON_SIDE    = 3,
    MOUSE_BUTTON_EXTRA   = 4,
    MOUSE_BUTTON_FORWARD = 5,
    MOUSE_BUTTON_BACK    = 6,
} MouseButton;

raylib-py currently exposes MOUSE_LEFT_BUTTON, etc.

working with raylib 3.1.0

I'm surprised what actually just works, there are some changed function names but so far I have all the example python code working that I have tried, will need to work through all of raylib.h just yet

looking through the binding I can see its obviously well done, however if I'm going to teach my nephew python, then I'd rather do it with a more up to date version of raylib !

Once I have this more licked into shape - is it worth me doing a PR ?

Shared object bit count mismatch with python interpreter error.

I get the following error when importing raylibpy:

import raylibpy
  File "/home/----/.local/lib/python3.8/site-packages/raylibpy/__init__.py", line 71, in <module>
    _rl = CDLL(os.path.join(RAYLIB_BIN_PATH, _lib_filename[_platform]))
  File "/usr/lib/python3.8/ctypes/__init__.py", line 373, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /home/----/.local/lib/python3.8/site-packages/raylibpy/libraylib.so.2.0.0: wrong ELF class: ELFCLASS32

I believe this is due to running 64bit python, but the shared object included in this project is 32bit. Could you also include a 64bit version that is dlopened instead when running 64bit python?

import raylibpy -> "wrong ELF class: ELFCLASS32"

I'm getting an error when I use "import raylibpy". I think it built a 32-bit library when it should be using 64-bit?

Traceback (most recent call last): File "./raylib_project.py", line 3, in <module> import raylibpy as raylib File "/usr/lib/python3.7/site-packages/raylib_py-0.1.1-py3.7.egg/raylibpy/__init__.py", line 71, in <module> _rl = CDLL(os.path.join(RAYLIB_BIN_PATH, _lib_filename[_platform])) File "/usr/lib/python3.7/ctypes/__init__.py", line 356, in __init__ self._handle = _dlopen(self._name, mode) OSError: /usr/lib/python3.7/site-packages/raylib_py-0.1.1-py3.7.egg/raylibpy/libraylib.so.2.0.0: wrong ELF class: ELFCLASS32

OS: Manjaro Linux (64-bit)

Both AUR and setup.py installations have same error.

Any ideas?

Merge `raylibpy-3.7` to master

The current master branch is using an old version of raylib which is not API compatible with the latest 3.x branch.
The 3.7 branch seems to be working - although I haven't exhaustively tested.
Are there any reasons to not merge 3.7 to master?

Error when open my export project

I was finish my game and export it by pyinstaller, but when I run the file, it error:

Traceback (most recent call last):
File "main.py", line 1, in
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
File "raylibpy_init
.py", line 68, in
RuntimeError: Unable to find raylib library ('libraylib_shared.dll').

Model Animation bug

Loading 3D skeletal animation or updating model with said animation doesn't seem to work properly. I have tried almost identical pieces of code for both python and the Zig binding for raylib. It works correctly for the zig version.

Here's the comparison:

Python

Screenshot

animation_python

Code

import raylibpy as rl

def main():
    width = 800
    height = 600
    rl.init_window(width, height, "Model animation test")
    rl.set_target_fps(60)

    camera = rl.Camera(
        position = rl.Vector3( x = 0, y = 5, z = 15 ),
        target = rl.Vector3( x = 0, y = 0, z = 0 ),
        up = rl.Vector3( x = 0, y = 1, z = 0 ),
        fovy = 45,
        projection = rl.CAMERA_PERSPECTIVE
    )

    modelPath = "resources/3d_models/avatar_rigged.glb"

    model = rl.load_model(modelPath)
    
    animCount = 0
    anims = rl.load_model_animations(modelPath, animCount)
    for anim in anims:
        print("%s" % anim.name)

    anim = anims[0]
    print(f"{anim}")

    frameCounter = 0

    while not rl.window_should_close():
        rl.begin_drawing()
        rl.clear_background(rl.RAYWHITE)

        rl.update_model_animation(model, anim, 0)
        # rl.update_model_animation(model, anim, frameCounter)
        frameCounter = (frameCounter + 1) % anim.frame_count

        rl.begin_mode3d(camera)

        rl.draw_model_ex(model, rl.vector3_zero(), rl.Vector3(1, 0, 0), 0, rl.Vector3(1, 1, 1), rl.WHITE)
        
        rl.end_mode3d()
        
        rl.end_drawing()
    
    model.unload()
    rl.close_window()

if __name__ == '__main__':
    main()

Zig

Screenshot

animation_zig

Code

const std = @import("std");
const rl = @import("raylib");

pub fn main() !void {
    const width = 800;
    const height = 600;
    rl.initWindow(width, height, "Model animation test");
    defer rl.closeWindow();
    rl.setTargetFPS(60);

    var camera = rl.Camera{
        .position = .{ .x = 0, .y = 5, .z = 15 },
        .target = .{ .x = 0, .y = 0, .z = 0 },
        .up = .{ .x = 0, .y = 1, .z = 0 },
        .fovy = 45,
        .projection = .camera_perspective,
    };

    const modelPath = "../resources/3d_models/avatar_rigged.glb";

    var model = rl.loadModel(modelPath);
    defer model.unload();

    const anims = try rl.loadModelAnimations(modelPath);
    for (anims) |anim| {
        std.debug.print("{s}\n", .{anim.name});
    }

    const anim = anims[0];
    std.debug.print("{any}", .{anim});

    var frameCounter: c_int = 0;

    while (!rl.windowShouldClose()) {
        rl.beginDrawing();
        rl.clearBackground(rl.Color.ray_white);

        rl.updateModelAnimation(model, anim, 0);
        // rl.updateModelAnimation(model, anim, frameCounter);
        frameCounter = @mod(frameCounter + 1, anim.frameCount);

        camera.begin();

        model.drawEx(rl.Vector3.zero(), rl.Vector3{ .x = 1, .y = 0, .z = 0 }, 0, rl.Vector3{ .x = 1, .y = 1, .z = 1 }, rl.Color.white);

        camera.end();

        rl.endDrawing();
    }
}

It shows as expected on the zig version but breaks in the python version.

Another thing is that python version seems to load 1 less frame of animation compared to zig version
Here are the log messages for animations loading:

Python

INFO: MODEL: [resources/3d_models/avatar_rigged.glb] Loaded animation: ArmatureAction (3 frames, 0.066667s)
INFO: MODEL: [resources/3d_models/avatar_rigged.glb] Loaded animation: Armature|mixamo.com|Layer0 (3 frames, 0.066667s)

Zig

INFO: MODEL: [../resources/3d_models/avatar_rigged.glb] Loaded animation: ArmatureAction (4 frames, 0.066667s)
INFO: MODEL: [../resources/3d_models/avatar_rigged.glb] Loaded animation: Armature|mixamo.com|Layer0 (4 frames, 0.066667s)

And from my testing with 2 different animations, this only occurred when I used an animation with duplicate or hold keyframes in animation (in blender, don't how gltf stores animation. The animation in the screenshot only has 1 keyframe for the pose at the very beginning and another duplicate keyframe in blender) but not for an animation where every keyframe is unique (again, in blender) for the animation I downloaded from mixamo. I don't know how helpful this bit of information is.

I think the combination of 1 less frame and duplicate keyframes appears to cause this.

can't use loaded font

Like i said:

font = load_font("/xxx/KAISG.ttf")
draw_text_ex(font, "asdasd", Vector2(19, 640), 30, 2, BLACK)

Doing nothing

Error when importing raylibpy

Hello, I really like raylib and it works without any problem in C
Today i wanted to use it inside python, I didpip install raylib-py then opened a python terminal to import it import raylibpy and i got this error message
Screenshot_20200515_165743
What does that error mean?

Typo in README

python -m pip install raylip-py needs to be python -m pip install raylib-py

Please, do not fork/use this project

It may seem that this project is abandoned and, in some sense it is.

In the first days of this project I encountered some difficulties related to the maintenance of the code. Raylib is a fast growing library and I wasn't having enough time to keep raylib-py up to speed. Maybe it was my lack of experience.

I started to look for a better way to maintain the code. In a frustrated attempt I've tried to create a bind generator that would translate the c headers into a python source file. I failed due to the complexity of parsing c headers, but I got close to something that would work.

Some time later, Raymon (raylib's author) came with a tool in c that would do the parsing and generate the desired information in some file formats like JSON, XML and others. That was exactly what I need move forward.

Back in august, this year, I started implementing it and today it reached a point in the development where I'm able to talk about it publicly.

Instead of creating a bind generator for my own use, I decided to make it as a tool, such that anyone can use to create his/her own binding and customize it as seen fit. It works via command line, it has a lot of options (like keeping names in python or C99 convention, and whether/how to add typing information), You can also use it to generate a cheat sheet in markdown. Finally, if that's not enough, there's also a template package if you desire to build a python package with the generated binding and install it on your system (includes a tutorial on how to make it).

EDIT: the main advantage of this new approach is that you become version independent: whenever a new C raylib is released, all you have todo, in the best scenario, replace a couple files and rerun the bind generator. No need to wait for pypi package updates (you can just make your own package).

The repo for this bind generator is raylibctbg ('ctbg' stands for CTypes Binding Generator). There you can learn more about features, howtos and more.

Somewhere in the future I'll add the C raylib examples translated to python, to be able to test and ensure everything is working as expected.

Please, give it a try and send me some feedback.

Is raylib 3.5 Compatible

Hello!

Is the library actually compatible with the new release of raylib 3.0?

Thank you for the answer!

Calling `begin_drawing` causes a segmentation fault

I just tried running this code:

import raylibpy
raylibpy.begin_drawing()
raylibpy.end_drawing()

It exited with Segmentation fault: 11 (on macOS 10.14.3). I tried it with my copy of raylib and the bundled one, with the same result.

Model Texturing Bug

Problem Statement: examples/models/models_heightmap.py shows that textures are not applied when rendering models.

Raylib-C Equivalent Example (Shows darkened edges of the model due to texture used):
image

Raylib-Py Example of Issue (Shows that the model is completely red instead of using the texture):
image

pip version import does not work on 64 bit Ubuntu 20.04

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import raylibpy as r
  File "/home/creikey/Documents/grayviewer/env/lib/python3.8/site-packages/raylibpy/__init__.py", line 71, in <module>
    _rl = CDLL(os.path.join(RAYLIB_BIN_PATH, _lib_filename[_platform]))
  File "/home/creikey/.pyenv/versions/3.8.5/lib/python3.8/ctypes/__init__.py", line 373, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /home/creikey/Documents/grayviewer/env/lib/python3.8/site-packages/raylibpy/libraylib.so.2.0.0: wrong ELF class: ELFCLASS32

Binding tool

Hi,

Out of curiosity, what binding tool did you use to create your binding ? I am looking at pybind11 right now.

Has this repo been abandoned?

Hey this repo is linked to from the raylib homepage but it looks like master is only on 2.0 while 4.0 is the most recent version out. Just wondering is there a reason for this or does the owner not have the free time to keep it updated? Do you want others to contribute?

Bug in the README

The README uses RAYLIB_LIB_PATH like a name, but it should be a string. This...

os.environ[RAYLIB_LIB_PATH] = "path/to/the/binary"

...should be...

os.environ["RAYLIB_LIB_PATH"] = "path/to/the/binary"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.