Giter Club home page Giter Club logo

sdl.zig's Introduction

SDL.zig

A Zig package that provides you with the means to link SDL2 to your project, as well as a Zig-infused header implementation (allows you to not have the SDL2 headers on your system and still compile for SDL2) and a shallow wrapper around the SDL apis that allow a more Zig-style coding with Zig error handling and tagged unions.

Getting started

Linking SDL2 to your project

This is an example build.zig that will link the SDL2 library to your project.

const std = @import("std");
const Sdk = @import("Sdk.zig"); // Import the Sdk at build time

pub fn build(b: *std.Build.Builder) !void {
    // Determine compilation target
    const target = b.standardTargetOptions(.{});

    // Create a new instance of the SDL2 Sdk
    const sdk = Sdk.init(b, null);

    // Create executable for our example
    const demo_basic = b.addExecutable(.{
        .name = "demo-basic",
        .root_source_file = .{ .path = "my-game.zig" },
        .target = target,
    });
    sdk.link(demo_basic, .dynamic); // link SDL2 as a shared library

    // Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow)
    demo_basic.root_module.addImport("sdl2", sdk.getNativeModule());

    // Install the executable into the prefix when invoking "zig build"
    b.installArtifact(demo_basic);
}

Using the native API

This package exposes the SDL2 API as defined in the SDL headers. Use this to create a normal SDL2 program:

const std = @import("std");
const SDL = @import("sdl2"); // Add this package by using sdk.getNativeModule

pub fn main() !void {
    if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0)
        sdlPanic();
    defer SDL.SDL_Quit();

    var window = SDL.SDL_CreateWindow(
        "SDL2 Native Demo",
        SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
        640, 480,
        SDL.SDL_WINDOW_SHOWN,
    ) orelse sdlPanic();
    defer _ = SDL.SDL_DestroyWindow(window);

    var renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic();
    defer _ = SDL.SDL_DestroyRenderer(renderer);

    mainLoop: while (true) {
        var ev: SDL.SDL_Event = undefined;
        while (SDL.SDL_PollEvent(&ev) != 0) {
            if(ev.type == SDL.SDL_QUIT)
                break :mainLoop;
        }

        _ = SDL.SDL_SetRenderDrawColor(renderer, 0xF7, 0xA4, 0x1D, 0xFF);
        _ = SDL.SDL_RenderClear(renderer);

        SDL.SDL_RenderPresent(renderer);
    }
}

fn sdlPanic() noreturn {
    const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
    @panic(std.mem.sliceTo(str, 0));
}

Using the wrapper API

This package also exposes the SDL2 API with a more Zig-style API. Use this if you want a more convenient Zig experience.

Note: This API is experimental and might change in the future

const std = @import("std");
const SDL = @import("sdl2"); // Created in build.zig by using exe.root_module.addImport("sdl2", sdk.getWrapperModule());

pub fn main() !void {
    try SDL.init(.{
        .video = true,
        .events = true,
        .audio = true,
    });
    defer SDL.quit();

    var window = try SDL.createWindow(
        "SDL2 Wrapper Demo",
        .{ .centered = {} }, .{ .centered = {} },
        640, 480,
        .{ .vis = .shown },
    );
    defer window.destroy();

    var renderer = try SDL.createRenderer(window, null, .{ .accelerated = true });
    defer renderer.destroy();

    mainLoop: while (true) {
        while (SDL.pollEvent()) |ev| {
            switch (ev) {
                .quit => break :mainLoop,
                else => {},
            }
        }

        try renderer.setColorRGB(0xF7, 0xA4, 0x1D);
        try renderer.clear();

        renderer.present();
    }
}

Sdk.zig API

/// Just call `Sdk.init(b, null)` to obtain a handle to the Sdk!
const Sdk = @This();

/// Creates a instance of the Sdk and initializes internal steps.
/// Initialize once, use everywhere (in your `build` function).
pub fn init(b: *Build, maybe_config_path: ?[]const u8) *Sdk

/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes
/// for a more *ziggy* feeling.
/// This is similar to the *C import* result.
pub fn getNativeModule(sdk: *Sdk) *Build.Module;

/// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on.
pub fn getWrapperModule(sdk: *Sdk) *Build.Module;

/// Links SDL2 to the given exe and adds required installs if necessary.
/// **Important:** The target of the `exe` must already be set, otherwise the Sdk will do the wrong thing!
pub fn link(sdk: *Sdk, exe: *LibExeObjStep, linkage: std.Build.LibExeObjStep.Linkage) void;

