Giter VIP home page Giter VIP logo

rust_minifb's Introduction

Build Status Crates.io Documentation

minifb is a cross platform library written in Rust and that makes it easy to setup a window and to (optional) display a 32-bit pixel buffer. It also makes it easy to get input from keyboard and mouse. Notice that minifb is primary designed for prototyping and may not include all the features found in full window handling libraries. An example is the best way to show how it works:

Changelog

Usage

# Cargo.toml
[dependencies]
minifb = "0.25"

Example

use minifb::{Key, Window, WindowOptions};

const WIDTH: usize = 640;
const HEIGHT: usize = 360;

fn main() {
    let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];

    let mut window = Window::new(
        "Test - ESC to exit",
        WIDTH,
        HEIGHT,
        WindowOptions::default(),
    )
    .unwrap_or_else(|e| {
        panic!("{}", e);
    });

    // Limit to max ~60 fps update rate
    window.limit_update_rate(Some(std::time::Duration::from_micros(16600)));

    while window.is_open() && !window.is_key_down(Key::Escape) {
        for i in buffer.iter_mut() {
            *i = 0; // write something more funny here!
        }

        // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way
        window
            .update_with_buffer(&buffer, WIDTH, HEIGHT)
            .unwrap();
    }
}

Status

Currently macOS, Linux and Windows (64-bit and 32-bit) are the current supported platforms. X11 (Linux/FreeBSD/etc) support has been tested on Ubuntu (x64). Linux Wayland support is also available. Bug report(s) for other OSes/CPUs are welcome! Notice: That after 0.13 Redox hasn't been updated and some work is required to get that working again. PR are welcome.

Build instructions

On Linux you may need to install these dependencies first:

sudo apt install libxkbcommon-dev libwayland-cursor0 libwayland-dev
cargo build
cargo run --example noise

This will run the noise example

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

rust_minifb's People

Contributors

andreasom avatar arifroktim avatar dc740 avatar dependabot-preview[bot] avatar emoon avatar fauxfaux avatar hiqua avatar kondrak avatar mightypork avatar mikaelurankar avatar mvforell avatar nbdd0121 avatar nelsonjchen avatar noi42 avatar razrfalcon avatar rfwatson avatar richardhozak avatar rupansh avatar sndels avatar speykious avatar stefanoincardone avatar tdaffin avatar thewatchmen avatar thisjaiden avatar vemoo avatar vmedea avatar wtfuzz avatar xkevio avatar xobs avatar xtibor 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rust_minifb's Issues

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 rust_minifb developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT/Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

Segfault on arm using nightly rust 1.6

Continuing from emoon/minifb#2, here's the backtrace after the s.as_ptr() as *const _ hack:

Starting program: /tmp/rust64-master/target/debug/rust64
Program received signal SIGSEGV, Segmentation fault.
0x7f57cc4c in mfb_update (buffer=0xb6458000) at src/native/x11/X11MiniFB.c:128
128             s_ximage->data = (char*)buffer;
(gdb) bt
#0  0x7f57cc4c in mfb_update (buffer=0xb6458000) at src/native/x11/X11MiniFB.c:128
#1  0x7f57c6f8 in minifb::update (buffer=...)
    at /home/odroid/.cargo/git/checkouts/rust_minifb-65b6a7c68ef60bd2/master/src/lib.rs:53
#2  0x7f55ff88 in rust64::c64::C64::render (self=0xbeffec78) at src/c64/mod.rs:89
#3  0x7f55cb38 in rust64::main () at src/main.rs:68
#4  0x7f586874 in sys_common::unwind::try::try_fn::h3067093340196622558 ()
#5  0x7f583c80 in __rust_try ()
#6  0x7f5863e0 in rt::lang_start::h6fedeacd81917c3471x ()
#7  0x7f560034 in main () at src/c64/mod.rs:90

Stack overflow on OS X 10.10.5 (mid-2014 macbook pro)

When building and running the noise example, the stack overflows:

