Top Related Projects
Quick Overview
gfx-rs/gfx is a low-level, high-performance graphics API for Rust. It provides a unified interface for multiple backends, including Vulkan, Metal, DirectX, and OpenGL. The project aims to offer a safe and efficient abstraction layer for graphics programming in Rust.
Pros
- Cross-platform compatibility with support for multiple graphics APIs
- High-performance and low-overhead design
- Type-safe and memory-safe due to Rust's language features
- Active development and community support
Cons
- Steep learning curve for beginners in graphics programming
- Documentation can be challenging for newcomers
- API may change frequently due to ongoing development
- Limited ecosystem compared to more established graphics libraries
Code Examples
- Creating a basic triangle:
use gfx_hal::{Backend, Device};
let mut vertices = [
Vertex { position: [-0.5, -0.5, 0.0] },
Vertex { position: [ 0.5, -0.5, 0.0] },
Vertex { position: [ 0.0, 0.5, 0.0] },
];
let vertex_buffer = factory
.create_buffer(
BufferInfo {
size: std::mem::size_of_val(&vertices) as u64,
usage: buffer::Usage::VERTEX,
},
Properties::CPU_VISIBLE,
)
.unwrap();
- Setting up a basic render pipeline:
let pipeline = factory
.create_graphics_pipeline(
&PipelineDescriptor {
vertex: VertexDescriptor {
buffers: &[VertexBufferDescriptor {
stride: std::mem::size_of::<Vertex>() as u32,
rate: 0,
}],
attributes: &[VertexAttributeDescriptor {
offset: 0,
shader_location: 0,
format: Format::Rgb32Float,
}],
},
fragment: Some(FragmentDescriptor {
targets: &[ColorTargetDescriptor {
format: Format::Rgba8Unorm,
blend: Some(BlendDescriptor::REPLACE),
write_mask: ColorWrites::ALL,
}],
}),
layout: &pipeline_layout,
shader_stages: ShaderStages {
vertex: vs_module.entry_point("main").unwrap(),
fragment: Some(fs_module.entry_point("main").unwrap()),
},
primitive: PrimitiveState::default(),
depth_stencil: None,
multisample: MultisampleState::default(),
},
)
.unwrap();
- Rendering a frame:
let mut encoder = command_pool.create_command_encoder(&CommandEncoderDescriptor::default());
{
let mut render_pass = encoder.begin_render_pass(&RenderPassDescriptor {
color_attachments: &[RenderPassColorAttachment {
view: &frame.view,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(Color::BLACK),
store: true,
},
}],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&pipeline);
render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));
render_pass.draw(0..3, 0..1);
}
queue.submit(std::iter::once(encoder.finish()));
Getting Started
To get started with gfx-rs/gfx, add the following to your Cargo.toml
:
[dependencies]
gfx-hal = "0.9"
gfx-backend-vulkan = "0.9" # Or other backend of your choice
Then, in your Rust code:
use gfx_hal::{Backend, Instance};
use gfx_backend_vulkan as back;
fn main() {
Competitor Comparisons
Safe and rich Rust wrapper around the Vulkan API
Pros of Vulkano
- Direct Vulkan API mapping, providing low-level control and performance
- Comprehensive type-checking and safety features at compile-time
- Extensive documentation and examples for easier learning
Cons of Vulkano
- Steeper learning curve due to Vulkan's complexity
- Less abstraction, requiring more boilerplate code
- Potentially slower development time for simple graphics applications
Code Comparison
Vulkano:
let instance = Instance::new(None, &InstanceExtensions::none(), None)
.expect("failed to create instance");
let physical = PhysicalDevice::enumerate(&instance).next()
.expect("no device available");
let queue_family = physical.queue_families()
.find(|&q| q.supports_graphics())
.expect("couldn't find a graphical queue family");
gfx:
let mut factory: gfx_device_gl::Factory = adapter.open(1).unwrap();
let (window, mut device, mut graphics_queue, mut main_color) =
factory.create_window_targets(&window_builder, ColorFormat::default(), None);
Both libraries aim to provide efficient graphics programming in Rust, but Vulkano offers a more direct Vulkan experience, while gfx provides a higher-level abstraction across multiple backends. The choice between them depends on the specific project requirements and the developer's familiarity with graphics APIs.
Vulkan bindings for Rust
Pros of ash
- Lower-level API, providing more direct control over Vulkan
- Potentially better performance due to less abstraction
- Closer to native Vulkan, easier for developers familiar with the API
Cons of ash
- Steeper learning curve for those new to Vulkan
- Requires more boilerplate code for basic operations
- Less cross-platform compatibility compared to gfx
Code Comparison
ash example:
let instance = ash::Instance::new(&create_info, None)?;
let physical_device = instance.enumerate_physical_devices()?.pop().unwrap();
let device = instance.create_device(physical_device, &device_create_info, None)?;
gfx example:
let instance = Instance::new(InstanceDescriptor::default())?;
let adapter = instance.request_adapter(&RequestAdapterOptions::default())?;
let device = adapter.request_device(&DeviceDescriptor::default(), None)?;
The ash example shows more explicit Vulkan-style initialization, while gfx provides a higher-level abstraction for device creation. ash requires more detailed setup but offers finer control, whereas gfx simplifies the process at the cost of some flexibility.
SDL2 bindings for Rust
Pros of rust-sdl2
- Simpler API, easier to get started for beginners
- Closer to the original SDL2 API, making it easier for developers familiar with SDL2
- More comprehensive coverage of SDL2 features, including audio and input handling
Cons of rust-sdl2
- Less flexible for advanced graphics programming
- Limited to SDL2's capabilities, which may not be sufficient for complex 3D rendering
- Potentially lower performance for graphics-intensive applications
Code Comparison
rust-sdl2:
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo", 800, 600)
.position_centered()
.build()
.unwrap();
gfx:
let mut factory = adapter.open(1, &Features::empty()).unwrap();
let mut swap_chain = factory.create_swap_chain(&surface, SwapChainConfig::default()).unwrap();
let frame = swap_chain.acquire_frame().unwrap();
The rust-sdl2 code is more straightforward and closely resembles SDL2 usage in other languages. The gfx code is more low-level and provides finer control over graphics operations, but requires more setup and understanding of graphics concepts.
A refreshingly simple data-driven game engine built in Rust
Pros of Bevy
- Higher-level game engine with a more user-friendly API
- Built-in ECS (Entity Component System) for efficient game development
- More comprehensive documentation and tutorials for beginners
Cons of Bevy
- Less flexible for low-level graphics programming
- Potentially higher overhead for simple applications
- Newer project with a less established ecosystem
Code Comparison
Bevy (game setup):
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.run();
}
GFX (rendering setup):
use gfx_hal::{Backend, Instance};
fn main() {
let instance = backend::Instance::create("My Engine", 1).expect("Failed to create instance");
let adapter = instance.enumerate_adapters().remove(0);
}
Bevy provides a more straightforward, high-level approach for game development, while GFX offers lower-level control for graphics programming. Bevy's ECS architecture simplifies game logic organization, but GFX allows for more fine-grained control over rendering pipelines. The choice between them depends on the project's requirements and the developer's familiarity with graphics programming concepts.
Window handling library in pure Rust
Pros of winit
- Focused solely on window creation and event handling, making it more lightweight and easier to integrate into various projects
- Provides a unified API across multiple platforms, simplifying cross-platform development
- More actively maintained with frequent updates and improvements
Cons of winit
- Limited to window management and input handling, requiring additional libraries for graphics rendering
- Less comprehensive documentation compared to gfx, which may make it harder for beginners to get started
Code Comparison
winit example:
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
event_loop.run(move |event, _, control_flow| {
// Event handling logic
});
}
gfx example:
use gfx_hal::{Backend, Instance};
use gfx_backend_vulkan as back;
fn main() {
let instance = back::Instance::create("gfx-rs example", 1).expect("Failed to create instance");
let adapter = instance.enumerate_adapters().remove(0);
// Device and queue creation logic
}
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Getting Started | Documentation | Blog | Funding
gfx-rs
gfx-rs is a low-level, cross-platform graphics and compute abstraction library in Rust. It consists of the following components:
gfx-hal deprecation
As of the v0.9 release, gfx-hal is now in maintenance mode. gfx-hal development was mainly driven by wgpu, which has now switched to its own GPU abstraction called wgpu-hal. For this reason, gfx-hal development has switched to maintenance only, until the developers figure out the story for gfx-portability. Read more about the transition in #3768.
hal
gfx-hal
which is gfx's hardware abstraction layer: a Vulkan-ic mostly unsafe API which translates to native graphics backends.gfx-backend-*
which contains graphics backends for various platforms:- Vulkan (runs on Linux, Windows, and Android)
- DirectX 12 and DirectX 11
- Metal (runs on macOS and iOS)
- OpenGL ES3 (runs on Linux/BSD, Android, and WASM/WebGL2)
gfx-warden
which is a data-driven reference test framework, used to verify consistency across all graphics backends.
gfx-rs is hard to use, it's recommended for performance-sensitive libraries and engines. If that's not your domain, take a look at wgpu-rs for a safe and simple alternative.
Hardware Abstraction Layer
The Hardware Abstraction Layer (HAL), is a thin, low-level graphics and compute layer which translates API calls to various backends, which allows for cross-platform support. The API of this layer is based on the Vulkan API, adapted to be more Rust-friendly.
Currently HAL has backends for Vulkan, DirectX 12/11, Metal, and OpenGL/OpenGL ES/WebGL.
The HAL layer is consumed directly by user applications or libraries. HAL is also used in efforts such as gfx-portability.
See the Big Picture blog post for connections.
The old gfx
crate (pre-ll)
This repository was originally home to the gfx
crate, which is now deprecated. You can find the latest versions of the code for that crate in the pre-ll
branch of this repository.
The master branch of this repository is now focused on developing gfx-hal
and its associated backend and helper libraries, as described above. gfx-hal
is a complete rewrite of gfx
, but it is not necessarily the direct successor to gfx
. Instead, it serves a different purpose than the original gfx
crate, by being "lower level" than the original. Hence, the name of gfx-hal
was originally ll
, which stands for "lower level", and the original gfx
is now referred to as pre-ll
.
The spiritual successor to the original gfx
is actually wgpu
, which stands on a similar level of abstraction to the old gfx
crate, but with a modernized API that is more fit for being used over Vulkan/DX12/Metal. If you want something similar to the old gfx
crate that is being actively developed, wgpu
is probably what you're looking for, rather than gfx-hal
.
Contributing
We are actively looking for new contributors and aim to be welcoming and helpful to anyone that is interested! We know the code base can be a bit intimidating in size and depth at first, and to this end we have a label on the issue tracker which marks issues that are new contributor friendly and have some basic direction for completion in the issue comments. If you have any questions about any of these issues (or any other issues) you may want to work on, please comment on GitHub and/or drop a message in our Matrix chat!
License
This repository is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
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.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot