Initial version

This commit is contained in:
Daniel Collin 2015-11-22 18:55:38 +01:00
commit 0c1fd92275
14 changed files with 779 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

12
Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[package]
name = "minifb"
version = "0.1.0"
authors = ["Daniel Collin <daniel@collin.com>"]
build = "build.rs"
[build-dependencies]
gcc = "0.3.19"
[dependencies]
libc = "0.1.10"

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Daniel Collin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

52
README.md Normal file
View file

@ -0,0 +1,52 @@
This text is based on the C version of the lib. This text will be updated soon...
MinFB
======
MiniFB (Mini FrameBuffer) is a small cross platform library that makes it easy to render (32-bit) pixels in a window. An example is the best way to show how it works:
if (!mfb_open("my display", 800, 600))
return 0;
for (;;)
{
int state;
// TODO: add some fancy rendering to the buffer of size 800 * 600
state = mfb_update(buffer);
if (state < 0)
break;
}
mfb_close();
First the code creates window with the mfb_open call that is used to display the data, next it's the applications resposiblity to allocate a buffer (which has to be at least the size of the window and in 32-bit) Next when calling mfb_update function the buffer will be copied over to the window and displayed. Currently the mfb_update will return -1 if ESC key is pressed but later on it will support to return a key code for a pressed button. See https://github.com/emoon/minifb/blob/master/tests/noise.c for a complete example
MiniFB has been tested on Windows, Mac OS X and Linux but may of course have trouble depending on your setup. Currently the code will not do any converting of data if not a proper 32-bit display can be created.
Build instructions
------------------
MiniFB uses tundra https://github.com/deplinenoise/tundra as build system and is required to build the code as is but not many changes should be needed if you want to use it directly in your own code.
Mac
---
Cocoa and clang is assumed to be installed on the system (downloading latest XCode + installing the command line tools should do the trick) then to build run: tundra2 macosx-clang-debug and you should be able to run the noise example (t2-output/macosx-clang-debug-default/noise)
Windows
-------
Visual Studio (ver 2012 express has been tested) tools needed (using the vcvars32.bat (for 32-bit) will set up the enviroment) to build run: tundra2 win32-msvc-debug and you should be able to run noise in t2-output/win32-msvc-debug-default/noise.exe
x11 (FreeBSD, Linux, *nix)
--------------------------
gcc and x11-dev libs needs to be installed. To build the code run tundra2 x11-gcc-debug and you should be able to run t2-output/x11-gcc-debug-default/noise

16
build.rs Normal file
View file

@ -0,0 +1,16 @@
use std::env;
extern crate gcc;
fn main() {
let env = env::var("TARGET").unwrap();
if env.contains("darwin") {
gcc::compile_library("libminifb_native.a",
&["src/native/macosx/MacMiniFB.m",
"src/native/macosx/OSXWindow.m",
"src/native/macosx/OSXWindowFrameView.m"]); // MacOS
} else if env.contains("windows") {
gcc::compile_library("libminifb_native.a", &["src/native/windows/WinMiniFB.c"]); // Windows
} else {
gcc::compile_library("libminifb_native.a", &["src/native/x11/X11MiniFB.c"]); // Unix
}
}

32
examples/noise.rs Normal file
View file

@ -0,0 +1,32 @@
extern crate minifb;
const WIDTH: usize = 1280;
const HEIGHT: usize = 720;
fn main() {
let mut noise;
let mut carry;
let mut seed = 0xbeefu32;
let mut buffer: [u32; WIDTH * HEIGHT] = [0; WIDTH * HEIGHT];
if !(minifb::open("TestWindow", WIDTH, HEIGHT)) {
return;
}
while minifb::update(&buffer) {
for i in buffer.iter_mut() {
noise = seed;
noise >>= 3;
noise ^= seed;
carry = noise & 1;
noise >>= 1;
seed >>= 1;
seed |= carry << 30;
noise &= 0xFF;
*i = (noise << 16) | (noise << 8) | noise;
}
}
minifb::close();
}

54
src/lib.rs Normal file
View file