Dependencies

All of those are dependencies for the target platform, not for your host. Zig will run/build the same on all source platforms.

Windows

For Windows, you need to fetch the correct dev libraries from the SDL download page. It is recommended to use the MinGW versions if you don't require MSVC compatibility.

MacOS

Right now, cross-compiling for MacOS isn't possible. On a Mac, install SDL2 via brew.

Linux

If you are cross-compiling, no dependencies exist. The build Sdk compiles a libSDL2.so stub which is used for linking.

If you compile to your target platform, you require SDL2 to be installed via your OS package manager.

Support Matrix

This project tries to provide you the best possible development experience for SDL2. Thus, this project supports the maximum amount of cross-compilation targets for SDL2.

The following table documents this. The rows document the target whereas the columns are the build host:

Windows (x86_64) Windows (i386) Linux (x86_64) MacOS (x86_64) MacOS (aarch64)
i386-windows-gnu ⚠️
i386-windows-msvc ⚠️
x86_64-windows-gnu ⚠️
x86_64-windows-msvc ⚠️
x86_64-macos
aarch64-macos ⚠️
x86_64-linux-gnu 🧪 🧪 🧪 ⚠️
aarch64-linux-gnu 🧪 🧪 🧪 🧪 ⚠️

Legend:

  • ✅ Cross-compilation is known to work and tested via CI
  • 🧪 Experimental cross-compilation support, covered via CI
  • ⚠️ Cross-compilation might work, but is not tested via CI
  • ❌ Cross-compilation is not possible right now

Contributing

You can contribute to this project in several ways:

  • Use it!
    This helps me to track bugs (which i know that there are some), and usability defects (which we can resolve then). I want this library to have the best development experience possible.
  • Implement/improve the linking experience:
    Right now, it's not possible to cross-compile for MacOS, which is very sad. We might find a way to do so, though! Also VCPKG is not well supported on windows platforms.
  • Improve the wrapper.
    Just add the functions you need and make a PR. Or improve existing ones. I won't do it for you, so you have to get your own hands dirty!

sdl.zig's People

Contributors

banchouboo avatar beyley avatar clarityflowers avatar clebs avatar darltrash avatar evilarchitextor avatar fabioarnold avatar gertkeno avatar hazeycode avatar henbr avatar iddev5 avatar jack-ji avatar kdx2a avatar lgrt-scms avatar marjohkan avatar markkimsal avatar masterq32 avatar mattnite avatar ominitay avatar p-louw avatar paoda avatar pierrec avatar poiuytrewqaaaaaaaaaaaaaaaa avatar polymethylmethacrylat avatar rohlem avatar silbinarywolf avatar stringflow avatar tecanec avatar ttrei avatar zerozshadow 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

sdl.zig's Issues

Vulkan Support

Bindings to SDL_vulkan.h for Vulkan support currently don't exist and should be added.

HOWTO use IMG

Hello and thank you for this package, it makes SDL easier to use, and sorry if this is not the right place to ask!

I am trying to load some image and wanted to use the src/wrapper/image.zig components but I am running into compile errors, which I am unsure how to adress (sorry I am a Zig newbie).

error(link): undefined reference to symbol '_IMG_LoadTexture'
error(link):   first referenced in '.../zig-cache/o/20640cb1f414271a11369a39446aa7a6/sdl.o'
error: UndefinedSymbolReference

I did install sdl2_image view brew so I am not sure why it cannot find the lib.

Any tips on how to use loadTexture for instance?

Thanks!

Does not work on NixOS due to non standard FHS

build.zig
const std = @import("std");
const Sdk = @import("sdl/Sdk.zig");

