mirror of
https://github.com/eliasstepanik/imgui-rs.git
synced 2026-01-11 21:48:36 +00:00
yeeted imgui-gfx renderer.
Please see the new repository under this organization to see its grave
This commit is contained in:
parent
f2fdfd47c9
commit
f05a2e0147
@ -1,33 +0,0 @@
|
||||
[package]
|
||||
name = "imgui-gfx-examples"
|
||||
version = "0.0.0"
|
||||
edition = "2018"
|
||||
authors = ["The imgui-rs Developers"]
|
||||
description = "imgui crate examples"
|
||||
homepage = "https://github.com/imgui-rs/imgui-rs"
|
||||
repository = "https://github.com/imgui-rs/imgui-rs"
|
||||
license = "MIT/Apache-2.0"
|
||||
publish = false
|
||||
|
||||
[badges]
|
||||
maintenance = { status = "deprecated" }
|
||||
|
||||
[features]
|
||||
opengl = ["imgui-gfx-renderer/opengl"]
|
||||
# FIXME
|
||||
# directx = ["imgui-gfx-renderer/directx"]
|
||||
default = ["opengl"]
|
||||
|
||||
[dev-dependencies]
|
||||
gfx = "0.18"
|
||||
gfx_device_gl = "0.16"
|
||||
glutin = "0.27"
|
||||
image = "0.23"
|
||||
imgui = { path = "../imgui" }
|
||||
imgui-gfx-renderer = { path = "../imgui-gfx-renderer" }
|
||||
imgui-winit-support = { path = "../imgui-winit-support" }
|
||||
old_school_gfx_glutin_ext = "0.27"
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
gfx_device_dx11 = "0.8"
|
||||
gfx_window_dxgi = "0.19"
|
||||
@ -1,4 +0,0 @@
|
||||
# `imgui-gfx-examples`
|
||||
|
||||
- Run with OpenGL backend: `cargo run --example gfx_hello_world`
|
||||
- Run with DirectX backend: `cargo run --example gfx_hello_world --features directx --no-default-features`
|
||||
@ -1,128 +0,0 @@
|
||||
use gfx::texture::{FilterMethod, SamplerInfo, WrapMode};
|
||||
use image::ImageFormat;
|
||||
use imgui::*;
|
||||
use std::error::Error;
|
||||
|
||||
mod support;
|
||||
|
||||
#[derive(Default)]
|
||||
struct CustomTexturesApp {
|
||||
my_texture_id: Option<TextureId>,
|
||||
lenna: Option<Lenna>,
|
||||
}
|
||||
|
||||
struct Lenna {
|
||||
texture_id: TextureId,
|
||||
size: [f32; 2],
|
||||
}
|
||||
|
||||
impl CustomTexturesApp {
|
||||
fn register_textures<R, F>(
|
||||
&mut self,
|
||||
factory: &mut F,
|
||||
textures: &mut Textures<imgui_gfx_renderer::Texture<R>>,
|
||||
) -> Result<(), Box<dyn Error>>
|
||||
where
|
||||
R: gfx::Resources,
|
||||
F: gfx::Factory<R>,
|
||||
{
|
||||
const WIDTH: usize = 128;
|
||||
const HEIGHT: usize = 128;
|
||||
|
||||
if self.my_texture_id.is_none() {
|
||||
// Generate dummy texture
|
||||
let mut data = Vec::with_capacity(WIDTH * HEIGHT * 4);
|
||||
for i in 0..WIDTH {
|
||||
for j in 0..HEIGHT {
|
||||
// Insert RGBA values
|
||||
data.push(i as u8);
|
||||
data.push(j as u8);
|
||||
data.push((i + j) as u8);
|
||||
data.push(255);
|
||||
}
|
||||
}
|
||||
|
||||
let (_, texture_view) = factory.create_texture_immutable_u8::<gfx::format::Srgba8>(
|
||||
gfx::texture::Kind::D2(WIDTH as u16, HEIGHT as u16, gfx::texture::AaMode::Single),
|
||||
gfx::texture::Mipmap::Provided,
|
||||
&[data.as_slice()],
|
||||
)?;
|
||||
let sampler =
|
||||
factory.create_sampler(SamplerInfo::new(FilterMethod::Bilinear, WrapMode::Clamp));
|
||||
let texture_id = textures.insert((texture_view, sampler));
|
||||
|
||||
self.my_texture_id = Some(texture_id);
|
||||
}
|
||||
|
||||
if self.lenna.is_none() {
|
||||
self.lenna = Some(Lenna::new(factory, textures)?);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn show_textures(&self, ui: &Ui) {
|
||||
Window::new("Hello textures")
|
||||
.size([400.0, 600.0], Condition::FirstUseEver)
|
||||
.build(ui, || {
|
||||
ui.text("Hello textures!");
|
||||
if let Some(my_texture_id) = self.my_texture_id {
|
||||
ui.text("Some generated texture");
|
||||
Image::new(my_texture_id, [100.0, 100.0]).build(ui);
|
||||
}
|
||||
|
||||
if let Some(lenna) = &self.lenna {
|
||||
ui.text("Say hello to Lenna.jpg");
|
||||
lenna.show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Lenna {
|
||||
fn new<R, F>(
|
||||
factory: &mut F,
|
||||
textures: &mut Textures<imgui_gfx_renderer::Texture<R>>,
|
||||
) -> Result<Self, Box<dyn Error>>
|
||||
where
|
||||
R: gfx::Resources,
|
||||
F: gfx::Factory<R>,
|
||||
{
|
||||
let lenna_bytes = include_bytes!("../../resources/Lenna.jpg");
|
||||
|
||||
let image = image::load_from_memory_with_format(lenna_bytes, ImageFormat::Jpeg)?;
|
||||
// gfx doesn't support easily RGB8 without alpha, so we need to convert
|
||||
let image = image.to_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let raw_data = image.into_raw();
|
||||
|
||||
let (_, texture_view) = factory.create_texture_immutable_u8::<gfx::format::Srgba8>(
|
||||
gfx::texture::Kind::D2(width as u16, height as u16, gfx::texture::AaMode::Single),
|
||||
gfx::texture::Mipmap::Provided,
|
||||
&[raw_data.as_slice()],
|
||||
)?;
|
||||
let sampler =
|
||||
factory.create_sampler(SamplerInfo::new(FilterMethod::Bilinear, WrapMode::Clamp));
|
||||
let texture_id = textures.insert((texture_view, sampler));
|
||||
Ok(Lenna {
|
||||
texture_id,
|
||||
size: [width as f32, height as f32],
|
||||
})
|
||||
}
|
||||
|
||||
fn show(&self, ui: &Ui) {
|
||||
Image::new(self.texture_id, self.size).build(ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut my_app = CustomTexturesApp::default();
|
||||
let mut system = support::init(file!());
|
||||
my_app
|
||||
.register_textures(
|
||||
&mut system.render_sys.factory,
|
||||
system.render_sys.renderer.textures(),
|
||||
)
|
||||
.expect("Failed to register textures");
|
||||
system.main_loop(|_, ui| my_app.show_textures(ui));
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
use imgui::*;
|
||||
|
||||
mod support;
|
||||
|
||||
fn main() {
|
||||
let system = support::init(file!());
|
||||
|
||||
let window_title = if cfg!(all(feature = "directx", windows)) {
|
||||
"Hello world (OpenGL)"
|
||||
} else {
|
||||
"Hello world (DirectX)"
|
||||
};
|
||||
|
||||
system.main_loop(|_, ui| {
|
||||
Window::new(window_title)
|
||||
.size([300.0, 100.0], Condition::FirstUseEver)
|
||||
.build(ui, || {
|
||||
ui.text("Hello world!");
|
||||
ui.text("こんにちは世界!");
|
||||
ui.text("This...is...imgui-rs!");
|
||||
ui.separator();
|
||||
let mouse_pos = ui.io().mouse_pos;
|
||||
ui.text(format!(
|
||||
"Mouse Position: ({:.1},{:.1})",
|
||||
mouse_pos[0], mouse_pos[1]
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
mod support;
|
||||
|
||||
fn main() {
|
||||
let system = support::init(file!());
|
||||
system.main_loop(|run, ui| ui.show_demo_window(run));
|
||||
}
|
||||
@ -1,286 +0,0 @@
|
||||
use gfx::Device;
|
||||
use glutin::{
|
||||
dpi::LogicalSize,
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
// XXX for easier porting...
|
||||
platform::run_return::EventLoopExtRunReturn,
|
||||
window::WindowBuilder,
|
||||
};
|
||||
use imgui::{Context, FontConfig, FontGlyphRanges, FontSource, Ui};
|
||||
use imgui_gfx_renderer::{Renderer, Shaders};
|
||||
use imgui_winit_support::{HiDpiMode, WinitPlatform};
|
||||
use old_school_gfx_glutin_ext::*;
|
||||
use std::time::Instant;
|
||||
|
||||
type ColorFormat = gfx::format::Rgba8;
|
||||
type DepthFormat = gfx::format::DepthStencil;
|
||||
// hack
|
||||
type EventsLoop = EventLoop<()>;
|
||||
|
||||
pub struct System {
|
||||
pub events_loop: EventsLoop,
|
||||
pub imgui: Context,
|
||||
pub platform: WinitPlatform,
|
||||
pub render_sys: RenderSystem,
|
||||
pub font_size: f32,
|
||||
}
|
||||
|
||||
pub fn init(title: &str) -> System {
|
||||
let title = match title.rfind('/') {
|
||||
Some(idx) => title.split_at(idx + 1).1,
|
||||
None => title,
|
||||
};
|
||||
let events_loop = EventsLoop::new();
|
||||
let builder = WindowBuilder::new()
|
||||
.with_title(title.to_owned())
|
||||
.with_inner_size(LogicalSize::new(1024f64, 768f64));
|
||||
|
||||
let mut imgui = Context::create();
|
||||
imgui.set_ini_filename(None);
|
||||
|
||||
let mut platform = WinitPlatform::init(&mut imgui);
|
||||
|
||||
let hidpi_factor = platform.hidpi_factor();
|
||||
let font_size = (13.0 * hidpi_factor) as f32;
|
||||
imgui.fonts().add_font(&[
|
||||
FontSource::DefaultFontData {
|
||||
config: Some(FontConfig {
|
||||
size_pixels: font_size,
|
||||
..FontConfig::default()
|
||||
}),
|
||||
},
|
||||
FontSource::TtfData {
|
||||
data: include_bytes!("../../../resources/mplus-1p-regular.ttf"),
|
||||
size_pixels: font_size,
|
||||
config: Some(FontConfig {
|
||||
rasterizer_multiply: 1.75,
|
||||
glyph_ranges: FontGlyphRanges::japanese(),
|
||||
..FontConfig::default()
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32;
|
||||
|
||||
let render_sys = RenderSystem::init(&mut imgui, builder, &events_loop);
|
||||
platform.attach_window(imgui.io_mut(), render_sys.window(), HiDpiMode::Rounded);
|
||||
System {
|
||||
events_loop,
|
||||
imgui,
|
||||
platform,
|
||||
render_sys,
|
||||
font_size,
|
||||
}
|
||||
}
|
||||
|
||||
impl System {
|
||||
pub fn main_loop<F: FnMut(&mut bool, &mut Ui)>(self, mut run_ui: F) {
|
||||
let System {
|
||||
mut events_loop,
|
||||
mut imgui,
|
||||
mut platform,
|
||||
mut render_sys,
|
||||
..
|
||||
} = self;
|
||||
let mut encoder: gfx::Encoder<_, _> = render_sys.factory.create_command_buffer().into();
|
||||
|
||||
let mut last_frame = Instant::now();
|
||||
let mut run = true;
|
||||
|
||||
while run {
|
||||
events_loop.run_return(|event, _, control_flow| {
|
||||
platform.handle_event(imgui.io_mut(), render_sys.window(), &event);
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::Resized(_) => render_sys.update_views(),
|
||||
WindowEvent::CloseRequested => {
|
||||
run = false;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
*control_flow = ControlFlow::Exit;
|
||||
});
|
||||
if !run {
|
||||
break;
|
||||
}
|
||||
|
||||
let io = imgui.io_mut();
|
||||
platform
|
||||
.prepare_frame(io, render_sys.window())
|
||||
.expect("Failed to start frame");
|
||||
let now = Instant::now();
|
||||
io.update_delta_time(now - last_frame);
|
||||
last_frame = now;
|
||||
let mut ui = imgui.frame();
|
||||
run_ui(&mut run, &mut ui);
|
||||
|
||||
if let Some(main_color) = render_sys.main_color.as_mut() {
|
||||
encoder.clear(main_color, [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
platform.prepare_render(&ui, render_sys.window());
|
||||
let draw_data = ui.render();
|
||||
if let Some(main_color) = render_sys.main_color.as_mut() {
|
||||
render_sys
|
||||
.renderer
|
||||
.render(&mut render_sys.factory, &mut encoder, main_color, draw_data)
|
||||
.expect("Rendering failed");
|
||||
}
|
||||
encoder.flush(&mut render_sys.device);
|
||||
render_sys.swap_buffers();
|
||||
render_sys.device.cleanup();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "opengl")]
|
||||
mod types {
|
||||
pub type Device = gfx_device_gl::Device;
|
||||
pub type Factory = gfx_device_gl::Factory;
|
||||
pub type Resources = gfx_device_gl::Resources;
|
||||
}
|
||||
|
||||
#[cfg(feature = "opengl")]
|
||||
pub struct RenderSystem {
|
||||
pub renderer: Renderer<ColorFormat, types::Resources>,
|
||||
pub windowed_context: glutin::WindowedContext<glutin::PossiblyCurrent>,
|
||||
pub device: types::Device,
|
||||
pub factory: types::Factory,
|
||||
pub main_color: Option<gfx::handle::RenderTargetView<types::Resources, ColorFormat>>,
|
||||
pub main_depth: gfx::handle::DepthStencilView<types::Resources, DepthFormat>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "opengl")]
|
||||
impl RenderSystem {
|
||||
pub fn init(
|
||||
imgui: &mut Context,
|
||||
builder: WindowBuilder,
|
||||
events_loop: &EventsLoop,
|
||||
) -> RenderSystem {
|
||||
{
|
||||
// Fix incorrect colors with sRGB framebuffer
|
||||
fn imgui_gamma_to_linear(col: [f32; 4]) -> [f32; 4] {
|
||||
let x = col[0].powf(2.2);
|
||||
let y = col[1].powf(2.2);
|
||||
let z = col[2].powf(2.2);
|
||||
let w = 1.0 - (1.0 - col[3]).powf(2.2);
|
||||
[x, y, z, w]
|
||||
}
|
||||
|
||||
let style = imgui.style_mut();
|
||||
for col in 0..style.colors.len() {
|
||||
style.colors[col] = imgui_gamma_to_linear(style.colors[col]);
|
||||
}
|
||||
}
|
||||
|
||||
let (windowed_context, device, mut factory, main_color, main_depth) =
|
||||
glutin::ContextBuilder::new()
|
||||
.with_vsync(true)
|
||||
.with_gfx_color_depth::<ColorFormat, DepthFormat>()
|
||||
.build_windowed(builder, events_loop)
|
||||
.expect("Failed to initialize graphics")
|
||||
.init_gfx::<ColorFormat, DepthFormat>();
|
||||
|
||||
let shaders = {
|
||||
let version = device.get_info().shading_language;
|
||||
if version.is_embedded {
|
||||
if version.major >= 3 {
|
||||
Shaders::GlSlEs300
|
||||
} else {
|
||||
Shaders::GlSlEs100
|
||||
}
|
||||
} else if version.major >= 4 {
|
||||
Shaders::GlSl400
|
||||
} else if version.major >= 3 {
|
||||
if version.minor >= 2 {
|
||||
Shaders::GlSl150
|
||||
} else {
|
||||
Shaders::GlSl130
|
||||
}
|
||||
} else {
|
||||
Shaders::GlSl110
|
||||
}
|
||||
};
|
||||
let renderer =
|
||||
Renderer::init(imgui, &mut factory, shaders).expect("Failed to initialize renderer");
|
||||
RenderSystem {
|
||||
renderer,
|
||||
windowed_context,
|
||||
device,
|
||||
factory,
|
||||
main_color: Some(main_color),
|
||||
main_depth,
|
||||
}
|
||||
}
|
||||
pub fn window(&self) -> &glutin::window::Window {
|
||||
self.windowed_context.window()
|
||||
}
|
||||
pub fn update_views(&mut self) {
|
||||
if let Some(main_color) = self.main_color.as_mut() {
|
||||
self.windowed_context
|
||||
.update_gfx(main_color, &mut self.main_depth);
|
||||
}
|
||||
}
|
||||
pub fn swap_buffers(&mut self) {
|
||||
self.windowed_context.swap_buffers().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "directx", windows))]
|
||||
mod types {
|
||||
pub type Device = gfx_device_dx11::Device;
|
||||
pub type Factory = gfx_device_dx11::Factory;
|
||||
pub type Resources = gfx_device_dx11::Resources;
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "directx", windows))]
|
||||
pub struct RenderSystem {
|
||||
pub renderer: Renderer<ColorFormat, types::Resources>,
|
||||
pub window: gfx_window_dxgi::Window,
|
||||
pub device: types::Device,
|
||||
pub factory: types::Factory,
|
||||
pub main_color: Option<gfx::handle::RenderTargetView<types::Resources, ColorFormat>>,
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "directx", windows))]
|
||||
impl RenderSystem {
|
||||
pub fn init(
|
||||
imgui: &mut Context,
|
||||
builder: WindowBuilder,
|
||||
events_loop: &EventsLoop,
|
||||
) -> RenderSystem {
|
||||
let (window, device, mut factory, main_color) =
|
||||
gfx_window_dxgi::init(builder, &events_loop).expect("Failed to initialize graphics");
|
||||
let renderer = Renderer::init(imgui, &mut factory, Shaders::HlslSm40)
|
||||
.expect("Failed to initialize renderer");
|
||||
RenderSystem {
|
||||
renderer,
|
||||
window,
|
||||
device,
|
||||
factory,
|
||||
main_color: Some(main_color),
|
||||
}
|
||||
}
|
||||
pub fn window(&self) -> &glutin::Window {
|
||||
&self.window.inner
|
||||
}
|
||||
pub fn update_views(&mut self, size: LogicalSize) {
|
||||
let physical = size.to_physical(self.window().get_hidpi_factor());
|
||||
let (width, height): (u32, u32) = physical.into();
|
||||
let _ = self.main_color.take(); // we need to drop main_color before calling update_views
|
||||
self.main_color = Some(
|
||||
gfx_window_dxgi::update_views(
|
||||
&mut self.window,
|
||||
&mut self.factory,
|
||||
&mut self.device,
|
||||
width as u16,
|
||||
height as u16,
|
||||
)
|
||||
.expect("Failed to update resize"),
|
||||
);
|
||||
}
|
||||
pub fn swap_buffers(&mut self) {
|
||||
self.window.swap_buffers(1);
|
||||
}
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
[package]
|
||||
name = "imgui-gfx-renderer"
|
||||
version = "0.8.0"
|
||||
edition = "2018"
|
||||
authors = ["The imgui-rs Developers"]
|
||||
description = "gfx renderer for the imgui crate"
|
||||
homepage = "https://github.com/imgui-rs/imgui-rs"
|
||||
repository = "https://github.com/imgui-rs/imgui-rs"
|
||||
license = "MIT/Apache-2.0"
|
||||
categories = ["gui", "rendering"]
|
||||
|
||||
[features]
|
||||
opengl = []
|
||||
directx = []
|
||||
default = ["opengl"]
|
||||
|
||||
[badges]
|
||||
maintenance = { status = "deprecated" }
|
||||
|
||||
[dependencies]
|
||||
gfx = "0.18"
|
||||
imgui = { version = "0.8.0", path = "../imgui" }
|
||||
|
||||
[target.'cfg(windows)'.build-dependencies]
|
||||
winapi = { version = "0.3", features = ["d3dcompiler"] }
|
||||
@ -1,202 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@ -1,19 +0,0 @@
|
||||
Copyright (c) 2015-2020 The imgui-rs Developers
|
||||
|
||||
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.
|
||||
@ -1,124 +0,0 @@
|
||||
fn main() {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Note: When building on Windows, this build script will automatically recompile the HLSL shaders.
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
|
||||
let src_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("src");
|
||||
|
||||
hlsl_build::update_hlsl_shaders(
|
||||
&src_dir.join("shader").join("sm_40.hlsl"),
|
||||
&src_dir.join("data").join("vertex.fx"),
|
||||
&src_dir.join("data").join("pixel.fx"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod hlsl_build {
|
||||
use std::ffi::CString;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
use std::slice;
|
||||
use std::str;
|
||||
|
||||
pub fn update_hlsl_shaders(
|
||||
source_path: &Path,
|
||||
vertex_destination: &Path,
|
||||
pixel_destination: &Path,
|
||||
) {
|
||||
println!("cargo:rerun-if-changed={}", source_path.display());
|
||||
|
||||
let src_data = fs::read_to_string(&source_path).unwrap();
|
||||
|
||||
if vertex_destination.exists() {
|
||||
fs::remove_file(vertex_destination).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
vertex_destination,
|
||||
compile_shader(&src_data, source_path, "VertexMain", "vs_4_0").unwrap_or_else(
|
||||
|error_message| {
|
||||
eprintln!("{}", error_message);
|
||||
panic!("Vertex shader failed to compile");
|
||||
},
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if pixel_destination.exists() {
|
||||
fs::remove_file(pixel_destination).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
pixel_destination,
|
||||
compile_shader(&src_data, source_path, "PixelMain", "ps_4_0").unwrap_or_else(
|
||||
|error_message| {
|
||||
eprintln!("{}", error_message);
|
||||
panic!("Pixel shader failed to compile");
|
||||
},
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn compile_shader(
|
||||
src_data: &str,
|
||||
source_path: &Path,
|
||||
entry_point: &str,
|
||||
target: &str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
use winapi::shared::minwindef::LPCVOID;
|
||||
use winapi::um::d3dcommon::ID3DBlob;
|
||||
use winapi::um::d3dcompiler;
|
||||
|
||||
unsafe {
|
||||
let mut code: *mut ID3DBlob = ptr::null_mut();
|
||||
let mut error_msgs: *mut ID3DBlob = ptr::null_mut();
|
||||
|
||||
let c_entry_point = CString::new(entry_point).unwrap();
|
||||
let c_target = CString::new(target).unwrap();
|
||||
let c_source_path = CString::new(source_path.to_string_lossy().to_string()).unwrap();
|
||||
let hr = d3dcompiler::D3DCompile(
|
||||
src_data.as_bytes().as_ptr() as LPCVOID,
|
||||
src_data.as_bytes().len(),
|
||||
c_source_path.as_ptr(),
|
||||
ptr::null(),
|
||||
ptr::null_mut(),
|
||||
c_entry_point.as_ptr(),
|
||||
c_target.as_ptr(),
|
||||
0,
|
||||
0,
|
||||
&mut code,
|
||||
&mut error_msgs,
|
||||
);
|
||||
|
||||
if hr < 0 {
|
||||
if !error_msgs.is_null() {
|
||||
let error_msgs = error_msgs.as_ref().unwrap();
|
||||
|
||||
let error_msgs = str::from_utf8(slice::from_raw_parts(
|
||||
error_msgs.GetBufferPointer() as *const u8,
|
||||
error_msgs.GetBufferSize(),
|
||||
))
|
||||
.expect("error messages from D3DCompile not valid UTF-8");
|
||||
|
||||
Err(error_msgs.to_string())
|
||||
} else {
|
||||
Err(format!("hresult: {}", hr))
|
||||
}
|
||||
} else {
|
||||
let code = code
|
||||
.as_ref()
|
||||
.expect("null code blob returned from D3DCompile");
|
||||
|
||||
Ok(slice::from_raw_parts(
|
||||
code.GetBufferPointer() as *const u8,
|
||||
code.GetBufferSize(),
|
||||
)
|
||||
.to_vec())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@ -1,592 +0,0 @@
|
||||
#[macro_use]
|
||||
pub extern crate gfx;
|
||||
pub extern crate imgui;
|
||||
|
||||
use gfx::format::BlendFormat;
|
||||
use gfx::handle::{Buffer, RenderTargetView};
|
||||
use gfx::memory::Bind;
|
||||
use gfx::pso::PipelineState;
|
||||
use gfx::texture::{FilterMethod, SamplerInfo, WrapMode};
|
||||
use gfx::traits::FactoryExt;
|
||||
use gfx::{CommandBuffer, Encoder, Factory, IntoIndexBuffer, Rect, Resources, Slice};
|
||||
use imgui::internal::RawWrapper;
|
||||
use imgui::{BackendFlags, DrawCmd, DrawCmdParams, DrawData, DrawIdx, TextureId, Textures};
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::usize;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum RendererError {
|
||||
Update(gfx::UpdateError<usize>),
|
||||
Buffer(gfx::buffer::CreationError),
|
||||
Pipeline(gfx::PipelineStateError<String>),
|
||||
Combined(gfx::CombinedError),
|
||||
BadTexture(TextureId),
|
||||
}
|
||||
|
||||
impl fmt::Display for RendererError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
use self::RendererError::*;
|
||||
match *self {
|
||||
Update(ref e) => write!(f, "{}", e),
|
||||
Buffer(ref e) => write!(f, "{}", e),
|
||||
Pipeline(ref e) => write!(f, "{}", e),
|
||||
Combined(ref e) => write!(f, "{}", e),
|
||||
BadTexture(ref t) => write!(f, "Bad texture ID: {}", t.id()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RendererError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
use self::RendererError::*;
|
||||
match *self {
|
||||
Update(ref e) => Some(e),
|
||||
Buffer(ref e) => Some(e),
|
||||
Pipeline(ref e) => Some(e),
|
||||
Combined(ref e) => Some(e),
|
||||
BadTexture(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gfx::UpdateError<usize>> for RendererError {
|
||||
fn from(e: gfx::UpdateError<usize>) -> RendererError {
|
||||
RendererError::Update(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gfx::buffer::CreationError> for RendererError {
|
||||
fn from(e: gfx::buffer::CreationError) -> RendererError {
|
||||
RendererError::Buffer(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gfx::PipelineStateError<String>> for RendererError {
|
||||
fn from(e: gfx::PipelineStateError<String>) -> RendererError {
|
||||
RendererError::Pipeline(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gfx::CombinedError> for RendererError {
|
||||
fn from(e: gfx::CombinedError) -> RendererError {
|
||||
RendererError::Combined(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Shaders {
|
||||
/// OpenGL 4.0+
|
||||
GlSl400,
|
||||
/// OpenGL 3.2+
|
||||
GlSl150,
|
||||
/// OpenGL 3.0+
|
||||
GlSl130,
|
||||
/// OpenGL 2.0+
|
||||
GlSl110,
|
||||
/// OpenGL ES 3.0+
|
||||
GlSlEs300,
|
||||
/// OpenGL ES 2.0+
|
||||
GlSlEs100,
|
||||
/// HLSL Shader Model 4.0+
|
||||
HlslSm40,
|
||||
}
|
||||
|
||||
impl Shaders {
|
||||
fn get_program_code(self) -> (&'static [u8], &'static [u8]) {
|
||||
use self::Shaders::*;
|
||||
match self {
|
||||
GlSl400 => (
|
||||
include_bytes!("shader/glsl_400.vert"),
|
||||
include_bytes!("shader/glsl_400.frag"),
|
||||
),
|
||||
GlSl150 => (
|
||||
include_bytes!("shader/glsl_150.vert"),
|
||||
include_bytes!("shader/glsl_150.frag"),
|
||||
),
|
||||
GlSl130 => (
|
||||
include_bytes!("shader/glsl_130.vert"),
|
||||
include_bytes!("shader/glsl_130.frag"),
|
||||
),
|
||||
GlSl110 => (
|
||||
include_bytes!("shader/glsl_110.vert"),
|
||||
include_bytes!("shader/glsl_110.frag"),
|
||||
),
|
||||
GlSlEs300 => (
|
||||
include_bytes!("shader/glsles_300.vert"),
|
||||
include_bytes!("shader/glsles_300.frag"),
|
||||
),
|
||||
GlSlEs100 => (
|
||||
include_bytes!("shader/glsles_100.vert"),
|
||||
include_bytes!("shader/glsles_100.frag"),
|
||||
),
|
||||
HlslSm40 => (
|
||||
include_bytes!("data/vertex.fx"),
|
||||
include_bytes!("data/pixel.fx"),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Texture<R> = (
|
||||
gfx::handle::ShaderResourceView<R, [f32; 4]>,
|
||||
gfx::handle::Sampler<R>,
|
||||
);
|
||||
|
||||
pub struct Renderer<Cf: BlendFormat, R: Resources> {
|
||||
vertex_buffer: Buffer<R, GfxDrawVert>,
|
||||
index_buffer: Buffer<R, DrawIdx>,
|
||||
slice: Slice<R>,
|
||||
pso: PipelineState<R, pipeline::Meta<Cf>>,
|
||||
font_texture: Texture<R>,
|
||||
textures: Textures<Texture<R>>,
|
||||
#[cfg(feature = "directx")]
|
||||
constants: Buffer<R, constants::Constants>,
|
||||
}
|
||||
|
||||
impl<Cf, R> Renderer<Cf, R>
|
||||
where
|
||||
Cf: BlendFormat,
|
||||
R: Resources,
|
||||
{
|
||||
pub fn init<F: Factory<R>>(
|
||||
ctx: &mut imgui::Context,
|
||||
factory: &mut F,
|
||||
shaders: Shaders,
|
||||
) -> Result<Renderer<Cf, R>, RendererError> {
|
||||
let (vs_code, ps_code) = shaders.get_program_code();
|
||||
let pso = factory.create_pipeline_simple(vs_code, ps_code, pipeline::new::<Cf>())?;
|
||||
let vertex_buffer = factory.create_buffer::<GfxDrawVert>(
|
||||
256,
|
||||
gfx::buffer::Role::Vertex,
|
||||
gfx::memory::Usage::Dynamic,
|
||||
Bind::empty(),
|
||||
)?;
|
||||
let index_buffer = factory.create_buffer::<DrawIdx>(
|
||||
256,
|
||||
gfx::buffer::Role::Index,
|
||||
gfx::memory::Usage::Dynamic,
|
||||
Bind::empty(),
|
||||
)?;
|
||||
let font_texture = upload_font_texture(ctx.fonts(), factory)?;
|
||||
let slice = Slice {
|
||||
start: 0,
|
||||
end: 0,
|
||||
base_vertex: 0,
|
||||
instances: None,
|
||||
buffer: index_buffer.clone().into_index_buffer(factory),
|
||||
};
|
||||
ctx.set_renderer_name(Some(format!(
|
||||
"imgui-gfx-renderer {}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
)));
|
||||
ctx.io_mut()
|
||||
.backend_flags
|
||||
.insert(BackendFlags::RENDERER_HAS_VTX_OFFSET);
|
||||
Ok(Renderer {
|
||||
vertex_buffer,
|
||||
index_buffer,
|
||||
slice,
|
||||
pso,
|
||||
font_texture,
|
||||
textures: Textures::new(),
|
||||
#[cfg(feature = "directx")]
|
||||
constants: factory.create_constant_buffer(1),
|
||||
})
|
||||
}
|
||||
pub fn reload_font_texture<F: Factory<R>>(
|
||||
&mut self,
|
||||
ctx: &mut imgui::Context,
|
||||
factory: &mut F,
|
||||
) -> Result<(), RendererError> {
|
||||
self.font_texture = upload_font_texture(ctx.fonts(), factory)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn textures(&mut self) -> &mut Textures<Texture<R>> {
|
||||
&mut self.textures
|
||||
}
|
||||
pub fn render<F: Factory<R>, C: CommandBuffer<R>>(
|
||||
&mut self,
|
||||
factory: &mut F,
|
||||
encoder: &mut Encoder<R, C>,
|
||||
target: &mut RenderTargetView<R, Cf>,
|
||||
draw_data: &DrawData,
|
||||
) -> Result<(), RendererError> {
|
||||
let fb_width = draw_data.display_size[0] * draw_data.framebuffer_scale[0];
|
||||
let fb_height = draw_data.display_size[1] * draw_data.framebuffer_scale[1];
|
||||
if !(fb_width > 0.0 && fb_height > 0.0) {
|
||||
return Ok(());
|
||||
}
|
||||
let left = draw_data.display_pos[0];
|
||||
let right = draw_data.display_pos[0] + draw_data.display_size[0];
|
||||
let top = draw_data.display_pos[1];
|
||||
let bottom = draw_data.display_pos[1] + draw_data.display_size[1];
|
||||
let matrix = [
|
||||
[(2.0 / (right - left)), 0.0, 0.0, 0.0],
|
||||
[0.0, (2.0 / (top - bottom)), 0.0, 0.0],
|
||||
[0.0, 0.0, -1.0, 0.0],
|
||||
[
|
||||
(right + left) / (left - right),
|
||||
(top + bottom) / (bottom - top),
|
||||
0.0,
|
||||
1.0,
|
||||
],
|
||||
];
|
||||
let clip_off = draw_data.display_pos;
|
||||
let clip_scale = draw_data.framebuffer_scale;
|
||||
for draw_list in draw_data.draw_lists() {
|
||||
self.upload_vertex_buffer(factory, encoder, unsafe {
|
||||
draw_list.transmute_vtx_buffer::<GfxDrawVert>()
|
||||
})?;
|
||||
self.upload_index_buffer(factory, encoder, draw_list.idx_buffer())?;
|
||||
self.slice.start = 0;
|
||||
for cmd in draw_list.commands() {
|
||||
match cmd {
|
||||
DrawCmd::Elements {
|
||||
count,
|
||||
cmd_params:
|
||||
DrawCmdParams {
|
||||
clip_rect,
|
||||
texture_id,
|
||||
vtx_offset,
|
||||
idx_offset,
|
||||
..
|
||||
},
|
||||
} => {
|
||||
let clip_rect = [
|
||||
(clip_rect[0] - clip_off[0]) * clip_scale[0],
|
||||
(clip_rect[1] - clip_off[1]) * clip_scale[1],
|
||||
(clip_rect[2] - clip_off[0]) * clip_scale[0],
|
||||
(clip_rect[3] - clip_off[1]) * clip_scale[1],
|
||||
];
|
||||
|
||||
self.slice.start = idx_offset as u32;
|
||||
self.slice.end = self.slice.start + count as u32;
|
||||
self.slice.base_vertex = vtx_offset as u32;
|
||||
|
||||
if clip_rect[0] < fb_width
|
||||
&& clip_rect[1] < fb_height
|
||||
&& clip_rect[2] >= 0.0
|
||||
&& clip_rect[3] >= 0.0
|
||||
{
|
||||
let scissor = Rect {
|
||||
x: f32::max(0.0, clip_rect[0]).floor() as u16,
|
||||
y: f32::max(0.0, clip_rect[1]).floor() as u16,
|
||||
w: (clip_rect[2] - clip_rect[0]).abs().ceil() as u16,
|
||||
h: (clip_rect[3] - clip_rect[1]).abs().ceil() as u16,
|
||||
};
|
||||
let tex = self.lookup_texture(texture_id)?;
|
||||
#[cfg(feature = "directx")]
|
||||
{
|
||||
let constants = constants::Constants { matrix };
|
||||
encoder.update_constant_buffer(&self.constants, &constants);
|
||||
}
|
||||
let data = pipeline::Data {
|
||||
vertex_buffer: &self.vertex_buffer,
|
||||
#[cfg(not(feature = "directx"))]
|
||||
matrix: &matrix,
|
||||
#[cfg(feature = "directx")]
|
||||
constants: &self.constants,
|
||||
tex,
|
||||
scissor: &scissor,
|
||||
target,
|
||||
};
|
||||
encoder.draw(&self.slice, &self.pso, &data);
|
||||
}
|
||||
}
|
||||
DrawCmd::ResetRenderState => (), // TODO
|
||||
DrawCmd::RawCallback { callback, raw_cmd } => unsafe {
|
||||
callback(draw_list.raw(), raw_cmd)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn upload_vertex_buffer<F: Factory<R>, C: CommandBuffer<R>>(
|
||||
&mut self,
|
||||
factory: &mut F,
|
||||
encoder: &mut Encoder<R, C>,
|
||||
vtx_buffer: &[GfxDrawVert],
|
||||
) -> Result<(), RendererError> {
|
||||
if self.vertex_buffer.len() < vtx_buffer.len() {
|
||||
self.vertex_buffer = factory.create_buffer::<GfxDrawVert>(
|
||||
vtx_buffer.len(),
|
||||
gfx::buffer::Role::Vertex,
|
||||
gfx::memory::Usage::Dynamic,
|
||||
Bind::empty(),
|
||||
)?;
|
||||
}
|
||||
encoder.update_buffer(&self.vertex_buffer, vtx_buffer, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
fn upload_index_buffer<F: Factory<R>, C: CommandBuffer<R>>(
|
||||
&mut self,
|
||||
factory: &mut F,
|
||||
encoder: &mut Encoder<R, C>,
|
||||
idx_buffer: &[DrawIdx],
|
||||
) -> Result<(), RendererError> {
|
||||
if self.index_buffer.len() < idx_buffer.len() {
|
||||
self.index_buffer = factory.create_buffer::<DrawIdx>(
|
||||
idx_buffer.len(),
|
||||
gfx::buffer::Role::Index,
|
||||
gfx::memory::Usage::Dynamic,
|
||||
Bind::empty(),
|
||||
)?;
|
||||
self.slice.buffer = self.index_buffer.clone().into_index_buffer(factory);
|
||||
}
|
||||
encoder.update_buffer(&self.index_buffer, idx_buffer, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
fn lookup_texture(&self, texture_id: TextureId) -> Result<&Texture<R>, RendererError> {
|
||||
if texture_id.id() == usize::MAX {
|
||||
Ok(&self.font_texture)
|
||||
} else if let Some(texture) = self.textures.get(texture_id) {
|
||||
Ok(texture)
|
||||
} else {
|
||||
Err(RendererError::BadTexture(texture_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_font_texture<R: Resources, F: Factory<R>>(
|
||||
mut fonts: imgui::FontAtlasRefMut,
|
||||
factory: &mut F,
|
||||
) -> Result<Texture<R>, RendererError> {
|
||||
let texture = fonts.build_rgba32_texture();
|
||||
let (_, texture_view) = factory.create_texture_immutable_u8::<gfx::format::Srgba8>(
|
||||
gfx::texture::Kind::D2(
|
||||
texture.width as u16,
|
||||
texture.height as u16,
|
||||
gfx::texture::AaMode::Single,
|
||||
),
|
||||
gfx::texture::Mipmap::Provided,
|
||||
&[texture.data],
|
||||
)?;
|
||||
fonts.tex_id = TextureId::from(usize::MAX);
|
||||
let sampler = factory.create_sampler(SamplerInfo::new(FilterMethod::Bilinear, WrapMode::Tile));
|
||||
let font_texture = (texture_view, sampler);
|
||||
Ok(font_texture)
|
||||
}
|
||||
|
||||
#[cfg(feature = "directx")]
|
||||
mod constants {
|
||||
use gfx::gfx_constant_struct_meta;
|
||||
use gfx::gfx_impl_struct_meta;
|
||||
|
||||
gfx::gfx_constant_struct! {
|
||||
Constants {
|
||||
// `matrix` is a reserved keyword in HLSL
|
||||
matrix: [[f32; 4]; 4] = "matrix_",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This is basically what gfx_pipeline generates, but with some changes:
|
||||
//
|
||||
// * Data struct contains references to avoid copying
|
||||
// * Everything is parameterized with BlendFormat
|
||||
// * Pipeline init is specialized for our structs
|
||||
mod pipeline {
|
||||
use super::*;
|
||||
use gfx::format::BlendFormat;
|
||||
use gfx::handle::Manager;
|
||||
use gfx::preset::blend;
|
||||
use gfx::pso::{
|
||||
AccessInfo, DataBind, DataLink, Descriptor, InitError, PipelineData, PipelineInit,
|
||||
RawDataSet,
|
||||
};
|
||||
use gfx::state::ColorMask;
|
||||
use gfx::{ProgramInfo, Resources};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Data<'a, R: Resources, Cf: BlendFormat + 'a> {
|
||||
pub vertex_buffer: &'a <gfx::VertexBuffer<GfxDrawVert> as DataBind<R>>::Data,
|
||||
#[cfg(not(feature = "directx"))]
|
||||
pub matrix: &'a <gfx::Global<[[f32; 4]; 4]> as DataBind<R>>::Data,
|
||||
#[cfg(feature = "directx")]
|
||||
pub constants: &'a <gfx::ConstantBuffer<super::constants::Constants> as DataBind<R>>::Data,
|
||||
pub tex: &'a <gfx::TextureSampler<[f32; 4]> as DataBind<R>>::Data,
|
||||
pub target: &'a <gfx::BlendTarget<Cf> as DataBind<R>>::Data,
|
||||
pub scissor: &'a <gfx::Scissor as DataBind<R>>::Data,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash, PartialEq)]
|
||||
pub struct Meta<Cf: BlendFormat> {
|
||||
vertex_buffer: gfx::VertexBuffer<GfxDrawVert>,
|
||||
#[cfg(not(feature = "directx"))]
|
||||
matrix: gfx::Global<[[f32; 4]; 4]>,
|
||||
#[cfg(feature = "directx")]
|
||||
constants: gfx::ConstantBuffer<super::constants::Constants>,
|
||||
tex: gfx::TextureSampler<[f32; 4]>,
|
||||
target: gfx::BlendTarget<Cf>,
|
||||
scissor: gfx::Scissor,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Init<'a, Cf: BlendFormat> {
|
||||
vertex_buffer: <gfx::VertexBuffer<GfxDrawVert> as DataLink<'a>>::Init,
|
||||
#[cfg(not(feature = "directx"))]
|
||||
matrix: <gfx::Global<[[f32; 4]; 4]> as DataLink<'a>>::Init,
|
||||
#[cfg(feature = "directx")]
|
||||
constants: <gfx::ConstantBuffer<super::constants::Constants> as DataLink<'a>>::Init,
|
||||
tex: <gfx::TextureSampler<[f32; 4]> as DataLink<'a>>::Init,
|
||||
target: <gfx::BlendTarget<Cf> as DataLink<'a>>::Init,
|
||||
scissor: <gfx::Scissor as DataLink<'a>>::Init,
|
||||
}
|
||||
|
||||
impl<'a, Cf: BlendFormat> PipelineInit for Init<'a, Cf> {
|
||||
type Meta = Meta<Cf>;
|
||||
fn link_to<'s>(
|
||||
&self,
|
||||
desc: &mut Descriptor,
|
||||
info: &'s ProgramInfo,
|
||||
) -> Result<Meta<Cf>, InitError<&'s str>> {
|
||||
let mut meta = Meta {
|
||||
vertex_buffer: DataLink::new(),
|
||||
#[cfg(not(feature = "directx"))]
|
||||
matrix: DataLink::new(),
|
||||
#[cfg(feature = "directx")]
|
||||
constants: DataLink::new(),
|
||||
tex: DataLink::new(),
|
||||
target: DataLink::new(),
|
||||
scissor: DataLink::new(),
|
||||
};
|
||||
if let Some(d) = meta
|
||||
.vertex_buffer
|
||||
.link_vertex_buffer(0, &self.vertex_buffer)
|
||||
{
|
||||
assert!(meta.vertex_buffer.is_active());
|
||||
desc.vertex_buffers[0] = Some(d);
|
||||
}
|
||||
for at in &info.vertex_attributes {
|
||||
match meta.vertex_buffer.link_input(at, &self.vertex_buffer) {
|
||||
Some(Ok(d)) => {
|
||||
assert!(meta.vertex_buffer.is_active());
|
||||
desc.attributes[at.slot as usize] = Some(d);
|
||||
continue;
|
||||
}
|
||||
Some(Err(fm)) => return Err(InitError::VertexImport(&at.name, Some(fm))),
|
||||
None => return Err(InitError::VertexImport(&at.name, None)),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "directx")]
|
||||
for cb in &info.constant_buffers {
|
||||
match meta.constants.link_constant_buffer(cb, &self.constants) {
|
||||
Some(Ok(d)) => {
|
||||
assert!(meta.constants.is_active());
|
||||
desc.constant_buffers[cb.slot as usize] = Some(d);
|
||||
}
|
||||
Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))),
|
||||
None => return Err(InitError::ConstantBuffer(&cb.name, None)),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "directx"))]
|
||||
for gc in &info.globals {
|
||||
match meta.matrix.link_global_constant(gc, &self.matrix) {
|
||||
Some(Ok(())) => assert!(meta.matrix.is_active()),
|
||||
Some(Err(e)) => return Err(InitError::GlobalConstant(&gc.name, Some(e))),
|
||||
None => return Err(InitError::GlobalConstant(&gc.name, None)),
|
||||
}
|
||||
}
|
||||
for srv in &info.textures {
|
||||
match meta.tex.link_resource_view(srv, &self.tex) {
|
||||
Some(Ok(d)) => {
|
||||
assert!(meta.tex.is_active());
|
||||
desc.resource_views[srv.slot as usize] = Some(d);
|
||||
}
|
||||
Some(Err(_)) => return Err(InitError::ResourceView(&srv.name, Some(()))),
|
||||
None => return Err(InitError::ResourceView(&srv.name, None)),
|
||||
}
|
||||
}
|
||||
for sm in &info.samplers {
|
||||
match meta.tex.link_sampler(sm, &self.tex) {
|
||||
Some(d) => {
|
||||
assert!(meta.tex.is_active());
|
||||
desc.samplers[sm.slot as usize] = Some(d);
|
||||
}
|
||||
None => return Err(InitError::Sampler(&sm.name, None)),
|
||||
}
|
||||
}
|
||||
for out in &info.outputs {
|
||||
match meta.target.link_output(out, &self.target) {
|
||||
Some(Ok(d)) => {
|
||||
assert!(meta.target.is_active());
|
||||
desc.color_targets[out.slot as usize] = Some(d);
|
||||
}
|
||||
Some(Err(fm)) => return Err(InitError::PixelExport(&out.name, Some(fm))),
|
||||
None => return Err(InitError::PixelExport(&out.name, None)),
|
||||
}
|
||||
}
|
||||
if !info.knows_outputs {
|
||||
use gfx::shade::core::*;
|
||||
let mut out = OutputVar {
|
||||
name: String::new(),
|
||||
slot: 0,
|
||||
base_type: BaseType::F32,
|
||||
container: ContainerType::Vector(4),
|
||||
};
|
||||
match meta.target.link_output(&out, &self.target) {
|
||||
Some(Ok(d)) => {
|
||||
assert!(meta.target.is_active());
|
||||
desc.color_targets[out.slot as usize] = Some(d);
|
||||
out.slot += 1;
|
||||
}
|
||||
Some(Err(fm)) => return Err(InitError::PixelExport("!known", Some(fm))),
|
||||
None => (),
|
||||
}
|
||||
}
|
||||
if meta.scissor.link_scissor() {
|
||||
assert!(meta.scissor.is_active());
|
||||
desc.scissor = true;
|
||||
}
|
||||
Ok(meta)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: Resources, Cf: BlendFormat> PipelineData<R> for Data<'a, R, Cf> {
|
||||
type Meta = Meta<Cf>;
|
||||
fn bake_to(
|
||||
&self,
|
||||
out: &mut RawDataSet<R>,
|
||||
meta: &Meta<Cf>,
|
||||
man: &mut Manager<R>,
|
||||
access: &mut AccessInfo<R>,
|
||||
) {
|
||||
meta.vertex_buffer
|
||||
.bind_to(out, self.vertex_buffer, man, access);
|
||||
#[cfg(not(feature = "directx"))]
|
||||
{
|
||||
meta.matrix.bind_to(out, self.matrix, man, access);
|
||||
}
|
||||
#[cfg(feature = "directx")]
|
||||
{
|
||||
meta.constants.bind_to(out, self.constants, man, access);
|
||||
}
|
||||
meta.tex.bind_to(out, self.tex, man, access);
|
||||
meta.target.bind_to(out, self.target, man, access);
|
||||
meta.scissor.bind_to(out, self.scissor, man, access);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new<Cf: BlendFormat>() -> Init<'static, Cf> {
|
||||
Init {
|
||||
vertex_buffer: (),
|
||||
#[cfg(not(feature = "directx"))]
|
||||
matrix: "matrix",
|
||||
#[cfg(feature = "directx")]
|
||||
constants: "Constants",
|
||||
tex: "tex",
|
||||
target: ("Target0", ColorMask::all(), blend::ALPHA),
|
||||
scissor: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gfx_vertex_struct! {
|
||||
GfxDrawVert {
|
||||
pos: [f32; 2] = "pos",
|
||||
uv: [f32; 2] = "uv",
|
||||
col: [gfx::format::U8Norm; 4] = "col",
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
#version 110
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
varying vec2 f_uv;
|
||||
varying vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_FragColor
|
||||
|
||||
void main() {
|
||||
gl_FragColor = f_color * texture2D(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 110
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
attribute vec2 pos;
|
||||
attribute vec2 uv;
|
||||
attribute vec4 col;
|
||||
|
||||
varying vec2 f_uv;
|
||||
varying vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
#version 130
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
in vec2 f_uv;
|
||||
in vec4 f_color;
|
||||
|
||||
out vec4 Target0;
|
||||
|
||||
void main() {
|
||||
Target0 = f_color * texture(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 130
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
in vec2 pos;
|
||||
in vec2 uv;
|
||||
in vec4 col;
|
||||
|
||||
out vec2 f_uv;
|
||||
out vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
#version 150
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
in vec2 f_uv;
|
||||
in vec4 f_color;
|
||||
|
||||
out vec4 Target0;
|
||||
|
||||
void main() {
|
||||
Target0 = f_color * texture(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 150
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
in vec2 pos;
|
||||
in vec2 uv;
|
||||
in vec4 col;
|
||||
|
||||
out vec2 f_uv;
|
||||
out vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
#version 400
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
in vec2 f_uv;
|
||||
in vec4 f_color;
|
||||
|
||||
out vec4 Target0;
|
||||
|
||||
void main() {
|
||||
Target0 = f_color * texture(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 400
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
in vec2 pos;
|
||||
in vec2 uv;
|
||||
in vec4 col;
|
||||
|
||||
out vec2 f_uv;
|
||||
out vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
#version 100
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
varying mediump vec2 f_uv;
|
||||
varying lowp vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_FragColor
|
||||
|
||||
void main() {
|
||||
gl_FragColor = f_color * texture2D(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 100
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
attribute mediump vec2 pos;
|
||||
attribute mediump vec2 uv;
|
||||
attribute lowp vec4 col;
|
||||
|
||||
varying mediump vec2 f_uv;
|
||||
varying lowp vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
#version 300 es
|
||||
|
||||
uniform sampler2D tex;
|
||||
|
||||
in mediump vec2 f_uv;
|
||||
in lowp vec4 f_color;
|
||||
|
||||
out lowp vec4 Target0;
|
||||
|
||||
void main() {
|
||||
Target0 = f_color * texture(tex, f_uv.st);
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
#version 300 es
|
||||
|
||||
uniform mat4 matrix;
|
||||
|
||||
in mediump vec2 pos;
|
||||
in mediump vec2 uv;
|
||||
in lowp vec4 col;
|
||||
|
||||
out mediump vec2 f_uv;
|
||||
out lowp vec4 f_color;
|
||||
|
||||
// Built-in:
|
||||
// vec4 gl_Position
|
||||
|
||||
void main() {
|
||||
f_uv = uv;
|
||||
f_color = col;
|
||||
gl_Position = matrix * vec4(pos.xy, 0, 1);
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
cbuffer Constants : register(b0) {
|
||||
float4x4 matrix_;
|
||||
}
|
||||
|
||||
Texture2D tex;
|
||||
SamplerState tex_;
|
||||
|
||||
struct VIn {
|
||||
float2 position : pos;
|
||||
float2 uv : uv;
|
||||
float4 color : col;
|
||||
};
|
||||
|
||||
struct VOut
|
||||
{
|
||||
float4 position : SV_POSITION;
|
||||
float2 uv : TEXCOORD0;
|
||||
float4 color : COLOR;
|
||||
};
|
||||
|
||||
VOut VertexMain(VIn vertex)
|
||||
{
|
||||
VOut output;
|
||||
output.position = mul(matrix_, float4(vertex.position, 0.0, 1.0));
|
||||
output.uv = vertex.uv;
|
||||
output.color = vertex.color;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
float4 PixelMain(VOut vout) : SV_TARGET
|
||||
{
|
||||
return vout.color * tex.Sample(tex_, vout.uv);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user