$ cargo run --example noise
    Updating registry `https://github.com/rust-lang/crates.io-index`
 Downloading gcc v0.3.21
   Compiling winapi-build v0.1.1
   Compiling libc v0.2.4
   Compiling winapi v0.2.5
   Compiling gcc v0.3.21
   Compiling kernel32-sys v0.2.1
   Compiling minifb v0.2.3 (file:///Users/yupferris/dev/projects/rust_minifb)
   Compiling time v0.1.34
     Running `target/debug/examples/noise`

thread '<main>' has overflowed its stackAn unknown error occurred

To learn more, run the command again with --verbose.

This has been happening for a couple months since I first tried the lib on os x, but I didn't report it as I thought you'd be working on stuff further and it might be known.

This happens in both debug and release builds.

'Plonk sound' on keyboard input in macOS 10.12 Sierra Beta

I just noticed when turning up the sound on OSX 10.12, a 'key plonk' sound is played when a key is pressed in a minifb window (as if the the window isn't accepting keyboard input). It's the same sound that plays when you look at a text file with 'less', and try to scroll past the end when hitting the Space key, or when you go to "About this Mac" in the Apple menu, and try Cut/Copy/Paste in the about-window.

This reproduces in the minifb examples (e.g. the noise example), just run the sample and start pressing keys.

I don't know whether this also happens on older OSX versions. The complete version number of the 10.12 Beta is "10.12 Beta (16A254g)".

Issues with tiling window manager.

Hey, I'm trying to run an old project using minifb. I'm having issues due to using a tiling window manager. I believe the window manager forces the window to be a specific size which the input buffer is too small to fill.

Sometimes the program will segfault, and other sometimes it will panic with

thread 'main' panicked at 'Failed to update window buffer.: UpdateFailed("Update failed because input buffer is too small. Required size for 1916 x 525 window (1x scale) is 4023600 bytes but the size of the input buffer has the size 1310
2 bytes")', libcore/result.rs:1009:5

Thanks.

Scaling not working on XWayland.

Hi. Currently on an X11 system but I'll try to get more details for you later.

The minifb::Scale option appears to have no effect on Wayland. I also seem to remember seeing an info message saying that only minifb::Scale::X8 and lower is supported. The window starts extremely small.

I believe the system I had the issue on was running Fedora 27, which uses XWayland.

Window::get_size() inconsistent on Windows

Using the latest published version (0.10.1) on Windows, with WindowOptions::resize = true, get_size initially returns the size of the client area of the window. However, after resizing the window, get_size will return the total size of the window (including title bar, border, etc). I believe the correct semantic is to always return the client size, as this is most useful when creating a pixel buffer to draw to within this area.

Memory Leak on macOS?

is it possible, that there is a memory leak on macOS? I'm running El Capitan and the example code on the front-page which just creates an empty (black) buffer seems to gain slowly but constantly memory.

Used code:

extern crate minifb;

use minifb::{Window, Key, Scale, WindowOptions};

const WIDTH: usize = 640;
const HEIGHT: usize = 360;

fn main() {
    let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];

    let mut window = Window::new("Test - ESC to exit",
                                 WIDTH,
                                 HEIGHT,
                                 WindowOptions::default()).unwrap_or_else(|e| {
        panic!("{}", e);
    });

    while window.is_open() && !window.is_key_down(Key::Escape) {
        for i in buffer.iter_mut() {
            *i = 0; // write something more funny here!
        }

        window.update_with_buffer(&buffer);
    }
}

1

2

3

after approx. 30 sec of running

Resize handling on X11 causes buffer overruns, segfaults.

This can be reproduced easily by running the noise or title_cursor demos under a tiling window manager. Both these demos set resize: true but draw to a 32-bit buffer, which is a combination that doesn't look officially supported. Tiling window managers tend to resize windows immediately when they're opened. (I bet you can repro this under the default Ubuntu window manager by resizing the window manually.)

However, setting resize: false doesn't actually fix it, because the flags aren't stored anywhere in the window info. They're only set on the X11 hints, which are just that -- hints. The window manager can still resize the client's window.

And when it does, the following happens:

  • The ConfigureNotify event gets processed here, changing the width and height without resizing the image or display_buffer.
  • At the next call to mfb_update_with_buffer the new size is passed along with the old buffer to a copying routine, e.g. this one.
  • The copying routine happily writes the buffer as though it were the new size, regardless of its actual size. (With the allocator on my machine, this happens to stomp the WindowInfo struct itself, making debugging quite confusing.)

I can see two ways of fixing this.

The "minimal" way would be to record the fact that the window doesn't support resizing somewhere, and (if that flag is set) never change width and height after they are initially set. This means that resizing the window just adjusts a black rectangle around the original image, but at least it doesn't segfault. I've got a slightly hacked patch for this if you want.

The "thorough" way would be to reallocate the buffers on ConfigureNotify events. This would enable basic resize support when drawing to a 32-bit buffer. I bet there's more to this, though -- I'm not familiar with your library, particularly on non-X11 platforms.

Support drag'n'drop of files

This has been requested now and then and would be nice to support. The way it would work is that the program can call a get_files_dropped function or something similar that returns Option<Vec<Path>> I think that would be good enough for many use-cases.

Mac: Move event polling to separate

When holding down a key or pressing a menu item the whole main thread stalls. It would be better to have event polling in a separate thread that just posts to the main thread instead.

Wayland support

unix assumes X11. Would be nice to have Wayland support too.

Example "noise" doesn't run on OSX 10.13.6

I can't run the "noise" example as written in the README.md.
The example exits with an "Unable to create window" error.

persephone:rust_minifb eric$ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.13.6
BuildVersion:	17G3025
persephone:rust_minifb eric$ cargo build
   Compiling cc v1.0.25                                                                                                             
   Compiling libc v0.2.43
   Compiling time v0.1.40
   Compiling minifb v0.11.0 (file:///Users/eric/src/rust/rust_minifb)
    Finished dev [unoptimized + debuginfo] target(s) in 9.59s
persephone:rust_minifb eric$ cargo run --example noise
   Compiling minifb v0.11.0 (file:///Users/eric/src/rust/rust_minifb)                                                               
    Finished dev [unoptimized + debuginfo] target(s) in 0.86s
     Running `target/debug/examples/noise`
Unable to create window Failed to create window "Unable to open Window"
Your device/OS doesn't support Metal.
persephone:rust_minifb eric$ 

Move to winapi 0.3

The 0.3 version lets you bind and compile against just the modules that are actually used, cuts down on compile times quite a bit.

Blurry on Retina Display on macOS

Hi!

This library looks fantastic. I was just playing with it and noticed there's a blur when used on a Retina Macbook Pro (mid-2012) โ€“ do you have an idea why?

My scaling setting is set to X1, and here's what a screenshot looks like of a black screen with a single pixel set to white:

screenshot 2016-10-25 00 34 17

And here it is again zoomed in:

screenshot 2016-10-25 00 36 11

You can see little 'wings' off to each of the four sides. Is this intentional, or a bug?

update_with_buffer() can cause buffer overflow's

Filing this as discussed. Issue is that update_with_buffer() can cause a overflow and start reading into random heap memory.

This was first discovered on Windows. Will test Linux and update the issue. If it also happens on Linux either it's happening at the OS API level or not.

If possible add checking to update_with_buffer() to prevent reading data outside of the set valid range.

Panic in Noise Example on Linux (Manjaro x64)

It looks like in the noise example, sometimes the scale factor causes the example to attempt to open a window wider than the display. It causes an underflow on this line:
let x = (d.screen_width - width) / 2;

In my case, width = 5120 and d.screen_width = 2560. Here's the error:

Finished dev [unoptimized + debuginfo] target(s) in 0.01s Runningtarget/debug/examples/noise thread 'main' panicked at 'attempt to subtract with overflow', src/os/unix/mod.rs:277:21

mouse problematic with odd-sized windows and scale

If your window width is not evenly divisible by scale (i.e. 463 pixels for Scale2x), something odd is going on with the mouse example, on unix. I haven't tried other platforms.

The resolved pixel appears "further along" the buffer than expected, as if multiplying by the (scaled) width is incorrect.

Is this a bug in the example, or is it a bug in the buffer handling in unix?

This is easier to test after (or caused by!) #72.

README example doesn't build

Window is not in scope on line 11:

   |
11 |    let mut window = Window::new("plasmatest", width, height, WindowOptions::default()).unwrap_or_else(|e| {
   |                     ^^^^^^^^^^^ Use of undeclared type or module `Window`

To fix, just add Window to the imports from minifb:

use minifb::{Key, Scale, WindowOptions, Window};

Window title in example menu.rs is wrong

Hi!

The window title in the example menu.rs says "Noise Test - Press ESC to exit".
I think you might have copy-pasted from noise.rs without changing the title.

image example

can we have an example showing how to display an image (say, the rust logo) with this library?

`Scale::FitScreen` produces a window that's too big

I'm using minifb version 0.10.4, on Linux (x11 backend). My screen resolution is 1366x768. With Scale::FitScreen and a 256x256 framebuffer size, the window ends up bigger vertically than my screen.
The following code reproduces the issue:

extern crate minifb;

use minifb::{Scale, Window, WindowOptions};

fn main() {
    let options = WindowOptions {
        scale: Scale::FitScreen,
        ..Default::default()
    };
    let mut window = Window::new("bug", 256, 256, options).unwrap();
    while window.is_open() {
        window.update();
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}

Consider rewriting in a threaded fashion

As noted in #15 right now the main thread gets stuck when polling for events (this happens for example if a user holds a menu key down the whole it gets stuck inside the event loop updating but doesn't call to the outside ever)

It might be possible to keep the way the API looks today intact but unsure yet. Other benefits is that when running with update_with_buffer a copy of the buffer can be made and then the window thread can actually update this while the main thread keeps running.

Of course with threading comes it's own sets of issues. Should it be possible to set update frequency of the window thread (so it doesn't hammer to much or should one just do the "classic" way of sleeping 1 ms?)

Can't compile on ubuntu 16.04 LTS

I get the following error when trying to simply include minifb as a dependency in a blank project. It works fine for me on windows. I am running Ubuntu 16.04 LTS 64-bit. I'm somewhat new to using linux so I can provide more information if I left something important out.

    Updating registry `https://github.com/rust-lang/crates.io-index`
 Downloading libc v0.2.33
   Compiling gcc v0.3.54
   Compiling lazy_static v0.2.9
   Compiling pkg-config v0.3.9
   Compiling libc v0.2.33
   Compiling time v0.1.38
   Compiling x11-dl v2.14.0
   Compiling minifb v0.10.3
error: failed to run custom build command for `minifb v0.10.3`
process didn't exit successfully: `/home/matt/Desktop/MiniFB/minifbtest/target/debug/build/minifb-4fc3435711f12bf0/build-script-build` (exit code: 101)
--- stdout
TARGET = Some("x86_64-unknown-linux-gnu")
OPT_LEVEL = Some("0")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CC_x86_64-unknown-linux-gnu = None
CC_x86_64_unknown_linux_gnu = None
HOST_CC = None
CC = None
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CFLAGS_x86_64-unknown-linux-gnu = None
CFLAGS_x86_64_unknown_linux_gnu = None
HOST_CFLAGS = None
CFLAGS = None
DEBUG = Some("true")
running: "cc" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-m64" "-Wall" "-Wextra" "-o" "/home/matt/Desktop/MiniFB/minifbtest/target/debug/build/minifb-8f11960e89c67ebc/out/src/native/x11/X11MiniFB.o" "-c" "src/native/x11/X11MiniFB.c"
cargo:warning=src/native/x11/X11MiniFB.c:4:33: fatal error: X11/Xcursor/Xcursor.h: No such file or directory
cargo:warning=compilation terminated.
exit code: 1

--- stderr
thread 'main' panicked at '

Internal error occurred: Command "cc" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-m64" "-Wall" "-Wextra" "-o" "/home/matt/Desktop/MiniFB/minifbtest/target/debug/build/minifb-8f11960e89c67ebc/out/src/native/x11/X11MiniFB.o" "-c" "src/native/x11/X11MiniFB.c" with args "cc" did not execute successfully (status code exit code: 1).

', /home/matt/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.54/src/lib.rs:1670:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.

warning: build failed, waiting for other jobs to finish...
error: build failed

WASM support

Would it fit the project to add a WebAssembly target?

  • Creating a simple HTML5 canvas object and then copying the buffer of pixels every frame to JavaScript and sending the events back. Or it could be done using ImageData.
  • Scaling could be implemented like this.
  • A example for keyboard input is shown here.
  • The menus could be a problem but that could be fixed with custom buttons in JavaScript.

I would love to help with developing/testing this if it fits your vision of the project!

Request: more flexible InputCallback mechanism?

The only way to get char codes seems to be through the InputCallback, but since this consumes a Box I'm having trouble getting the data "out" of the callback since the Box<> is moved away into the depths of minifb :) The examples I've seen (in examples/menu.rs, and in ProDBG) both don't make the data available up to the caller (menu.rs just has a println!(), and ProDBG calls a 'global' imgui wrapper function).

Is there a recommended way to make the char code data available up in the main loop? I'm still a Rust noob, and I'm not sure what a good solution would be. The simplest would probably be to collect all char codes for a frame and make them available through polling, similar to get_keys()? The most important functionality for me is to get the UNICODE char code (as opposed to virtual key codes), whether through polling, a callback closure or callback trait isn't important to me :)

x11-dl compilation eats all memory on nightly + Linux

For some reason, on Linux and Rust nightly x11-dl 2.2 never compiles successfully and eats all the memory (got 16 GB on this machine). Upgrading to x11-dl 2.14 seems to fix the issue, so maybe that dependency could be upgraded?

$ uname -srvmpio
Linux 4.10.0-28-generic #32-Ubuntu SMP Fri Jun 30 05:32:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Why multiple updates are required?

I'm very new for this library, and I'm trying to use it for minimal case of 'show one picture and nothing else'.

I decided to get rid of while loop and found that window.update_with_buffer stop working. After some tinkering I found I need to update screen at least 31 (!!!) times to see result.

My code:

extern crate minifb;

use minifb::{Key, WindowOptions, Window};

const WIDTH: usize = 640;
const HEIGHT: usize = 360;

fn main() {
    let  buffer: Vec<u32> = vec![0x77777777; WIDTH * HEIGHT];

    let mut window = Window::new("Test - ESC to exit",
                                 WIDTH,
                                 HEIGHT,
                                 WindowOptions::default()).unwrap_or_else(|e| {
        panic!("{}", e);
    });
      for _ in 0..30 {
            window.update_with_buffer(&buffer).unwrap();
        }
    loop{};
}

If I use 30 here, it show black screen, if I use larger values (f.e. 31, 300, etc) - it show expected gray window.

I'm not sure if this is a bug or I do something strange... Is there a way to 'show picture and go idle'?

segmentation fault when window size is bigger than buffer

crashes when using this code

use minifb::{Key, WindowOptions, Window};

const WIDTH: usize = 640;
const HEIGHT: usize = 360;

fn main() {
    let mut buffer: Vec<u32> = vec![0; 1];

    let mut window = Window::new("Test - ESC to exit",
                                 WIDTH,
                                 HEIGHT,
                                 WindowOptions::default()).unwrap_or_else(|e| {
        panic!("{}", e);
    });

    while window.is_open() && !window.is_key_down(Key::Escape) {

        // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way
        window.update_with_buffer(&buffer).unwrap();
    }
}

rustc version

rustc 1.36.0 (a53f9df32 2019-07-03)
binary: rustc
commit-hash: a53f9df32fbb0b5f4382caaad8f1a46f36ea887c
commit-date: 2019-07-03
host: x86_64-unknown-linux-gnu
release: 1.36.0
LLVM version: 8.0

Support for raw inputs

Some applications i have require a handling for raw input data, for example when any type of HID is used or inputs affect the non-focused window.

On windows this would be handled by the WM_INPUT messages, but i have no clue about the others.

Resize callback?

Would love to see a call back or just update called while resizing a window. I would add it myself as a pull request, but I don't have the cross platform knowledge to do so.

crash in menu,noise on osx 10.10.5

When attempting to run the examples menu and noise I am getting a SEGV. While the mouse example does not throw an exception (it draws dots on a black screen).

rustc 1.10.0 (cfcb716cf 2016-07-03)
cargo 0.11.0-nightly (259324c 2016-05-20)
Process:               noise [45612]
Path:                  /Users/USER/*/noise
Identifier:            noise
Version:               0
Code Type:             X86-64 (Native)
Parent Process:        cargo [45398]
Responsible:           Terminal [382]
User ID:               501

Date/Time:             2016-07-30 12:35:14.906 -0500
OS Version:            Mac OS X 10.10.5 (14F1909)
Report Version:        11
Anonymous UUID:        E32D7403-865C-487A-2324-2C9936F3A4B2

Sleep/Wake UUID:       349BA63B-26E8-495F-84DA-E318B0E92FDF

Time Awake Since Boot: 53000 seconds
Time Since Wake:       5700 seconds

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000000

VM Regions Near 0:
--> 
    __TEXT                 000000010673d000-0000000106784000 [  284K] r-x/rwx SM=COW  /Users/USER/*

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   noise                           0x000000010674790d -[OSXWindowFrameView windowResized:] + 157
1   com.apple.CoreFoundation        0x00007fff9a9f445c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
2   com.apple.CoreFoundation        0x00007fff9a8e4634 _CFXNotificationPost + 3140
3   com.apple.Foundation            0x00007fff8d779aa1 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
4   com.apple.AppKit                0x00007fff93427660 -[NSWindow _setFrameCommon:display:stashSize:] + 2885
5   com.apple.AppKit                0x00007fff9348c2d1 -[NSWindow _reallyDoOrderWindow:relativeTo:findKey:forCounter:force:isModal:] + 1526
6   com.apple.AppKit                0x00007fff9348b787 -[NSWindow _doOrderWindow:relativeTo:findKey:forCounter:force:isModal:] + 829
7   com.apple.AppKit                0x00007fff9348b3db -[NSWindow orderWindow:relativeTo:] + 159
8   com.apple.AppKit                0x00007fff934829a2 -[NSWindow makeKeyAndOrderFront:] + 47
9   com.apple.Foundation            0x00007fff8d7a1ef1 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 954
10  com.apple.Foundation            0x00007fff8d7a1ab9 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 131
11  noise                           0x00000001067457c1 mfb_open + 1025
12  noise                           0x0000000106742bf0 minifb::os::macos::Window::new::h48ebed0fa9ab2ed0 + 1008
13  noise                           0x0000000106741b79 minifb::Window::new::hd3126515b0ced15b + 137
14  noise                           0x000000010673e5c7 noise::main::h24afd7fcfc944014 + 263
15  noise                           0x000000010674ec2e std::panicking::try::call::hbbf4746cba890ca7 + 30
16  noise                           0x000000010675166c __rust_try + 12
17  noise                           0x0000000106751606 __rust_maybe_catch_panic + 38
18  noise                           0x000000010674ea52 std::rt::lang_start::hbcefdc316c2fbd45 + 562
19  noise                           0x0000000106741aea main + 42
20  libdyld.dylib                   0x00007fff9334e5c9 start + 1

fullscreen windows

Hi, I'd like to make windows fullscreen, thanks. I suppose currently I could manually get the screen size and set the image to that.

X11 Dep Issue on Elementary OS

Here's a log of running cargo build:

david@davids-laptop:~/devwork/gbaemulator$ cargo build
Compiling libc v0.1.12
Compiling libc v0.2.23
Compiling gcc v0.3.50
Compiling dylib v0.0.1
Compiling time v0.1.37
Compiling x11-dl v2.2.1
Compiling minifb v0.9.1
error: failed to run custom build command for minifb v0.9.1
process didn't exit successfully:
/home/david/devwork/gbaemulator/target/debug/build/minifb-dd163c76d6efa2a1/build-script-build (exit code: 101)
--- stdout
TARGET = Some("x86_64-unknown-linux-gnu")
OPT_LEVEL = Some("0")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CC_x86_64-unknown-linux-gnu = None
CC_x86_64_unknown_linux_gnu = None
HOST_CC = None
CC = None
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CFLAGS_x86_64-unknown-linux-gnu = None
CFLAGS_x86_64_unknown_linux_gnu = None
HOST_CFLAGS = None
CFLAGS = None
PROFILE = Some("debug")
running: "cc" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-m64" "-o" "/home/david/devwork/gbaemulator/target/debug/build/minifb-c081ab0c3ee253cf/out/src/native/x11/X11MiniFB.o" "-c" "src/native/x11/X11MiniFB.c"
cargo:warning=src/native/x11/X11MiniFB.c:1:27: fatal error: X11/Xresource.h: No such file or directory
cargo:warning=compilation terminated.
exit code: 1
command did not execute successfully, got: exit code: 1
--- stderr
thread 'main' panicked at 'explicit panic', /home/david/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.50/src/lib.rs:1210
note: Run with RUST_BACKTRACE=1 for a backtrace.
Build failed, waiting for other jobs to finish...
error: build failed

Pretty sure I installed X11 via apt-get as well. This is just a dependency in my Cargo.toml - works well on my Win10 machine.

Resize doesn't actually work (for me?) on macOS

Upon resizing the window, the content still stays the same size and has a gray border on the top and right, and the resized buf does not draw correctly.

I had to add this:

diff --git a/orig.m b/OSXWindowFrameView.m
index 9e7a5bc..850aba7 100644
--- a/OSXWindowFrameView.m
+++ b/OSXWindowFrameView.m
@@ -132,9 +132,14 @@ - (void)windowResized:(NSNotification *)notification;
     if (window->shared_data) {
         window->shared_data->width = (int)(size.width);
         window->shared_data->height = (int)(size.height);
+        window->draw_buffer = malloc((int)size.width*(int)size.height*4);
+        draw_buffer = window->draw_buffer;
+        window->width = (int)size.width;
+        window->height = (int)size.height;
+        width = (int)size.width;
+        height = (int)size.height;
     }
 }
 
 @end

However I'm sure there's a better way to fix it so I don't really want to submit that as a pull request.

Slow under macOS

I've found minifb to be pretty slow under OS X - my machine is a Macbook Pro (2.5GHz) running El Capitan.

A simple blank test:

extern crate minifb;
extern crate time;

const WIDTH: usize = 320;
const HEIGHT: usize = 200;

fn main() {

    let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];

    let mut window = match minifb::Window::new("Test - ESC to exit", WIDTH, HEIGHT,
                                               minifb::WindowOptions { scale: minifb::Scale::X4, borderless : false, title: true, resize: false }) {
        Ok(win) => win,
        Err(err) => {
            println!("Unable to create window {}", err);
            return;
        }
    };


    let mut last_time = time::PreciseTime::now();
    while window.is_open() && !window.is_key_down(minifb::Key::Escape) {
        window.update_with_buffer(&buffer);
        let now = time::PreciseTime::now();
        println!("Frame time: {}", last_time.to(now).num_milliseconds());
        last_time = now;
    }
}

Gives me around 42 ms per frame already!

Frame time: 44
Frame time: 44
Frame time: 46
Frame time: 49
Frame time: 43
Frame time: 42
Frame time: 44
Frame time: 41
Frame time: 43
Frame time: 43

It seems that the Scale::X4 is the culprit. With X1, I get better results, albeit not ideal:

Frame time: 23
Frame time: 6
Frame time: 19
Frame time: 22
Frame time: 11
Frame time: 16
Frame time: 17
Frame time: 15
Frame time: 17
Frame time: 22
Frame time: 11
Frame time: 16

There is huge variability within frame times.
I get much better result from simple drawing code using either glium or SDL2 bindings, but I much prefer the simplicity of minifb.

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.