pub fn build(b: *std.build.Builder) void {
    const target = b.standardTargetOptions(.{});

    const sdk = Sdk.init(b);

    const mode = b.standardReleaseOptions();

    const exe = b.addExecutable("ziggyboy", "src/main.zig");
    exe.setTarget(target);
    exe.setBuildMode(mode);
    sdk.link(exe, .static);
    exe.addPackage(sdk.getNativePackage("sdl2"));
    // exe.linkSystemLibrary("SDL2");
    // exe.linkSystemLibrary("c");
    exe.install();

    const run_cmd = exe.run();
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);

    const tests = b.addTest("src/main.zig");
    tests.setBuildMode(mode);

    const test_step = b.step("test", "Run all the tests");
    test_step.dependOn(&tests.step);
}
Error from LLD
ld.lld: error: unable to find library -lsdl2
error: LLDReportedFailure
ziggyboy...The following command exited with error code 1:
/nix/store/rfpl182slqas5nq68xbla2901jc6f6c6-zig-master-unstable-2021-06-27/bin/zig build-exe /home/devin/Repos/ziggyboy/src/main.zig -lc -lsdl2 --cache-dir /home/devin/Repos/ziggyboy/zig-cache --global-cache-dir /home/devin/.cache/zig --name ziggyboy --enable-cache
error: the following build command failed with exit code 1:
/home/devin/Repos/ziggyboy/zig-cache/o/fd09d5499e7e1e5f701e4b7c647cdf96/build /nix/store/rfpl182slqas5nq68xbla2901jc6f6c6-zig-master-unstable-2021-06-27/bin/zig /home/devin/Repos/ziggyboy /home/devin/Repos/ziggyboy/zig-cache /home/devin/.cache/zig
My shell.nix
{ pkgs ? import <nixpkgs> { } }:
pkgs.mkShell {
  nativeBuildInputs = with pkgs; [ SDL2 pkgconf ];
  NIX_LD_LIBRARY_PATH =
    pkgs.lib.makeLibraryPath [ pkgs.pkgconf pkgs.SDL2 pkgs.lld ];
  NIX_LD = builtins.readFile "${pkgs.stdenv.cc}/nix-support/dynamic-linker";
}

Using Andrew's build.zig as an example, linking them as system libraries does compile using the shell.nix.

    exe.linkSystemLibrary("SDL2");
    exe.linkSystemLibrary("c");

Might be related to NixOS/nixpkgs#24744

Bug: union field 'shown' ordered differently than corresponding enum field

When I use the wrapper module, I get an error like this error: union field 'shown' ordered differently than corresponding enum field. The error occurs because there is a different field order on the tagged union, the Data type with its Type enum.

none = c.SDL_WINDOWEVENT_NONE,

shown: void,

Reordering the fields will solve the error

zig version: 0.12.0-dev.170+750998eef

linkTtf needs updating.

linkTtf calls std.zig.system.NativeTargetInfo.detect, which is gone thanks to this breaking change.

Here's how far I got:

const target = (std.zig.system.resolveTargetQuery(exe.root_module.resolved_target.?.query) catch @panic("failed to detect native target info!"));

That's clearly wrong, but might have useful pointers for anyone who wants to pick this up. Alternatively, someone who actually knows how build.zig is supposed to work could maybe fix this easily.

Error with windows linking when compiling with zig 0.11.0-dev.750+25d3713b0

When trying to compile the example I get the following error:

/usr/lib/zig/lib/std/build/LibExeObjStep.zig:22:28: error: 'VcpkgRoot' is not marked 'pub'
const VcpkgRoot = std.build.VcpkgRoot;
                  ~~~~~~~~~^~~~~~~~~~