@ -0,0 +1,54 @@
extern crate libc;
use std::ffi::CString;
use std::mem::transmute;
use libc::{c_char, c_int, c_void};
#[link(name = "Cocoa", kind = "framework")]
#[link(name = "minifb_native")]
extern {
fn mfb_open(name: *const c_char, width: c_int, height: c_int) -> c_int;
fn mfb_update(buffer: *mut c_void) -> c_int;
fn mfb_close();
}
///
/// Open up a window
///
pub fn open(name: &str, width: usize, height: usize) -> bool {
let s = CString::new(name).unwrap();
let ret;
unsafe {
ret = mfb_open(s.as_ptr(), width as c_int, height as c_int);
}
match ret {
0 => false,
_ => true,
}
}
///
/// Update
///
pub fn update(buffer: &[u32]) -> bool {
let ret;
unsafe {
ret = mfb_update(transmute(buffer.as_ptr()));
}
if ret < 0 {
return false;
} else {
return true;
}
}
///
/// Close
///
pub fn close() {
unsafe {
mfb_close();
}
}

View file

@ -0,0 +1,96 @@
#include "OSXWindow.h"
#include <Cocoa/Cocoa.h>
#include <unistd.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void* g_updateBuffer = 0;
int g_width = 0;
int g_height = 0;
static NSWindow* window_;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_open(const char* name, int width, int height)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
g_width = width;
g_height = height;
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
unsigned int styles = NSResizableWindowMask | NSClosableWindowMask | NSTitledWindowMask;
NSRect rectangle = NSMakeRect(0, 0, width, height);
window_ = [[OSXWindow alloc] initWithContentRect:rectangle styleMask:styles backing:NSBackingStoreBuffered defer:NO];
if (!window_)
return 0;
[window_ setTitle:[NSString stringWithUTF8String:name]];
[window_ setReleasedWhenClosed:NO];
[window_ performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:YES];
[window_ center];
[NSApp activateIgnoringOtherApps:YES];
[pool drain];
return 1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void mfb_close()
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if (window_)
[window_ close];
[pool drain];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int updateEvents()
{
int state = 0;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES];
if (event)
{
switch ([event type])
{
case NSKeyDown:
case NSKeyUp:
{
state = -1;
break;
}
default :
{
[NSApp sendEvent:event];
break;
}
}
}
[pool release];
return state;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_update(void* buffer)
{
g_updateBuffer = buffer;
int state = updateEvents();
[[window_ contentView] setNeedsDisplay:YES];
return state;
}

View file

@ -0,0 +1,10 @@
#import <Cocoa/Cocoa.h>
// @class OSXWindowFrameView;
@interface OSXWindow : NSWindow
{
NSView* childContentView;
}
@end

View file

