summaryrefslogtreecommitdiff
path: root/world/src/main.rs
blob: 30fe8d47e9d4b936c611bbdad8f988a46bdbdf06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
    wearechat - generic multiplayer game with voip
    Copyright (C) 2025 metamuffin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#![feature(iter_array_chunks)]
pub mod mesh;

use anyhow::{Result, bail};
use clap::Parser;
use gltf::image::Source;
use image::{ImageReader, codecs::webp::WebPEncoder};
use log::info;
use mesh::import_mesh;
use rand::random;
use std::{
    fs::File,
    io::{Cursor, Read, Write},
    net::{SocketAddr, TcpStream},
    path::{Path, PathBuf},
    thread::{self, sleep},
    time::Duration,
};
use weareshared::{
    Vec3A,
    helper::ReadWrite,
    packets::{Data, Object, Packet, Resource},
    resources::{EnvironmentPart, Image, LightPart, Prefab},
    store::ResourceStore,
    vec3a,
};

#[derive(Parser)]
struct Args {
    address: SocketAddr,
    /// Path to a glTF file, binary or json format
    scene: PathBuf,
    /// Send all resources to the server then quit
    #[arg(short, long)]
    push: bool,
    /// Spin the object
    #[arg(short, long)]
    spin: bool,
    /// Remove all other object from the world
    #[arg(short, long)]
    clear: bool,
    /// Add the object to the world
    #[arg(short, long)]
    add: bool,
    /// Transcode all textures to WebP
    #[arg(short, long)]
    webp: bool,
    /// Register to the prefab index
    #[arg(short, long)]
    name: Option<String>,
    /// Add skybox
    #[arg(short, long)]
    skybox: Option<PathBuf>,
}

fn main() -> Result<()> {
    env_logger::init_from_env("LOG");
    let args = Args::parse();

    let mut sock = TcpStream::connect(args.address)?;
    let store = ResourceStore::new_memory();

    Packet::Connect(random()).write(&mut sock)?;

    let (gltf, buffers, _) = gltf::import(&args.scene)?;
    let path_base = args.scene.parent().unwrap();

    let mut prefab = Prefab::default();
    for node in gltf.nodes() {
        if let Some(mesh) = node.mesh() {
            import_mesh(
                mesh,
                &buffers,
                &store,
                path_base,
                &node,
                &mut prefab,
                args.webp,
            )?;
        }
        let (position, _, _) = node.transform().decomposed();
        if let Some(light) = node.light() {
            let emission = Some(Vec3A::from_array(light.color()) * light.intensity());
            prefab.light.push((
                Vec3A::from_array(position),
                store.set(&LightPart {
                    emission,
                    ..Default::default()
                })?,
            ));
        }
    }

    if let Some(skybox) = args.skybox {
        let mut buf = Vec::new();
        File::open(skybox)?.read_to_end(&mut buf)?;
        prefab.environment = Some(store.set(&EnvironmentPart {
            skybox: Some(store.set(&Image(buf))?),
            ..Default::default()
        })?);
    }

    let pres = store.set(&prefab)?;

    if let Some(name) = args.name {
        Packet::PrefabName(pres.clone(), name).write(&mut sock)?;
        sock.flush()?;
    }
    let ob = if args.add {
        let ob = Object::new();
        Packet::Add(ob, pres.clone()).write(&mut sock)?;
        sock.flush()?;
        Some(ob)
    } else {
        None
    };

    if args.spin {
        let ob = ob.clone().unwrap();
        let mut sock2 = sock.try_clone().unwrap();
        thread::spawn(move || {
            let mut x = 0.;
            loop {
                Packet::Position(ob, Vec3A::ZERO, vec3a(x, x * 0.3, x * 0.1))
                    .write(&mut sock2)
                    .unwrap();
                sock2.flush().unwrap();
                x += 0.1;
                sleep(Duration::from_millis(50));
            }
        });
    }

    if args.push {
        store.iter(|d| {
            Packet::RespondResource(Data(d.to_vec()))
                .write(&mut sock)
                .unwrap();
        })?;
        sock.flush()?;
    } else {
        loop {
            let packet = Packet::read(&mut sock)?;
            match packet {
                Packet::RequestResource(hash) => {
                    if let Some(d) = store.get_raw(hash)? {
                        Packet::RespondResource(Data(d)).write(&mut sock)?;
                        sock.flush()?;
                    }
                }
                Packet::Add(ob_a, _) => {
                    if Some(ob_a) != ob {
                        info!("removing object {ob_a}");
                        Packet::Remove(ob_a).write(&mut sock)?;
                        sock.flush()?;
                    }
                }
                _ => (),
            }
        }
    }
    Ok(())
}

fn load_texture(
    name: &str,
    store: &ResourceStore,
    path: &Path,
    buffers: &[gltf::buffer::Data],
    source: &Source,
    webp: bool,
) -> Result<Resource<Image>> {
    let mut image = match source {
        gltf::image::Source::View { view, mime_type } => {
            info!("{name} texture is embedded and of type {mime_type:?}");
            let buf =
                &buffers[view.buffer().index()].0[view.offset()..view.offset() + view.length()];
            Image(buf.to_vec())
        }
        gltf::image::Source::Uri {
            uri,
            mime_type: Some(mime_type),
        } => {
            info!("{name} texture is {uri:?} and of type {mime_type:?}");
            let path = path.join(uri);
            let mut buf = Vec::new();
            File::open(path)?.read_to_end(&mut buf)?;
            Image(buf)
        }
        _ => {
            bail!("texture is external and has no mime type")
        }
    };

    if webp {
        let mut image_out = Image(Vec::new());

        let len = image.0.len();
        ImageReader::new(Cursor::new(image.0))
            .with_guessed_format()?
            .decode()?
            .write_with_encoder(WebPEncoder::new_lossless(&mut image_out.0))?;
        info!("webp encode: {len} -> {}", image_out.0.len());
        image = image_out;
    }
    Ok(store.set(&image)?)
}