/usr/lib/zig/lib/std/build.zig:1472:1: note: declared here
const VcpkgRoot = union(VcpkgRootStatus) {
^~~~~
referenced by:
    addVcpkgPaths: /usr/lib/zig/lib/std/build/LibExeObjStep.zig:972:17
    link: /strg/prgm/zig/usg/lib/SDL.zig/Sdk.zig:168:12
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

Looking at the source code I see that it is a Windows related error and I'm on Linux, the target os tag says so. Commenting from line 165 to 306 (windows SDL2 linking) makes the error go away and the program runs just fine

cannot use getWrapperModuleVulkan

I cannot use the wrapper w/vulkan-zig without getting an error for the vulkan binding existing in both modules

this is my build.zig

const std = @import("std");
const sdl = @import("lib/SDL.zig/build.zig");
const vkgen = @import("lib/vulkan-zig/generator/index.zig");

pub fn build(b: *std.build.Builder) !void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});


    const exe = b.addExecutable(.{
        .name = "test",
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    const sdk = sdl.init(b, null);
    sdl.link(sdk, exe, .dynamic);
    const gen = vkgen.VkGenerateStep.create(b, "vk.xml");
    
    exe.addModule("sdl2", sdl.getWrapperModuleVulkan(sdk, gen.getModule()));
    exe.addModule("vulkan", gen.getModule());

    const shaders = vkgen.ShaderCompileStep.create(
        b,
        &[_][]const u8{ "glslc", "--target-env=vulkan1.2" },
        "-o",
    );
    shaders.add("triangle_vert", "shaders/triangle.vert", .{});
    shaders.add("triangle_frag", "shaders/triangle.frag", .{});
    exe.addModule("shaders", shaders.getModule());
    
    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run test");
    run_step.dependOn(&run_cmd.step);
}

and this is the error i get

zig-cache/o/ac2f9342bd342b23d954a92e2875a499/vk.zig:1:1: error: file exists in multiple modules
zig-cache/o/ac2f9342bd342b23d954a92e2875a499/vk.zig:1:1: note: root of module vulkan0
zig-cache/o/ac2f9342bd342b23d954a92e2875a499/vk.zig:1:1: note: root of module vulkan

removing the vulkan module and leaving just the sdl2 module does not fix the problem because then I cannot use vulkan at all in my code

translated sdl.zig file is incorrectly big-endian

Not sure why this is happening, but the src/binding/sdl.zig looks like it assumes big endian.

Symptoms (the ones I've found, I'm kind of new to SDL though, there might be more):

  • Audio formats AUDIO_{U,S,F}{16,32}SYS should alias the native byte ordering, but they alias MSB instead of LSB constants.
  • SDL_Swap{LE,BE}{16,32,64} and SDL_SwapFloat{LE,BE} should be no-op for native ordering and only swap for foreign ordering, again it's reversed.

These are observable in the current master branch, it's the same when locally regenerated on my x86_64 (little-endian) windows machine.


Not sure if it's the same issue, but notably, my file also contains some definitions that identify it as a windows instead of a linux build (SDL_SENSOR_WINDOWS, missing the SDL_HAPTIC_LINUX constant from master).
This is despite the -target x86_64-linux-gnu flag given to the zig translate-c invocation in gen_sdl.sh. So is that being ignored, or overruled in some strange way?

Allow build on Windows when Vcpkg exists but SDL is installed manually

When building on Windows, I get this error:

$ zig build --verbose
cp C:\dev\vcpkg\installed\x64-windows-static\bin\SDL2.dll C:\Users\WT\code\ziggame\zig-out\bin\SDL2.dll error: FileNotFound
C:\Users\WT\scoop\apps\zig\current\lib\std\os\windows.zig:123:35: 0x7ff7e960c8e1 in std.os.windows.OpenFile (build.obj)
        .OBJECT_NAME_COLLISION => return error.PathAlreadyExists,
                                  ^
...

error: the following build command failed with exit code 1:
C:\Users\WT\code\ziggame\zig-cache\o\170af392d93d348114ce947d1eeae7d0\build.exe C:\Users\WT\scoop\apps\zig\current\zig.exe C:\Users\WT\code\ziggame C:\Users\WT\code\ziggame\zig-cache C:\Users\WT\AppData\Local\zig --verbose

I have Vcpkg installed, but I don't want to use it for this project. Here, SDK.zig sees that I have a Vcpkg directory configured, and then tries to copy a nonexistent SDL2.dll from that directory, which crashes the build. If I comment that block out, everything works great.

Would it make sense to add a key to .build_config/sdl.json disabling vcpkg?

SDL.zig may not interact well with heap allocated bitmaps

Currently, I'm trying to create a Gameboy Advance Emulator. For graphics, I have chosen to go with SDL2 and have decided to use SDL.zig as an alternative to using direct C bindings. Thank you for your work in creating this library.

I have stumbled across some confusing behaviour and have created a rather trivial example, which I shall link here.

The program creates and renders a white texture in the BGR555 Pixel Format. If you are to run this program, you will find a variable amount of garbage data displayed on the texture like in the screenshot below:
image

If you comment out L37, L38, and L39, and replace &white_heap with &white on L49 (the SDL_UpdateTexture call) the program works as expected, producing:
image

It is my current understanding that where the bitmap was allocated should have no effect on SDL2 displaying the texture itself.

I am quite unfamiliar with SDL.zig and SDL as a whole and therefore do not really know where to get started. I understand that you prefer contributions rather than bug reports and if so, I would at the very least appreciate some assistance regarding how I should go about identifying and resolving this issue.

Build error on latest 0.11 nightly, std.json changes

/SDKs/zig/zig-linux-x86_64-0.11.0-dev.3934+ba6e5e65a/lib/std/json.zig:108:20: error: Deprecated; use parseFromSlice(Value) or parseFromTokenSource(Value) instead.
pub const Parser = @compileError("Deprecated; use parseFromSlice(Value) or parseFromTokenSource(Value) instead.");

Could not build example with `Zig 0.9.1` + Linux

Atfer clone repo, i tried to build project i got that error:

λ zig build
./Sdk.zig:54:9: error: no member named 'source' in struct 'std.build.Pkg'
        .source = .{ .path = sdkRoot() ++ "/src/binding/sdl.zig" },
        ^
./Sdk.zig:82:9: error: no member named 'source' in struct 'std.build.Pkg'
        .source = .{ .path = sdkRoot() ++ "/src/wrapper/sdl.zig" },
   

I found that easiest fix is to change source to path because std.build.Pkg is changed.


I am new in Zig so i do not know if that solution is backward compatible.

Build issue on Windows

Hi,

Specs:

  • Windows 10 x64
  • Zig 0.11.0-dev.2560+602029bb2

I'm trying to compile the Using the native API example from the README with this build script:

const std = @import("std");
const Sdk = @import("libs/SDL.zig/Sdk.zig"); // Import the Sdk at build time

pub fn build(b: *std.Build.Builder) !void {
    // Determine compilation target
    const target = b.standardTargetOptions(.{});
  
    // Create a new instance of the SDL2 Sdk
    const sdk = Sdk.init(b, null);

    // Create executable for our example
    const demo_basic = b.addExecutable(.{
        .name = "demo-basic",
        .root_source_file = .{ .path = "src/main.zig" },
    });
    
    demo_basic.setTarget(target);   // must be done before calling sdk.link
    sdk.link(demo_basic, .dynamic); // link SDL2 as a shared library

    // Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow)
    demo_basic.addModule("sdl2", sdk.getNativeModule()); 

    // Install the executable into the prefix when invoking "zig build"
    demo_basic.install();
}

... and am getting this error running zig build:

J:\Zig\Tests\sdl_test> zig build
J:\Zig\Tests\sdl_test\build.zig:17:15: error: no field or member function named 'setTarget' in 'Build.CompileStep'
    demo_basic.setTarget(target);   // must be done before calling sdk.link
    ~~~~~~~~~~^~~~~~~~~~
J:\Zig\Compiler\bin\lib\std\Build\CompileStep.zig:1:1: note: struct declared here
const builtin = @import("builtin");
^~~~~

Any ideas?

Doesn't build on freebsd

error: ld.lld: undefined symbol: hid_init
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickInit) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_end_parse
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_start_parse
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_get_data
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_get_item
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickUpdate) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_dispose_report_desc
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(BSD_JoystickClose) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(MaybeAddDevice) in archive /usr/local/lib/libSDL2.a
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(MaybeAddDevice) in archive /usr/local/lib/libSDL2.a
    note: referenced 1 more times