@ -0,0 +1,136 @@
#import "OSXWindow.h"
#import "OSXWindowFrameView.h"
@implementation OSXWindow
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithContentRect:(NSRect)contentRect
styleMask:(NSUInteger)windowStyle
backing:(NSBackingStoreType)bufferingType
defer:(BOOL)deferCreation
{
self = [super
initWithContentRect:contentRect
styleMask:windowStyle
backing:bufferingType
defer:deferCreation];
if (self)
{
[self setOpaque:YES];
[self setBackgroundColor:[NSColor clearColor]];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(mainWindowChanged:)
name:NSWindowDidBecomeMainNotification
object:self];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(mainWindowChanged:)
name:NSWindowDidResignMainNotification
object:self];
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]
removeObserver:self];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setContentSize:(NSSize)newSize
{
NSSize sizeDelta = newSize;
NSSize childBoundsSize = [childContentView bounds].size;
sizeDelta.width -= childBoundsSize.width;
sizeDelta.height -= childBoundsSize.height;
OSXWindowFrameView *frameView = [super contentView];
NSSize newFrameSize = [frameView bounds].size;
newFrameSize.width += sizeDelta.width;
newFrameSize.height += sizeDelta.height;
[super setContentSize:newFrameSize];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)mainWindowChanged:(NSNotification *)aNotification
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setContentView:(NSView *)aView
{
if ([childContentView isEqualTo:aView])
{
return;
}
NSRect bounds = [self frame];
bounds.origin = NSZeroPoint;
OSXWindowFrameView *frameView = [super contentView];
if (!frameView)
{
frameView = [[[OSXWindowFrameView alloc] initWithFrame:bounds] autorelease];
[super setContentView:frameView];
}
if (childContentView)
{
[childContentView removeFromSuperview];
}
childContentView = aView;
[childContentView setFrame:[self contentRectForFrameRect:bounds]];
[childContentView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[frameView addSubview:childContentView];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSView *)contentView
{
return childContentView;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)canBecomeKeyWindow
{
return YES;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)canBecomeMainWindow
{
return YES;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSRect)contentRectForFrameRect:(NSRect)windowFrame
{
windowFrame.origin = NSZeroPoint;
return NSInsetRect(windowFrame, 0, 0);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ (NSRect)frameRectForContentRect:(NSRect)windowContentRect styleMask:(NSUInteger)windowStyle
{
return NSInsetRect(windowContentRect, 0, 0);
}
@end

View file

@ -0,0 +1,8 @@
#import <Cocoa/Cocoa.h>
@interface OSXWindowFrameView : NSView
{
}
@end

View file

@ -0,0 +1,50 @@
#import "OSXWindowFrameView.h"
@implementation OSXWindowFrameView
extern void* g_updateBuffer;
extern int g_width;
extern int g_height;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSRect)resizeRect
{
const CGFloat resizeBoxSize = 16.0;
const CGFloat contentViewPadding = 5.5;
NSRect contentViewRect = [[self window] contentRectForFrameRect:[[self window] frame]];
NSRect resizeRect = NSMakeRect(
NSMaxX(contentViewRect) + contentViewPadding,
NSMinY(contentViewRect) - resizeBoxSize - contentViewPadding,
resizeBoxSize,
resizeBoxSize);
return resizeRect;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)drawRect:(NSRect)rect
{
if (!g_updateBuffer)
return;
CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, g_updateBuffer, g_width * g_height * 4, NULL);
CGImageRef img = CGImageCreate(g_width, g_height, 8, 32, g_width * 4, space, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
provider, NULL, false, kCGRenderingIntentDefault);
CGColorSpaceRelease(space);
CGDataProviderRelease(provider);
CGContextDrawImage(context, CGRectMake(0, 0, g_width, g_height), img);
CGImageRelease(img);
}
@end

View file

