self.stack.pop();
if self.stack.is_empty(){
println!("堆疊結束");
}
}
fn push(&mut self,state:Box<dyn State>){
self.stack.push(state);
}
fn update(&mut self,args:&UpdateArgs){
if let Some(top)=self.stack.last_mut(){
top.update(args);
}
}
fn render(&mut self,c:Context,g:&mut G2d,glyphs:&mut Glyphs){
for state in &mut self.stack{
state.render(c, g, glyphs);
}
}
fn input(&mut self,button:Button){
if let Some(top)=self.stack.last_mut(){
if let Some(cmd)=top.input(button){
match cmd{
StateCommand::Push(state)=>self.push(state),
StateCommand::Pop=>self.pop(),
StateCommand::None=>{}
}
}
}
}
let text_width=text_str.len() as f64 *24.0/2.0;
let x=320.0-text_width;
let transform=c.transform.trans(x, y);
let text_obj=graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 32);
text_obj.draw(
text_str,
glyphs, &graphics::DrawState::default(), c.transform, g).unwrap();
draw_text_centered(
"主頁", c, g, glyphs, 240.0);
graphics::ellipse(
[1.0, 0.0, 0.0, 1.0],
[self.circle_x-20.0,300.0-20.0,40.0,40.0], c.transform, g);
let fps_text=format!("{}",self.fps);
let text_obj=graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 24);
text_obj.draw(
&fps_text, glyphs,&graphics::DrawState::default(), c.transform.trans(10.0, 460.0), g).unwrap
();
}
fn input(&mut self,button:Button)->Option<StateCommand> {
if let Button::Keyboard(key)=button{
if key == Key::M {
return Some(StateCommand::Push(Box::new(MainPage::new())));
}
}
None
}
}
impl State for ModalWindow{
fn update(&mut self,args:&UpdateArgs) {}
fn render(&mut self,c:Context,g:&mut G2d,glyphs:&mut Glyphs) {
graphics::rectangle(
[1.0;4],
[120.0,140.0,240.0,440.0],
c.transform, g);
code
let rect=[0.0,0.0,640.0,480.0];
graphics::rectangle([1.0;4], rect, c.transform.trans(150.0, 50.0), g);
let text_obj=graphics::text::Text::new_color([1.0;4], 32);
text_obj.draw(
"按下M",
glyphs,
&graphics::DrawState::default(),
c.transform, g).unwrap();
let conter_text=format!("鍵盤按下{}",self.counter);
let text_obj=graphics::text::Text::new_color([1.0;4], 32);
text_obj.draw(&conter_text, glyphs, &graphics::DrawState::default(), c.transform.trans(10.0, 50.0), g).unwrap();
}
fn input(&mut self,button:Button)->Option<StateCommand> {
if let Button::Keyboard(key)=button{
match key {
Key::Escape=>{return Some(StateCommand::Pop);}
Key::Space=>{
self.counter +=1;
println!("列印{}",self.counter);
return Some(StateCommand::None);
}
_=>{}
}
}
None
}
}
fn main(){
let mut window22:PistonWindow=WindowSettings::new("fdfdf", [640.0,480.0,]).exit_on_esc(true).build().unwrap();
code
let mut assets=find_folder::Search::ParentsThenKids(3, 3).for_folder("assets").unwrap();
let font_path=assets.join("mingliu.ttc");
let mut glyphs=window22.load_font(font_path).expect("找不到字形");
let mut state_stack=StateStack::new(Box::new(MainPage::new()));
while let Some(event) = window22.next() {
if let Some(args)=event.update_args(){
state_stack.update(&args);
}
if let Some(button)=event.press_args(){
state_stack.input(button);
}
window22.draw_2d(&event, |c,g,device|{
state_stack.render(c, g, &mut glyphs);
glyphs.factory.encoder.flush(device);
});
if state_stack.is_empty(){
break;
}
}
fn main() {
let mut window: PistonWindow = WindowSettings::new("Dashed border select", [400, 400])
.exit_on_esc(true)
.build()
.unwrap();
let mut draggable = Draggable::new(50.0, 50.0, 100.0, 100.0);
while let Some(e) = window.next() {
if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_press(x, y);
}
}
if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
draggable.mouse_release();
}
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_move(x, y);
}
window.draw_2d(&e, |c, g, _device| {
clear([1.0; 4], g);
draggable.draw(c, g);
});
}
}
補充
你也可以加入 Debug 印出位置,確保 mouse_press 有被觸發。
如果還是沒辦法拖曳,請確認 Piston、PistonWindow 版本無誤。
這樣改了之後,應該能正確點擊方塊開始拖曳,拖動滑鼠時更新位置,放開滑鼠時停止拖曳。祝你成功!
User
error[E0412]: cannot find type PistonWindow in this scope
--> src\main.rs:2:21
|
2 | let mut window: PistonWindow = WindowSettings::new("Dashed border select", [400, 400])
| ^^^^^^^^^^^^ not found in this scope
|
help: consider importing this struct
|
1 + use piston_window::PistonWindow;
|
error[E0433]: failed to resolve: use of undeclared type WindowSettings
--> src\main.rs:2:36
|
2 | let mut window: PistonWindow = WindowSettings::new("Dashed border select", [400, 400])
| ^^^^^^^^^^^^^^ use of undeclared type WindowSettings
|
help: consider importing one of these structs
|
1 + use piston::WindowSettings;
|
1 + use piston_window::WindowSettings;
|
error[E0433]: failed to resolve: use of undeclared type Button
--> src\main.rs:10:21
|
10 | if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
| ^^^^^^ use of undeclared type Button
|
help: consider importing one of these items
|
1 + use conrod_core::event::Button;
|
1 + use conrod_core::input::Button;
|
1 + use conrod_core::input::state::mouse::Button;
|
1 + use conrod_core::widget::Button;
|
and 2 other candidates
error[E0433]: failed to resolve: use of undeclared type MouseButton
--> src\main.rs:10:35
|
10 | if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
| ^^^^^^^^^^^ use of undeclared type MouseButton
|
help: consider importing one of these enums
|
1 + use conrod_core::input::MouseButton;
|
1 + use crossterm::event::MouseButton;
|
1 + use piston::MouseButton;
|
1 + use piston_window::MouseButton;
|
and 1 other candidate
error[E0433]: failed to resolve: use of undeclared type Button
--> src\main.rs:16:21
|
16 | if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
| ^^^^^^ use of undeclared type Button
|
help: consider importing one of these items
|
1 + use conrod_core::event::Button;
|
1 + use conrod_core::input::Button;
|
1 + use conrod_core::input::state::mouse::Button;
|
1 + use conrod_core::widget::Button;
|
and 2 other candidates
error[E0433]: failed to resolve: use of undeclared type MouseButton
--> src\main.rs:16:35
|
16 | if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
| ^^^^^^^^^^^ use of undeclared type MouseButton
|
help: consider importing one of these enums
|
1 + use conrod_core::input::MouseButton;
|
1 + use crossterm::event::MouseButton;
|
1 + use piston::MouseButton;
|
1 + use piston_window::MouseButton;
|
and 1 other candidate
error[E0425]: cannot find function clear in this scope
--> src\main.rs:25:13
|
25 | clear([1.0; 4], g);
| ^^^^^ not found in this scope
|
help: consider importing this function
|
1 + use piston_window::clear;
|
error[E0599]: no method named press_args found for enum Event in the current scope
--> src\main.rs:128:59
|
128 | if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
| ^^^^^^^^^^
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\button.rs:79:8
|
79 | fn press_args(&self) -> Option {
| ---------- the method is available for Event here
|
= help: items from traits can only be used if the trait is in scope
help: there is a method press with a similar name, but with different arguments
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\button.rs:75:5
|
75 | / fn press<U, F>(&self, f: F) -> Option
76 | | where
77 | | F: FnMut(Button) -> U;
| |______________________________^
help: trait PressEvent which provides press_args is implemented but not in scope; perhaps you want to import it
|
1 + use piston_window::PressEvent;
|
error[E0599]: no method named mouse_cursor found for enum Event in the current scope
--> src\main.rs:129:37
|
129 | if let Some([x, y]) = e.mouse_cursor() {
| ^^^^^^^^^^^^
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\mouse.rs:82:8
|
82 | fn mouse_cursor<U, F>(&self, f: F) -> Option
| ------------ the method is available for Event here
|
= help: items from traits can only be used if the trait is in scope
help: trait MouseCursorEvent which provides mouse_cursor is implemented but not in scope; perhaps you want to import it
|
1 + use piston_window::MouseCursorEvent;
|
help: there is a method mouse_cursor_args with a similar name
|
129 | if let Some([x, y]) = e.mouse_cursor_args() {
| +++++
error[E0599]: no method named release_args found for enum Event in the current scope
--> src\main.rs:134:59
|
134 | if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
| ^^^^^^^^^^^^
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\button.rs:134:8
|
134 | fn release_args(&self) -> Option {
| ------------ the method is available for Event here
|
= help: items from traits can only be used if the trait is in scope
help: there is a method release with a similar name, but with different arguments
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\button.rs:130:5
|
130 | / fn release<U, F>(&self, f: F) -> Option
131 | | where
132 | | F: FnMut(Button) -> U;
| |______________________________^
help: trait which provides is implemented but not in scope; perhaps you want to import it
|
1 + use piston_window::ReleaseEvent;
|
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0599]: no variant or associated item named Press found for enum piston_window::Input in the current scope
--> src\main.rs:138:33
|
138 | Event::Input(Input::Press(button), _) => {
| ^^^^^ variant or associated item not found in Input
error[E0599]: no variant or associated item named Release found for enum piston_window::Input in the current scope
--> src\main.rs:143:33
|
143 | Event::Input(Input::Release(button), _) => {
| ^^^^^^^ variant or associated item not found in Input
error[E0023]: this pattern has 2 fields, but the corresponding tuple variant has 1 field
--> src\main.rs:133:59
|
133 | if let piston_window::Motion::MouseCursor(x, y) = motion {
| ^ ^ expected 1 field, found 2
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\lib.rs:86:17
|
86 | MouseCursor([f64; 2]),
| -------- tuple variant has 1 field
Some errors have detailed explanations: E0023, E0599.
For more information about an error, try rustc --explain E0023.
error: could not compile my_project (bin "my_project") due to 3 previous errors
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0499]: cannot borrow draggables as mutable more than once at a time
--> src\main.rs:178:58
|
175 | ... for (i, d) in draggables.iter_mut().enumerate().rev() {
| ---------- first mutable borrow occurs here
...
178 | ... for other in &mut draggables {
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
...
181 | ... d.start_drag(cursor_pos[0], cursor_pos[1]);
| - first borrow later used here
For more information about this error, try rustc --explain E0499.
error: could not compile my_project (bin "my_project") due to 1 previous error
PS C:\Users\fer52\mynewcargo\my_project> cargo run
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error: expected one of ! or ::, found (
--> src\main.rs:1:13
|
1 | Event::Input(input, _) => {
| ^ expected one of ! or ::
error: could not compile my_project (bin "my_project") due to 1 previous error
Assistant
你的錯誤訊息:
code
error: expected one of `!` or `::`, found `(`
--> src\main.rs:1:13
|
1 | Event::Input(input, _) => {
| ^ expected one of `!` or `::`
表示你直接寫了 Event::Input(input, _) => { 之類的語法,但這通常是出現在 match 或 if let 的分支中,錯誤的原因是你把 Event::Input(...) => { 放在全檔第一行,導致語法錯誤。
根本原因:
這段 Event::Input(input, _) => { ... } 是 match 詞法的一部分,你必須把它放進 match some_expression { ... } 裡面。
你可能寫成像:
rust
Event::Input(input, _) => {
//...
}
獨立使用,但 Rust 不是這樣寫分支,要在 match 裡
正確寫法範例:
rust
while let Some(event) = window.next() {
match event {
Event::Input(input, _) => {
// 事件處理程式碼
}
Event::Loop(piston_window::Loop::Render(_)) => {
// 渲染程式碼
}
_ => {}
}
}
你貼錯誤的程式碼位置了,或者解讀錯誤訊息。
請把你整個 while let Some(event) = window.next() 區塊貼上,才能幫你檢查問題。
如果你是把我之前回覆的 match 裡面 code copy 出來,請務必連同 while let Some(event) = window.next() 與 match event { ... } 一起貼。
如果要快速修正這個錯誤,只要把 Event::Input(input, _) => { 改成在 match 區塊裡使用即可。
若需要,我可以幫你把完整的 main 函式再貼一次範例,請回應告訴我!
User
Event::Input(input, _) => {
match input {
Input::Move(motion) => {
if let Motion::MouseCursor(pos) = motion {
cursor_pos = pos;
if let Some(idx) = dragging_index {
draggables[idx].move_to(pos[0], pos[1]);
let mut collision = false;
for (i, other) in draggables.iter().enumerate() {
if i != idx && draggables[idx].intersects(other) {
collision = true;
break;
}
}
if collision {
if idx != draggables.len() - 1 {
let d = draggables.remove(idx);
draggables.push(d);
dragging_index = Some(draggables.len() - 1);
}
} else {
if idx != 0 {
let d = draggables.remove(idx);
draggables.insert(0, d);
dragging_index = Some(0);
}
}
}
}
}
Input::Button(button_args) => {
if button_args.button == Button::Mouse(MouseButton::Left) {
match button_args.state {
ButtonState::Press => {
dragging_index = None;
let mut selected_index: Option = None;
for (i, d) in draggables.iter().enumerate().rev() {
if d.is_inside(cursor_pos[0], cursor_pos[1]) {
selected_index = Some(i);
break;
}
}
code
if let Some(i) = selected_index {
for d in &mut draggables {
d.selected = false;
}
draggables[i].start_drag(cursor_pos[0], cursor_pos[1]);
dragging_index = Some(i);
}
}
ButtonState::Release => {
if let Some(idx) = dragging_index {
draggables[idx].stop_drag();
}
dragging_index = None;
}
}
}
}
_ => {}
}
},
PS C:\Users\fer52\mynewcargo\my_project> cargo run
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error: expected one of ! or ::, found (
--> src\main.rs:1:13
|
1 | Event::Input(input, _) => {
| ^ expected one of ! or ::
error: could not compile my_project (bin "my_project") due to 1 previous error
Assistant
你目前貼的這段程式碼:
rust
Event::Input(input, _) => {
match input {
...
}
},
[dependencies]
piston_window = "0.132.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
範例完整程式碼
rust
User
error[E0271]: type mismatch resolving <G as Graphics>::Texture == Texture<Resources>
--> src\main.rs:42:71
|
42 | text_obj.draw(text, glyphs, &DrawState::default(), transform, g).ok();
| ---- required by a bound introduced by this call ^ expected Texture<Resources>, found associated type
|
= note: expected struct Texture<gfx_device_gl::Resources>
found associated type <G as piston_window::Graphics>::Texture
note: required by a bound in piston_window::Text::draw
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\text.rs:76:21
|
66 | pub fn draw<C, G>(
| ---- required by a bound in this associated function
...
76 | G: Graphics<Texture = ::Texture>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in Text::draw
help: consider constraining the associated type <G as piston_window::Graphics>::Texture to Texture<gfx_device_gl::Resources>
|
34 | fn draw<G: Graphics<Texture = Texture<gfx_device_gl::Resources>>>(&self, c: Context, g: &mut G, glyphs: &mut Glyphs) {
| +++++++++++++++++++++++++++++++++++++++++++++
error[E0271]: type mismatch resolving <G as Graphics>::Texture == Texture<Resources>
--> src\main.rs:136:84
|
136 | text_obj.draw(label, glyphs, &DrawState::default(), c.transform.trans(tx, ty), g).ok();
| ---- required by a bound introduced by this call ^ expected
Texture<Resources>, found associated type
|
= note: expected struct Texture<gfx_device_gl::Resources>
found associated type <G as piston_window::Graphics>::Texture
note: required by a bound in piston_window::Text::draw
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\text.rs:76:21
|
66 | pub fn draw<C, G>(
| ---- required by a bound in this associated function
...
76 | G: Graphics<Texture = ::Texture>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in Text::draw
help: consider constraining the associated type <G as piston_window::Graphics>::Texture to Texture<gfx_device_gl::Resources>
|
120 | fn button<G: Graphics<Texture = Texture<gfx_device_gl::Resources>>>(label: &str, rect: [f64;4], c: Context, g: &mut G, glyphs: &mut Glyphs, mouse_pos: [f64;2], mouse_pressed: bool) -> bool {
| +++++++++++++++++++++++++++++++++++++++++++++
error[E0308]: mismatched types
--> src\main.rs:184:46
|
184 | if tb.focused && tb.char_add(c) {
| -------- ^ expected char, found
| |
| arguments to this method are incorrect
|
note: method defined here
--> src\main.rs:70:8
|
70 | fn char_add(&mut self, c: char) -> bool {
| ^^^^^^^^ -------
if let Some(text) = e.text_args() {
for c in text.chars() {
for tb in &mut textboxes {
if tb.focused && tb.char_add(c) {
break;
}
}
}
}
User
修正後可運行完整版
Assistant
以下是以 piston_window 0.132.0 實作的完整範例,包含:
三個文字輸入框(TextBox),點擊會顯示虛線框取得焦點
可鍵盤輸入文字且支援 Backspace,Enter 失去焦點
兩個按鈕「Save」與「Load」,會將輸入框內容序列化成 JSON 儲存與讀取
使用 serde_json 做序列化
字型請自行放在專案的 assets 目錄下,預設名稱為 FiraSans-Regular.ttf
Cargo.toml
toml
[package]
name = "your_project"
version = "0.1.0"
edition = "2021"
[dependencies]
piston_window = "0.132.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
find_folder = "0.3"
main.rs
rust
User
error[E0271]: type mismatch resolving <G as Graphics>::Texture == Texture<Resources>
--> src\main.rs:145:84
|
145 | text_obj.draw(label, glyphs, &DrawState::default(), c.transform.trans(tx, ty), g).ok();
| ---- required by a bound introduced by this call ^ expected
Texture<Resources>, found associated type
|
= note: expected struct Texture<gfx_device_gl::Resources>
found associated type <G as piston_window::Graphics>::Texture
note: required by a bound in piston_window::Text::draw
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\text.rs:76:21
|
66 | pub fn draw<C, G>(
| ---- required by a bound in this associated function
...
76 | G: Graphics<Texture = ::Texture>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in Text::draw
help: consider constraining the associated type <G as piston_window::Graphics>::Texture to Texture<gfx_device_gl::Resources>
|
119 | fn button<G: Graphics<Texture = Texture<gfx_device_gl::Resources>>>(
| +++++++++++++++++++++++++++++++++++++++++++++
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:226:15
|
226 | e.draw_2d().unwrap().0,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:227:15
|
227 | e.draw_2d().unwrap().1,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:245:15
|
245 | e.draw_2d().unwrap().0,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:246:15
|
246 | e.draw_2d().unwrap().1,
| ^^^^^^^ method not found in Event
Some errors have detailed explanations: E0271, E0599.
For more information about an error, try rustc --explain E0271.
error: could not compile my_project (bin "my_project") due to 5 previous errors
Assistant
你遇到的錯誤主要有兩個:
1. Text::draw 的泛型約束錯誤 (Texture 相關)
錯誤訊息提到:
code
expected struct `Texture<gfx_device_gl::Resources>`, found associated type `<G as piston_window::Graphics>::Texture`
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0432]: unresolved import piston_window::KeyboardEvent
--> src\main.rs:24:69
|
24 | use piston_window::{PressEvent, ReleaseEvent, MouseCursorEvent, KeyboardEvent};
| ^^^^^^^^^^^^^ no KeyboardEvent in the root
error[E0659]: Context is ambiguous
--> src\main.rs:15:21
|
15 | let mut imgui = Context::create();
| ^^^^^^^ ambiguous name
|
= note: ambiguous because of multiple glob imports of a name in the same module
note: Context could refer to the struct imported here
--> src\main.rs:1:5
|
1 | use piston_window::;
| ^^^^^^^^^^^^^^^^
= help: consider adding an explicit import of Context to disambiguate
note: Context could also refer to the struct imported here
--> src\main.rs:3:5
|
3 | use imgui::;
| ^^^^^^^^
= help: consider adding an explicit import of Context to disambiguate
error[E0659]: MouseButton is ambiguous
--> src\main.rs:32:35
|
32 | if let Some(Button::Mouse(MouseButton::Left)) = event.press_args() {
| ^^^^^^^^^^^ ambiguous name
|
= note: ambiguous because of multiple glob imports of a name in the same module
note: MouseButton could refer to the enum imported here
--> src\main.rs:1:5
|
1 | use piston_window::;
| ^^^^^^^^^^^^^^^^
= help: consider adding an explicit import of MouseButton to disambiguate
note: MouseButton could also refer to the enum imported here
--> src\main.rs:3:5
|
3 | use imgui::;
| ^^^^^^^^
= help: consider adding an explicit import of MouseButton to disambiguate
error[E0659]: MouseButton is ambiguous
--> src\main.rs:36:35
|
36 | if let Some(Button::Mouse(MouseButton::Left)) = event.release_args() {
| ^^^^^^^^^^^ ambiguous name
|
= note: ambiguous because of multiple glob imports of a name in the same module
note: MouseButton could refer to the enum imported here
--> src\main.rs:1:5
|
1 | use piston_window::;
| ^^^^^^^^^^^^^^^^
= help: consider adding an explicit import of MouseButton to disambiguate
note: MouseButton could also refer to the enum imported here
--> src\main.rs:3:5
|
3 | use imgui::;
| ^^^^^^^^
= help: consider adding an explicit import of MouseButton to disambiguate
error[E0659]: Key is ambiguous
--> src\main.rs:45:23
|
45 | if key == Key::Escape {
| ^^^ ambiguous name
|
= note: ambiguous because of multiple glob imports of a name in the same module
note: Key could refer to the enum imported here
--> src\main.rs:1:5
|
1 | use piston_window::;
| ^^^^^^^^
= help: consider adding an explicit import of to disambiguate
你同時 use piston_window::* 和 use imgui::*,兩者都有 Context、Key、MouseButton 等導致名稱不明確。
解決方法:
不使用glob import (*),改為明確指定使用到的型別與函式,如:
rust
use piston_window::{PistonWindow, WindowSettings, Button, MouseButton, Key, PressEvent, ReleaseEvent, MouseCursorEvent};
use imgui::{Context as ImguiContext, FontSource, Text, DrawState, Condition};
use imgui_opengl_renderer::Renderer;
let mut draggable = Draggable::new(50.0, 50.0, 100.0, 100.0);
while let Some(e) = window.next() {
if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
if let Some([x, y]) = e.mouse_cursor_args() {
draggable.mouse_press(x, y);
}
}
if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
draggable.mouse_release();
}
if let Some([x, y]) = e.mouse_cursor_args() {
draggable.mouse_move(x, y);
}
window.draw_2d(&e, |c, g, _device| {
clear([1.0; 4], g);
draggable.draw(c, g);
});
}
}
請修正為何不能拖曳藍色的方塊
error[E0433]: failed to resolve: use of undeclared type Draggable
--> src\main.rs:7:25
|
7 | let mut draggable = Draggable::new(50.0, 50.0, 100.0, 100.0);
| ^^^^^^^^^ use of undeclared type Draggable
Some errors have detailed explanations: E0412, E0425, E0433.
For more information about an error, try rustc --explain E0412.
error: could not compile my_project (bin "my_project") due to 8 previous errors
use piston_window::{
PistonWindow, WindowSettings, clear,
Button, MouseButton, Context, Graphics,
rectangle, line,
};
struct Draggable {
rect: [f64; 4], // 物件位置尺寸
dragging: bool,
drag_start: [f64; 2],
rect_start: [f64; 2],
selected: bool,
}
impl Draggable {
fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
Draggable {
rect: [x, y, w, h],
dragging: false,
drag_start: [0.0, 0.0],
rect_start: [x, y],
selected: false,
}
}
fn is_inside(&self, x: f64, y: f64) -> bool {
let [rx, ry, rw, rh] = self.rect;
x >= rx && x <= rx + rw && y >= ry && y <= ry + rh
}
fn mouse_press(&mut self, x: f64, y: f64) {
if self.is_inside(x, y) {
self.dragging = true;
self.selected = true;
self.drag_start = [x, y];
self.rect_start = [self.rect[0], self.rect[1]];
} else {
self.selected = false;
}
}
fn mouse_release(&mut self) {
self.dragging = false;
}
fn mouse_move(&mut self, x: f64, y: f64) {
if self.dragging {
let dx = x - self.drag_start[0];
let dy = y - self.drag_start[1];
self.rect[0] = self.rect_start[0] + dx;
self.rect[1] = self.rect_start[1] + dy;
}
}
fn draw<G: Graphics>(&self, c: Context, g: &mut G) {
rectangle([0.0, 0.5, 1.0, 1.0], self.rect, c.transform, g);
if self.selected {
draw_dashed_rect(self.rect, 5.0, 3.0, [1.0, 0.0, 0.0, 1.0], c, g);
}
}
}
fn draw_dashed_rect<G: Graphics>(
rect: [f64; 4],
dash_length: f64,
gap_length: f64,
color: [f32; 4],
context: Context,
g: &mut G,
) {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
draw_dashed_line(x, y, x + w, y, dash_length, gap_length, color, context, g);
draw_dashed_line(x + w, y, x + w, y + h, dash_length, gap_length, color, context, g);
draw_dashed_line(x + w, y + h, x, y + h, dash_length, gap_length, color, context, g);
draw_dashed_line(x, y + h, x, y, dash_length, gap_length, color, context, g);
}
fn draw_dashed_line<G: Graphics>(
x1: f64,
y1: f64,
x2: f64,
y2: f64,
dash_length: f64,
gap_length: f64,
color: [f32; 4],
context: Context,
g: &mut G,
) {
let dx = x2 - x1;
let dy = y2 - y1;
let length = ((dx * dx) + (dy * dy)).sqrt();
if length == 0.0 { return; }
let dir_x = dx / length;
let dir_y = dy / length;
let mut drawn_len = 0.0;
while drawn_len < length {
let start_x = x1 + dir_x * drawn_len;
let start_y = y1 + dir_y * drawn_len;
let seg_len = dash_length.min(length - drawn_len);
let end_x = start_x + dir_x * seg_len;
let end_y = start_y + dir_y * seg_len;
line(
color,
1.0,
[start_x, start_y, end_x, end_y],
context.transform,
g,
);
drawn_len += dash_length + gap_length;
}
}
fn main() {
let mut window: PistonWindow = WindowSettings::new("Dashed border select", [400, 400])
.exit_on_esc(true)
.build()
.unwrap();
let mut draggable = Draggable::new(50.0, 50.0, 100.0, 100.0);
while let Some(e) = window.next() {
if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_press(x, y);
}
}
if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
draggable.mouse_release();
}
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_move(x, y);
}
window.draw_2d(&e, |c, g, _device| {
clear([1.0; 4], g);
draggable.draw(c, g);
});
}
}
總結
請確保以下型別和函式都從 piston_window 套件引入。
只引入 use piston_window::*; 有時不保證全部型別會進來(視 IDE 行為及版本不同),建議明確列出。
error[E0599]: no method named mouse_cursor found for enum Event in the current scope
--> src\main.rs:138:33
|
138 | if let Some([x, y]) = e.mouse_cursor() {
| ^^^^^^^^^^^^
|
::: C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\pistoncore-input-1.0.1\src\mouse.rs:82:8
|
82 | fn mouse_cursor<U, F>(&self, f: F) -> Option
| ------------ the method is available for Event here
|
= help: items from traits can only be used if the trait is in scope
help: trait MouseCursorEvent which provides mouse_cursor is implemented but not in scope; perhaps you want to import it
|
1 + use piston_window::MouseCursorEvent;
|
help: there is a method mouse_cursor_args with a similar name
|
138 | if let Some([x, y]) = e.mouse_cursor_args() {
| +++++
For more information about this error, try rustc --explain E0599.
error: could not compile my_project (bin "my_project") due to 4 previous errors
use piston_window::{
PistonWindow, WindowSettings, clear,
Button, MouseButton, Context, Graphics,
rectangle, line,
PressEvent, ReleaseEvent, MouseCursorEvent,
};
struct Draggable {
rect: [f64; 4], // 物件位置尺寸
dragging: bool,
drag_start: [f64; 2],
rect_start: [f64; 2],
selected: bool,
}
impl Draggable {
fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
Draggable {
rect: [x, y, w, h],
dragging: false,
drag_start: [0.0, 0.0],
rect_start: [x, y],
selected: false,
}
}
fn is_inside(&self, x: f64, y: f64) -> bool {
let [rx, ry, rw, rh] = self.rect;
x >= rx && x <= rx + rw && y >= ry && y <= ry + rh
}
fn mouse_press(&mut self, x: f64, y: f64) {
if self.is_inside(x, y) {
self.dragging = true;
self.selected = true;
self.drag_start = [x, y];
self.rect_start = [self.rect[0], self.rect[1]];
} else {
self.selected = false;
}
}
fn mouse_release(&mut self) {
self.dragging = false;
}
fn mouse_move(&mut self, x: f64, y: f64) {
if self.dragging {
let dx = x - self.drag_start[0];
let dy = y - self.drag_start[1];
self.rect[0] = self.rect_start[0] + dx;
self.rect[1] = self.rect_start[1] + dy;
}
}
fn draw<G: Graphics>(&self, c: Context, g: &mut G) {
rectangle([0.0, 0.5, 1.0, 1.0], self.rect, c.transform, g);
if self.selected {
draw_dashed_rect(self.rect, 5.0, 3.0, [1.0, 0.0, 0.0, 1.0], c, g);
}
}
}
fn draw_dashed_rect<G: Graphics>(
rect: [f64; 4],
dash_length: f64,
gap_length: f64,
color: [f32; 4],
context: Context,
g: &mut G,
) {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
draw_dashed_line(x, y, x + w, y, dash_length, gap_length, color, context, g);
draw_dashed_line(x + w, y, x + w, y + h, dash_length, gap_length, color, context, g);
draw_dashed_line(x + w, y + h, x, y + h, dash_length, gap_length, color, context, g);
draw_dashed_line(x, y + h, x, y, dash_length, gap_length, color, context, g);
}
fn draw_dashed_line<G: Graphics>(
x1: f64,
y1: f64,
x2: f64,
y2: f64,
dash_length: f64,
gap_length: f64,
color: [f32; 4],
context: Context,
g: &mut G,
) {
let dx = x2 - x1;
let dy = y2 - y1;
let length = ((dx * dx) + (dy * dy)).sqrt();
if length == 0.0 { return; }
let dir_x = dx / length;
let dir_y = dy / length;
let mut drawn_len = 0.0;
while drawn_len < length {
let start_x = x1 + dir_x * drawn_len;
let start_y = y1 + dir_y * drawn_len;
let seg_len = dash_length.min(length - drawn_len);
let end_x = start_x + dir_x * seg_len;
let end_y = start_y + dir_y * seg_len;
line(
color,
1.0,
[start_x, start_y, end_x, end_y],
context.transform,
g,
);
drawn_len += dash_length + gap_length;
}
}
fn main() {
let mut window: PistonWindow = WindowSettings::new("Dashed border select", [400, 400])
.exit_on_esc(true)
.build()
.unwrap();
let mut draggable = Draggable::new(50.0, 50.0, 100.0, 100.0);
while let Some(e) = window.next() {
if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() {
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_press(x, y);
}
}
if let Some(Button::Mouse(MouseButton::Left)) = e.release_args() {
draggable.mouse_release();
}
if let Some([x, y]) = e.mouse_cursor() {
draggable.mouse_move(x, y);
}
window.draw_2d(&e, |c, g, _device| {
clear([1.0; 4], g);
draggable.draw(c, g);
});
}
}
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:213:15
|
213 | e.draw_2d().unwrap().0,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:214:15
|
214 | e.draw_2d().unwrap().1,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:233:15
|
233 | e.draw_2d().unwrap().0,
| ^^^^^^^ method not found in Event
error[E0599]: no method named draw_2d found for enum Event in the current scope
--> src\main.rs:234:15
|
234 | e.draw_2d().unwrap().1,
| ^^^^^^^ method not found in Event
Some errors have detailed explanations: E0271, E0308, E0599.
For more information about an error, try rustc --explain E0271.
error: could not compile my_project (bin "my_project") due to 7 previous errors
3. Event 沒有 draw_2d() 方法
draw_2d 是在 PistonWindow 物件上的方法,你不能拿一個事件 e 調用 draw_2d()。
;
| ^^^^^^^^^^^^^^^^
= help: consider adding an explicit import of Key to disambiguate
note: Key could also refer to the enum imported here
--> src\main.rs:3:5
|
3 | use imgui::
Key
warning: unused import: piston_window::texture::TextureSettings
--> src\main.rs:2:5
|
2 | use piston_window::texture::TextureSettings;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
error[E0599]: no function or associated item named create found for struct piston_window::Context in the current scope
--> src\main.rs:15:30
|
15 | let mut imgui = Context::create();
| ^^^^^^ function or associated item not found in Context
|
note: if you're trying to build a new piston_window::Context consider using one of the following associated functions:
piston_window::Context::new
piston_window::Context::new_viewport
piston_window::Context::new_abs
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\context.rs:24:5
|
24 | pub fn new() -> Context {
| ^^^^^^^^^^^^^^^^^^^^^^^
...
44 | pub fn new_viewport(viewport: Viewport) -> Context {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
65 | pub fn new_abs(w: Scalar, h: Scalar) -> Context {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0277]: expected a FnMut(&'static str) closure, found TextureContext<Factory, Resources, CommandBuffer>
--> src\main.rs:20:55
|
20 | let mut renderer = Renderer::new(&mut imgui, &mut texture_context);
| ------------- ^^^^^^^^^^^^^^^ expected an FnMut(&'static str) closure, found TextureContext<Factory, Resources, CommandBuffer>
| |
| required by a bound introduced by this call
|
= help: the trait FnMut(&'static str) is not implemented for TextureContext<Factory, Resources, CommandBuffer>
= note: required for &mut TextureContext<Factory, Resources, ...> to implement FnMut(&'static str)
note: required by a bound in Renderer::new
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\imgui-opengl-renderer-0.12.1\src\lib.rs:37:8
|
32 | pub fn new(
| --- required by a bound in this associated function
...
37 | F: FnMut(&'static str) -> *const ::std::os::raw::c_void
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in Renderer::new
= note: the full name for the type has been written to 'C:\Users\fer52\mynewcargo\my_project\target\debug\deps\my_project.long-type-16290177830720086569.txt'
= note: consider using --verbose to print the full type name to the console
error[E0277]: expected a FnOnce(&'static str) closure, found TextureContext<Factory, Resources, CommandBuffer>
--> src\main.rs:20:50
|
20 | let mut renderer = Renderer::new(&mut imgui, &mut texture_context);
| ------------- ^^^^^^^^^^^^^^^^^^^^ expected an FnOnce(&'static str) closure, found TextureContext<Factory, Resources, CommandBuffer>
| |
| required by a bound introduced by this call
|
= help: the trait FnOnce(&'static str) is not implemented for TextureContext<Factory, Resources, CommandBuffer>
note: required by a bound in Renderer::new
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\imgui-opengl-renderer-0.12.1\src\lib.rs:37:31
|
32 | pub fn new(
| --- required by a bound in this associated function
...
37 | F: FnMut(&'static str) -> *const ::std::os::raw::c_void
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in Renderer::new
= note: the full name for the type has been written to 'C:\Users\fer52\mynewcargo\my_project\target\debug\deps\my_project.long-type-16290177830720086569.txt'
= note: consider using --verbose to print the full type name to the console
error[E0061]: this method takes 1 argument but 2 arguments were supplied
--> src\main.rs:65:22
|
65 | renderer.render(ui.render(), g).expect("Rendering failed");
| ^^^^^^ - unexpected argument #2 of type &mut gfx_graphics::back_end::GfxGraphics<'_, gfx_device_gl::Resources, gfx_device_gl::command::CommandBuffer>
|
note: method defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\imgui-opengl-renderer-0.12.1\src\lib.rs:138:10
|
138 | pub fn render(
| ^^^^^^
help: remove the extra argument
|
65 - renderer.render(ui.render(), g).expect("Rendering failed");
65 + renderer.render(ui.render()).expect("Rendering failed");
|
error[E0599]: no method named expect found for unit type () in the current scope
--> src\main.rs:65:45
|
65 | renderer.render(ui.render(), g).expect("Rendering failed");
| ^^^^^^ method not found in ()
Some errors have detailed explanations: E0061, E0277, E0432, E0599, E0659.
For more information about an error, try rustc --explain E0061.
warning: my_project (bin "my_project") generated 1 warning
error: could not compile my_project (bin "my_project") due to 10 previous errors; 1 warning emitted
5. expect 用在 () 會錯誤
render() 傳回 (), 不能再用 .expect(".."),你直接呼叫即可。
修正後示範 (精簡版完整)
rust
use piston_window::{PistonWindow, WindowSettings, clear, Button, MouseButton, Key, PressEvent, ReleaseEvent, MouseCursorEvent};
use imgui::{Context as ImguiContext, FontSource, Text, DrawState, Condition};
use imgui_opengl_renderer::Renderer;
use std::time::Instant;
fn main() {
let mut window: PistonWindow = WindowSettings::new("Piston + Imgui example", [800, 600])
.exit_on_esc(true)
.build()
.expect("Failed to build PistonWindow");
let mut texture_context = window.create_texture_context();
let mut imgui = ImguiContext::create();
imgui.set_ini_filename(None);
imgui.fonts().add_font(&FontSource::DefaultFontData { config: None });
let mut renderer = Renderer::new(&mut imgui, |s| texture_context.get_proc_address(s));
let mut last_frame = Instant::now();
while let Some(event) = window.next() {
let now = Instant::now();
let delta_s = now.duration_since(last_frame).as_secs_f32();
last_frame = now;
imgui.io_mut().delta_time = delta_s;
if let Some(Button::Mouse(MouseButton::Left)) = event.press_args() {
imgui.io_mut().mouse_down[0] = true;
}
if let Some(Button::Mouse(MouseButton::Left)) = event.release_args() {
imgui.io_mut().mouse_down[0] = false;
}
if let Some(pos) = event.mouse_cursor_args() {
imgui.io_mut().mouse_pos = [pos[0], pos[1]];
}
if let Some(Button::Keyboard(key)) = event.press_args() {
if key == Key::Escape {
break;
}
// 這裡可擴充鍵盤事件對 imgui 鍵位映射
}
window.draw_2d(&event, |c, g, device| {
clear([0.2, 0.2, 0.2, 1.0], g);
let ui = imgui.frame();
ui.window("Hello from imgui + piston!")
.size([300.0, 100.0], Condition::FirstUseEver)
.build(|| {
ui.text("This is a simple integration example.");
if ui.button("Exit") {
std::process::exit(0);
}
});
renderer.render(ui.render());
texture_context.encoder.flush(device);
});
}
}