error: ld.lld: undefined symbol: inotify_init1
    note: referenced by SDL_sysjoystick.c
    note:               SDL_sysjoystick.o:(LINUX_JoystickInit) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: inotify_add_watch
    note: referenced by SDL_sysjoystick.c
    note:               SDL_sysjoystick.o:(LINUX_JoystickInit) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_get_report_desc
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_get_report_id
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a
error: ld.lld: undefined symbol: hid_report_size
    note: referenced by SDL_bsdjoystick.c
    note:               SDL_bsdjoystick.o:(CreateHwData) in archive /usr/local/lib/libSDL2.a

I addressed this by adding a new section to build.zig:

else if (target.os.tag == .freebsd) {
    exe.linkSystemLibrary("sdl2");
    exe.linkSystemLibrary("inotify");
    exe.linkSystemLibrary("usbhid");
}

I'm not sure what else it will need but that works for the example program at least.

Question: beginner question on why this lib exists?

Hello,

I’m currently looking into building a zig-based game using SDL.

I know that you can import the C code directly using Zigs awesome understanding of C/C++ source code but I’m curious why this library of bindings exists and why you’d want to use it?

I’m only asking because this lib seems very convenient to hide the C complexity away and the possible casting that would need to happen back and forth between the world of zig and C.

Am I on the right track on why using this would be useful?

Thanks for your time!

How to build for Android?

Hi there!

Is there a way to build for Android based on android-project directory in the original SDL repository?