@ -0,0 +1,142 @@
#include <MiniFB.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static WNDCLASS s_wc;
static HWND s_wnd;
static int s_close = 0;
static int s_width;
static int s_height;
static HDC s_hdc;
static void* s_buffer;
static BITMAPINFO s_bitmapInfo;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int res = 0;
switch (message)
{
case WM_PAINT:
{
if (s_buffer)
{
StretchDIBits(s_hdc, 0, 0, s_width, s_height, 0, 0, s_width, s_height, s_buffer,
&s_bitmapInfo, DIB_RGB_COLORS, SRCCOPY);
ValidateRect(hWnd, NULL);
}
break;
}
case WM_KEYDOWN:
{
if ((wParam&0xFF) == 27)
s_close = 1;
break;
}
case WM_CLOSE:
{
s_close = 1;
break;
}
default:
{
res = DefWindowProc(hWnd, message, wParam, lParam);
}
}
return res;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_open(const char* title, int width, int height)
{
RECT rect = { 0 };
s_wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
s_wc.lpfnWndProc = WndProc;
s_wc.hCursor = LoadCursor(0, IDC_ARROW);
s_wc.lpszClassName = title;
RegisterClass(&s_wc);
rect.right = width;
rect.bottom = height;
AdjustWindowRect(&rect, WS_POPUP | WS_SYSMENU | WS_CAPTION, 0);
rect.right -= rect.left;
rect.bottom -= rect.top;
s_width = width;
s_height = height;
s_wnd = CreateWindowEx(0,
title, title,
WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
CW_USEDEFAULT, CW_USEDEFAULT,
rect.right, rect.bottom,
0, 0, 0, 0);
if (!s_wnd)
return 0;
ShowWindow(s_wnd, SW_NORMAL);
s_bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
s_bitmapInfo.bmiHeader.biPlanes = 1;
s_bitmapInfo.bmiHeader.biBitCount = 32;
s_bitmapInfo.bmiHeader.biCompression = BI_BITFIELDS;
s_bitmapInfo.bmiHeader.biWidth = width;
s_bitmapInfo.bmiHeader.biHeight = -height;
s_bitmapInfo.bmiColors[0].rgbRed = 0xff;
s_bitmapInfo.bmiColors[1].rgbGreen = 0xff;
s_bitmapInfo.bmiColors[2].rgbBlue = 0xff;
s_hdc = GetDC(s_wnd);
return 1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_update(void* buffer)
{
MSG msg;
s_buffer = buffer;
InvalidateRect(s_wnd, NULL, TRUE);
SendMessage(s_wnd, WM_PAINT, 0, 0);
while (PeekMessage(&msg, s_wnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (s_close == 1)
return -1;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void mfb_close()
{
s_buffer = 0;
ReleaseDC(s_wnd, s_hdc);
DestroyWindow(s_wnd);
}

148
src/native/x11/X11MiniFB.c Normal file
View file

@ -0,0 +1,148 @@
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <MiniFB.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define KEY_FUNCTION 0xFF
#define KEY_ESC 0x1B
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static Display* s_display;
static int s_screen;
static int s_width;
static int s_height;
static Window s_window;
static GC s_gc;
static XImage *s_ximage;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_open(const char* title, int width, int height)
{
int depth, i, formatCount, convDepth = -1;
XPixmapFormatValues* formats;
XSetWindowAttributes windowAttributes;
XSizeHints sizeHints;
Visual* visual;
s_display = XOpenDisplay(0);
if (!s_display)
return -1;
s_screen = DefaultScreen(s_display);
visual = DefaultVisual(s_display, s_screen);
formats = XListPixmapFormats(s_display, &formatCount);
depth = DefaultDepth(s_display, s_screen);
Window defaultRootWindow = DefaultRootWindow(s_display);
for (i = 0; i < formatCount; ++i)
{
if (depth == formats[i].depth)
{
convDepth = formats[i].bits_per_pixel;
break;
}
}
XFree(formats);
// We only support 32-bit right now
if (convDepth != 32)
{
XCloseDisplay(s_display);
return -1;
}
int screenWidth = DisplayWidth(s_display, s_screen);
int screenHeight = DisplayHeight(s_display, s_screen);
windowAttributes.border_pixel = BlackPixel(s_display, s_screen);
windowAttributes.background_pixel = BlackPixel(s_display, s_screen);
windowAttributes.backing_store = NotUseful;
s_window = XCreateWindow(s_display, defaultRootWindow, (screenWidth - width) / 2,
(screenHeight - height) / 2, width, height, 0, depth, InputOutput,
visual, CWBackPixel | CWBorderPixel | CWBackingStore,
&windowAttributes);
if (!s_window)
return 0;
XSelectInput(s_display, s_window, KeyPressMask | KeyReleaseMask);
XStoreName(s_display, s_window, title);
sizeHints.flags = PPosition | PMinSize | PMaxSize;
sizeHints.x = 0;
sizeHints.y = 0;
sizeHints.min_width = width;
sizeHints.max_width = width;
sizeHints.min_height = height;
sizeHints.max_height = height;
XSetWMNormalHints(s_display, s_window, &sizeHints);
XClearWindow(s_display, s_window);
XMapRaised(s_display, s_window);
XFlush(s_display);
s_gc = DefaultGC(s_display, s_screen);
s_ximage = XCreateImage(s_display, CopyFromParent, depth, ZPixmap, 0, NULL, width, height, 32, width * 4);
s_width = width;
s_height = height;
return 1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int processEvents()
{
XEvent event;
KeySym sym;
if (!XPending(s_display))
return;
XNextEvent(s_display, &event);
if (event.type != KeyPress)
return 0;
sym = XLookupKeysym(&event.xkey, 0);
if ((sym >> 8) != KEY_FUNCTION)
return 0;
if ((sym & 0xFF) == KEY_ESC)
return -1;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int mfb_update(void* buffer)
{
s_ximage->data = (char*)buffer;
XPutImage(s_display, s_window, s_gc, s_ximage, 0, 0, 0, 0, s_width, s_height);
XFlush(s_display);
if (processEvents() < 0)
return -1;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void mfb_close (void)
{
s_ximage->data = NULL;
XDestroyImage(s_ximage);
XDestroyWindow(s_display, s_window);
XCloseDisplay(s_display);
}