Git Product home page Git Product logo

Comments (6)

git2013vb avatar git2013vb commented on August 10, 2024 1

Thank you for your suggestions. In effect was too advanced for me to came up with that solution :)

Now I have to digest all of it :). Ill take some time I guess.

Thank you again:)

from message-io.

lemunozm avatar lemunozm commented on August 10, 2024

Hi @git2013vb,

The Endpoint implements both, Copy and Clone traits so you should be able to copy/clone it.

Maybe you can share a minor example (it is not necessary that it compiles) to see the structure of your code and to know exactly what is happening.

from message-io.

git2013vb avatar git2013vb commented on August 10, 2024

Sure :)
I have a workspace where inside I have: server , client, my_lib.
Currently the problem is in the client because I haven't done anything in server.
First of all the error (main.rs in client workspace)

error[E0382]: assign to part of moved value: `client.client_network`
   --> client/src/main.rs:100:9
    |
100 |         client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------------^^^^^^^^^^^
    |         |                                                                 |
    |         |                                                                 value moved here
    |         value partially assigned here after move
    |
    = note: move occurs because `client.client_network` has type `desert_edge_lib::network::Network`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `client.client_network`
   --> client/src/main.rs:107:20
    |
98  |       thread::spawn(|| {
    |                     -- value moved into closure here
99  |           // connect to server
100 |           client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    |                                                                             --------------------- variable moved due to use in closure
...
107 |       event_loop.run(move |event, _, control_flow| {
    |  ____________________^
108 | |         match event {
109 | |             Event::MainEventsCleared => {
110 | |                 // This main game loop - it has fixed time step which means that game
...   |
217 | |         }
218 | |     });
    | |_____^ value used here after move
    |
    = note: move occurs because `client.client_network` has type `desert_edge_lib::network::Network`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0382`.

then its code:

struct Client {
    login_screen: LoginScreen,
    client_network: Network,
    // tcp_stream: Result<TcpStream, eyre::Report>,
    is_exit: bool,
}
impl Client {
    fn new(engine: &mut Engine) -> Self {
        let (signal_handler, signal_listener) = node::split::<Signal>();
        Self {
            client_network: Network {
                signal_handler,
                signal_listener,
                client_endpoint:None,
                // client_listener: ClientListener {
                //     endpoint: Endpoint::from_listener(resource_id, addr),
                //     socket_address,
                // },
            },
            login_screen: LoginScreen::new(engine, P_400X350),
            is_exit: false,
        }
    }
}
fn main() {
    tracing_subscriber::registry().with(LogLayer).init();
    Log::set_verbosity(MessageKind::Warning); // remove [INFO] messages from Fyrox
                                              // rust_i18n::set_locale("it");
    trace!("{}", LOG_START);
    //================================
    let event_loop = EventLoop::new();
    // Create window builder first.
    let window_builder = WindowBuilder::new()
        .with_title("DesertEdge")
        .with_resizable(true);

    let serialization_context = Arc::new(SerializationContext::new());
    let mut engine = Engine::new(EngineInitParams {
        window_builder,
        resource_manager: ResourceManager::new(serialization_context.clone()),
        serialization_context,
        events_loop: &event_loop,
        vsync: true,
    })
    .unwrap();

    let mut client = Client::new(&mut engine);

    // Define game loop variables.
    let clock = Instant::now();
    let fixed_timestep = 1.0 / 60.0;
    let mut elapsed_time = 0.0;
    thread::spawn(|| {
        // connect to server
        client.client_network.client_endpoint = Some(connection_to_server(client.client_network).endpoint);
    });

    // Finally run our event loop which will respond to OS and window events and update
    // engine state accordingly. Engine lets you to decide which event should be handled,
    // this is minimal working example if how it should be.

    event_loop.run(move |event, _, control_flow| {
        match event {
            Event::MainEventsCleared => {
                // This main game loop - it has fixed time step which means that game
                // code will run at fixed speed even if renderer can't give you desired
                // 60 fps.
                let mut dt = clock.elapsed().as_secs_f32() - elapsed_time;
                while dt >= fixed_timestep {
                    dt -= fixed_timestep;
                    elapsed_time += fixed_timestep;

                    // ************************
                    // ************************
                    // Put your game logic here.
                    // ************************
                    // ************************
                    if client.is_exit {
                        *control_flow = ControlFlow::Exit;
                    }

                    // It is very important to update the engine every frame!
                    engine.update(fixed_timestep);
                }

                // It is very important to "pump" messages from UI. Even if don't need to
                // respond to such message, you should call this method, otherwise UI
                // might behave very weird.
                while let Some(message) = engine.user_interface.poll_message() {
                    // ************************
                    // ************************
                    // Put your data model synchronization code here. It should
                    // take message and update data in your game according to
                    // changes in UI.
                    // ************************
                    // ************************
                    match message.data() {
                        Some(ButtonMessage::Click) => {
                            if message.destination() == client.login_screen.quit_button_handle {
                                // network::close_connection(&self);
                                trace!("Used exit button to close");
                                log_quit();
                                client.is_exit = true
                            }
                            if message.destination() == client.login_screen.login_button_handle {
                                info!("Login Pressed");
                                let data = b"hello world";
                                // let endpoint = client.client_network.signal_handler.network();
                                // client.client_network.signal_handler.network().send(
                                //     client.client_network.client_listener.endpoint,
                                //     data,
                                // );
                                &client
                                    .client_network
                                    .signal_handler
                                    .network()
                                    .send(client.client_network.client_endpoint.unwrap(), data);
                            }
                        }
                        _ => (),
                    }
                }

                // Rendering must be explicitly requested and handled after RedrawRequested event is received.
                engine.get_window().request_redraw();
            }
            Event::RedrawRequested(_) => {
                // Run renderer at max speed - it is not tied to game code.
                engine.render().unwrap();
            }
            Event::WindowEvent { event, .. } => {
                match event {
                    WindowEvent::CloseRequested => {
                        log_quit();
                        *control_flow = ControlFlow::Exit
                    }
                    WindowEvent::Resized(size) => {
                        // It is very important to handle Resized event from window, because
                        // renderer knows nothing about window size - it must be notified
                        // directly when window size has changed.
                        if let Err(e) = engine.set_frame_size(size.into()) {
                            Log::writeln(
                                MessageKind::Error,
                                format!("Unable to set frame size: {:?}", e),
                            );
                        }
                        // engine.user_interface.send_message(WidgetMessage::width(
                        //     self.client_main_screen.grid_handle,
                        //     MessageDirection::ToWidget,
                        //     size.width as f32,
                        // ));
                        // engine.user_interface.send_message(WidgetMessage::height(
                        //     self.client_main_screen.grid_handle,
                        //     MessageDirection::ToWidget,
                        //     size.height as f32,
                        // ));
                        debug!("Resized");
                    }
                    // Handle rest of events here if necessary.
                    _ => (),
                }

                // It is very important to "feed" user interface (UI) with events coming
                // from main window, otherwise UI won't respond to mouse, keyboard, or any
                // other event.
                if let Some(os_event) = translate_event(&event) {
                    engine.user_interface.process_os_event(&os_event);
                }
            }
            // Continue polling messages from OS.
            _ => *control_flow = ControlFlow::Poll,
        }
    });
    // old way .....
    // let framework_game = Framework::<Game>::new()?;
    // let framework_game = framework_game.title("DesertEdge");
    // framework_game.run();
}
pub fn log_quit() {
    trace!("{}", LOG_QUIT);
}

Then the Network struct (in my lib in the same workspace ./network/mod.rs):

pub struct Network {
    pub signal_handler: NodeHandler<Signal>,
    pub signal_listener: NodeListener<Signal>,
    pub client_endpoint: Option<Endpoint>,
}

Then the fn where I use to connect to the server(./network/mod.rs):

pub fn connection_to_server(client_network: Network) -> ClientListener {
    debug!("connection to server");
    let transport = Transport::Tcp;
    let remote_addr = (String::from("127.0.0.1:10000")).to_remote_addr().unwrap();
    let (endpoint, socket_address) = client_network
        .signal_handler
        .network()
        .connect(transport, remote_addr.clone())
        .unwrap();
    client_network
        .signal_listener
        .for_each(move |node_event| match node_event {
            NodeEvent::Network(net_event) => match net_event {
                NetEvent::Accepted(_, _) => unreachable!(), // Only generated when a listener accepts
                NetEvent::Connected(_, established) => {
                    if established {
                        trace!(
                            "Connected to server at {} by {}",
                            endpoint.addr(),
                            transport
                        );
                        info!("Client identified by local port: {}", socket_address.port());
                        client_network.signal_handler.signals().send(Signal::Greet);
                        info!("Sent Greet");
                    } else {
                        trace!(
                            "Can not connect to server at {} by {}",
                            socket_address,
                            transport
                        )
                    }
                }
                NetEvent::Message(_, input_data) => {
                    let message: FromServerMessage = bincode::deserialize(&input_data).unwrap();
                    match message {
                        FromServerMessage::Pong(count) => {
                            println!("Pong from server: {} times", count)
                        }
                        FromServerMessage::UnknownPong => println!("Pong from server"),
                    }
                }
                NetEvent::Disconnected(_) => {
                    trace!("Server is disconnected");
                    client_network.signal_handler.stop();
                }
            },
            NodeEvent::Signal(signal) => match signal {
                Signal::Greet => {
                    let message: FromClientMessage = FromClientMessage::Ping;
                    let output_data = bincode::serialize(&message).unwrap();
                    client_network
                        .signal_handler
                        .network()
                        .send(endpoint, &output_data);
                    // client_network_handler
                    //     .signals()
                    //     .send_with_timer(Signal::Greet, Duration::from_secs(1));
                }
            },
        });
    ClientListener {
        endpoint,
        socket_address,
    }
}

The game engine is Fyrox
I tried to set #[derive(Clone)] in Network struct but after that he error switched to the Enpoint.


   --> desert_edge_lib/src/network/mod.rs:20:5
    |
17  | #[derive(Clone)]
    |          ----- in this derive macro expansion
...
20  |     pub signal_listener: NodeListener<Signal>,
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `NodeListener<network::Signal>`
    |
note: required by `clone`
   --> /home/vale/.rustup/toolchains/1.57.0-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/clone.rs:122:5
    |
122 |     fn clone(&self) -> Self;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^
    = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.

I think I posted all the code related the error. Let me know if I miss something.
Thanks :)

from message-io.

git2013vb avatar git2013vb commented on August 10, 2024

I re read my issue and probably I have to write NodeListener Instead of point out the problem to the Endpoint I'm not 100% sure, because I did a lot of try and repeat in my code :).

from message-io.

lemunozm avatar lemunozm commented on August 10, 2024

Hi, If I have seen it well, you're trying to move the Network struct you have created into two different closures. This struct is neither copy nor clone, this is the reason you are getting the error.

Looking in detail, the GUI closure is not using the NodeListener for anything, so that instance should be only moved to the first spawned thread. The NodeHandler is clonable and you can send two instances to the closures. Regarding the endpoint, if you want to write its value and then read it from the other closure, I would wrap it into an Arc<Mutex<Option<Endpoint>>>. In that way, you can share the value among the threads/closures.

from message-io.

lemunozm avatar lemunozm commented on August 10, 2024

I close the issue. Feel free to reopen it if needed.

from message-io.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.