Thanks!

Weird condition in Sdk.zig

The second if's conditions are clearly wrong (both are always false), shouldn't detected_target be involved?

SDL.zig/Sdk.zig

Lines 235 to 236 in 9bef355

} else if (target.os.tag == .linux) {
if (target.os.tag != .linux or target.cpu.arch != target.cpu.arch) {

Renderer.copy srcRect and dstRect arguments flipped

    pub fn copy(ren: Renderer, tex: Texture, dstRect: ?Rectangle, srcRect: ?Rectangle) !void {
        if (c.SDL_RenderCopy(ren.ptr, tex.ptr, if (srcRect) |r| r.getConstSdlPtr() else null, if (dstRect) |r| r.getConstSdlPtr() else null) < 0)
            return makeError();
    }

    pub fn copyF(ren: Renderer, tex: Texture, dstRect: ?RectangleF, srcRect: ?Rectangle) !void {
        if (c.SDL_RenderCopyF(ren.ptr, tex.ptr, if (srcRect) |r| r.getConstSdlPtr() else null, if (dstRect) |r| r.getConstSdlPtr() else null) < 0)
            return makeError();
    }

Seems like an odd change from the source which could be hard to debug if converting from native to wrapper bindings. Though similarly hard to debug if flipped back to match SDL2

Memory leak on example

Im quite new to zig (so i might be doing something dumb like missing a build flag)
But when i run either of the native or wrapper examples, the app will slowly consume more and more memory (im running Arch Linux with an Nvidia graphics card)
Here is it using 1gb of ram after only about a min
img

EDIT: i tried to run it in valgrind, and when using valgrind the leak just disappears? the stack traces valgrind gives for potential leaks isnt very helpful either, with everything being in libnvidia-glcore.so.495.46 or libX11.so.6.4.0

MacOS cross compilation

Hey there!

I'm working on GLFW bindings for Zig that are zero-fuss and support cross compilation. You can read more about how I'm approaching this here.

I noticed your README says:

Right now, it's not possible to cross-compile for MacOS, which is very sad. We might find a way to do so, though! Also VCPKG is not well supported on windows platforms.

I wanted to say I think you can use the same method I'm using for cross compiling GLFW from Linux/Windows -> macOS. Basically, I have packaged the macOS SDK required for cross compilation and have it at https://github.com/hexops/sdk-macos-11.3 -- this also works for compiling on macOS without Xcode installed, which I think is quite nice.

Then from your Zig build script, you can automatically clone it and link it in where needed. e.g. as I am doing here: https://github.com/hexops/mach/blob/main/glfw/build.zig#L196-L270

Feel free to use the same hexops/sdk-macos-11.3 repository if you like (it won't change.) and reuse whatever bits of my build script are useful to you, it's all FOSS :) I'm not actually using SDL.zig, just wanted to offer this as an idea. Feel free to dismiss if not helpful!

God dammit please add ttf support for windows

I mean, most of the library paths are already set via the link() function and thus you only need to do as the other systems.

I even have a better idea but I tried and it's annoying, making the zig build file for SDL2 source code, but the original one is like 30k lines or so and not decryptable (for me at least).

Feel free to don't care and continue on the wrapper, but please, as a more "low-level" programmer : I prefer the native module, and would like to get the SDL_ttf library without messing around with zig's build system and modifying your library implementation to do so.

Also add functions for SDL_image and SDL_mixer please :)

Missing GLtypes support - `SDL_GL`

I am trying to develop another player example for the libvlc-zig - issue#3 project using SDL2 but the referenced example uses OGL together.
However, the binding doesn't have access to the GL types (GLint, GLfloat, GLchar,...) and some functions are not available for use.
How would I get access to these SDL_GL features?

Windows DLL imports.

Hi,
While working with SDL2 in Zig I tried to build whole library trying to incoporate TTF inside my engine. I found out that build cannot find sdl2_image trying to import DLL:

D:\engines\zig-longship-engine\libs\SDL.zig(master -> origin) λ zig build LLD Link... error(link): DLL import library for -lsdl2_image not found error: DllImportLibraryNotFound error: demo-wrapper-image... error: The following command exited with error code 1:

I don't know should I try to build this DLL and put it somewhere? What's the solution here?
Also it would be nice to have a little example how to incorporate TTF code and drawing text.

Using mouse button mask (SDL_BUTTON_LMASK, etc.) leads to compile error

Minimal example:

const sdl = @import("sdl2");

pub fn main() void {
    _ = sdl.SDL_BUTTON_LMASK;
}

The error:

./deps/sdl/src/binding/sdl.zig:2475:32: error: expected type 'u5', found 'c_int'
    return @as(c_int, 1) << (X - @as(c_int, 1));
                               ^

Tested with zig-0.9.1 and zig-0.10.0-dev.1838+3bfb1616d.

The problem is within SDL_BUTTON() function:

SDL.zig/src/binding/sdl.zig

Lines 2474 to 2476 in bf72bbe

pub inline fn SDL_BUTTON(X: c_int) c_int {
return @as(c_int, 1) << (X - @as(c_int, 1));
}

Experimented with intCast: return @as(c_int, 1) << @intCast(u5, (X - @as(c_int, 1)));
It fixes this issue, but I'm not experienced enough to know if this is the correct solution.

VulkanWrapperModule not compiling

Basicly the

.{
    .name = sdk.build.dupe("sdl-native");
    .module = sdk.getNativeVulkanModule(vulkan),
},

is missing.
Could make a pr tomorrow.
Please correct me when im incorrect or stupid.

how to use with Zig's package manager?

build.zig.zon file:

...
        .sdl = .{
            .url = "https://github.com/MasterQ32/SDL.zig/archive/dd46ee3.tar.gz",
            .hash = "12202a0847d24f9c79302fff04e73d65a3342baecf0dfea46ac304eb68109ab6b472",
        }
...

build.zig file:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});

    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "example",
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    const zgl = b.dependency("zgl", .{});
    exe.addModule("zgl", zgl.module("zgl"));

    const sdl = b.dependency("sdl", .{});
    exe.addModule("sdl", sdl.module("sdl"));

    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);

    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);

    const unit_tests = b.addTest(.{
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    const run_unit_tests = b.addRunArtifact(unit_tests);

    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_unit_tests.step);
}

I get this error:

hasan@asus:example$ zig build 
thread 94179 panic: unable to find module 'sdl'
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/debug.zig:373:22: 0x3a18a9 in panicExtra__anon_47103 (build)
    std.builtin.panic(msg, trace, ret_addr);
                     ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/debug.zig:348:15: 0x3787a9 in panic__anon_28777 (build)
    panicExtra(null, null, format, args);
              ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/Build.zig:1707:18: 0x34e347 in module (build)
            panic("unable to find module '{s}'", .{name});
                 ^
/home/hasan/coding/zig/opengl/example/build.zig:19:36: 0x30b0f9 in build (build)
    exe.addModule("sdl", sdl.module("sdl"));
                                   ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/Build.zig:1843:33: 0x2f9cb3 in runBuild__anon_7150 (build)
        .Void => build_zig.build(b),
                                ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/build_runner.zig:298:29: 0x2f58ee in main (build)
        try builder.runBuild(root);
                            ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/start.zig:370:37: 0x2e1325 in posixCallMainAndExit (build)
            var i: usize = 0;
                                    ^
/home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/lib/std/start.zig:243:5: 0x2e0e11 in _start (build)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x4 in ??? (???)
Unwind information for `???:0x4` was not available, trace may be incomplete

error: the following build command crashed:
/home/hasan/coding/zig/opengl/example/zig-cache/o/a5d18aabd80fe14db47c9868cb3b387f/build /home/hasan/opt/zig/zig-linux-x86_64-0.12.0-dev.396+55f0d8b41/zig /home/hasan/coding/zig/opengl/example /home/hasan/coding/zig/opengl/example/zig-cache /home/hasan/.cache/zig

Sdk not linking sdl2_image

When attempting to build on Arch Linux 5.16.8 I get this:

ld.lld: error: undefined symbol: IMG_Init

Adding this line to Sdk.zig seems to fix the problem:

// . . .

} else {
    // on linux, we should rely on the system libraries to "just work"
    exe.linkSystemLibrary("sdl2");
    exe.linkSystemLibrary("sdl2_image"); // <--
}

// . . .

Largely unfamiliar with the zig build system, so I might be doing something wrong.

Zig std version supported.

Which version of the zig std is this library mainly aimed at?
I was using it with compiler version 0.9.1 up until yesterday.

The latest pr changes the pkg sources path to match the latest commit of the zig git
repo. Asking it here since I wasn't able to find this in the readme.

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.