perovskite_client 0.0.4

Multiplayer voxel game written in Rust - Game client
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2023 drey7925
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

use std::time::{Duration, Instant};

use cgmath::vec3;
use perovskite_core::constants::permissions;
use perovskite_core::protocol::blocks::block_type_def::PhysicsInfo;
use perovskite_core::{block_id::BlockId, coordinates::PlayerPositionUpdate};

use perovskite_core::constants::items::default_item_interaction_rules;
use perovskite_core::coordinates::BlockCoordinate;

use line_drawing::WalkVoxels;
use perovskite_core::protocol::blocks::BlockTypeDef;
use perovskite_core::protocol::items::interaction_rule::DigBehavior;
use perovskite_core::protocol::items::ItemDef;
use rustc_hash::FxHashSet;

use super::physics::apply_aabox_transformation;
use super::{input::BoundAction, make_fallback_blockdef, ClientState, GameAction};

struct DigState {
    // 0.0 to 1.0
    progress: f64,
    // Coordinate being dug
    coord: BlockCoordinate,
    // Current block ID
    id: BlockId,
    item_dig_behavior: Option<DigBehavior>,
    // Current durability (of selected block) for scaled time
    base_durability: f64,
}

// Computes the block that the player is pointing at, tracks the progress of digging, etc.
pub(crate) struct ToolController {
    dig_progress: Option<DigState>,
    hover_block: Option<BlockId>,
    current_item: ItemDef,
    current_slot: u32,
    current_item_interacting_groups: Vec<Vec<String>>,
    fallback_blockdef: BlockTypeDef,
    can_dig_place: bool,
    can_tap_interact: bool,
    futile_dig_since: Option<Instant>,
}
impl ToolController {
    pub(crate) fn new() -> ToolController {
        ToolController {
            dig_progress: None,
            hover_block: None,
            current_item: default_item(),
            current_slot: 0,
            current_item_interacting_groups: get_dig_interacting_groups(&default_item()),
            fallback_blockdef: make_fallback_blockdef(),
            can_dig_place: false,
            can_tap_interact: false,
            futile_dig_since: None,
        }
    }

    pub(crate) fn update_permissions(&mut self, permissions: &[String]) {
        self.can_dig_place = permissions
            .iter()
            .any(|p| p.contains(permissions::DIG_PLACE));
        self.can_tap_interact = permissions
            .iter()
            .any(|p| p.contains(permissions::TAP_INTERACT));
    }

    // Update the current item
    pub(crate) fn update_item(
        &mut self,
        client_state: &ClientState,
        slot: u32,
        item: Option<ItemDef>,
    ) {
        let item = item.unwrap_or(default_item());
        self.current_slot = slot;
        self.current_item_interacting_groups = get_dig_interacting_groups(&item);
        if let Some(progress) = &mut self.dig_progress {
            progress.item_dig_behavior = Self::compute_dig_behavior(
                &item,
                client_state.block_types.get_blockdef(progress.id).unwrap(),
            );
        }
        self.current_item = item;
    }

    // Compute a new selected block.
    pub(crate) fn update(&mut self, client_state: &ClientState, delta: Duration) -> ToolState {
        let player_pos = client_state.last_position();
        let (pointee, neighbor, block_def, block_id) =
            match self.compute_pointee(client_state, &player_pos) {
                Some(x) => x,
                None => {
                    // Ensure that we don't leave pending input events that fire when we finally do get a pointee
                    let mut input = client_state.input.lock();
                    input.take_just_pressed(BoundAction::Dig);
                    input.take_just_released(BoundAction::Dig);
                    input.take_just_pressed(BoundAction::Place);
                    input.take_just_pressed(BoundAction::Interact);
                    self.dig_progress = None;
                    self.hover_block = None;
                    return ToolState {
                        pointee: None,
                        neighbor: None,
                        action: None,
                    };
                }
            };
        let mut action = None;

        let mut input = client_state.input.lock();

        if input.is_pressed(BoundAction::Dig) && self.can_dig_place {
            if self.dig_progress.as_ref().map_or(true, |x: &DigState| {
                x.coord != pointee || !x.id.equals_ignore_variant(BlockId(block_def.id))
            }) {
                // The pointee changed
                let behavior = Self::compute_dig_behavior(&self.current_item, block_def);
                if let Some(DigBehavior::InstantDig(_)) = behavior {
                    // Only do this when the pointee changes
                    action = Some(GameAction::Dig(super::DigTapAction {
                        target: pointee,
                        prev: neighbor,
                        item_slot: self.current_slot,
                        player_pos,
                    }));
                }
                self.dig_progress = behavior.map(|behavior| DigState {
                    progress: 0.,
                    coord: pointee,
                    id: BlockId(block_def.id),
                    item_dig_behavior: Some(behavior),
                    base_durability: block_def.base_dig_time,
                });
            } else if let Some(dig_progress) = &mut self.dig_progress {
                // The pointee is the same, update dig progress
                let delta_progress = match dig_progress.item_dig_behavior {
                    None => 0.,
                    Some(DigBehavior::InstantDig(_)) => 0.,
                    Some(DigBehavior::InstantDigOneshot(_)) => {
                        if input.take_just_pressed(BoundAction::Dig) {
                            action = Some(GameAction::Dig(super::DigTapAction {
                                target: pointee,
                                prev: neighbor,
                                item_slot: self.current_slot,
                                player_pos,
                            }));
                        }
                        0.
                    }
                    Some(DigBehavior::ConstantTime(dig_seconds)) => {
                        delta.as_secs_f64() / dig_seconds
                    }
                    Some(DigBehavior::ScaledTime(scale)) => {
                        delta.as_secs_f64() / (scale * dig_progress.base_durability)
                    }
                    Some(DigBehavior::Undiggable(_)) => 0.,
                };

                dig_progress.progress += delta_progress;
                if dig_progress.progress >= 1.0 {
                    // Lock out digging until progress is reset by changing the pointee or pointed-to blockid
                    dig_progress.progress = f64::NEG_INFINITY;
                    action = Some(GameAction::Dig(super::DigTapAction {
                        target: pointee,
                        prev: neighbor,
                        item_slot: self.current_slot,
                        player_pos,
                    }));
                }
            }
        } else {
            self.dig_progress = None;
        }

        if input.take_just_released(BoundAction::Dig) && self.can_tap_interact {
            action = Some(GameAction::Tap(super::DigTapAction {
                target: pointee,
                prev: neighbor,
                item_slot: self.current_slot,
                player_pos,
            }))
        } else if input.take_just_pressed(BoundAction::Place)
            && neighbor.is_some()
            && self.can_dig_place
        {
            action = Some(GameAction::Place(super::PlaceAction {
                target: neighbor.unwrap(),
                anchor: Some(pointee),
                item_slot: self.current_slot,
                player_pos,
            }))
        } else if input.take_just_pressed(BoundAction::Interact) && self.can_tap_interact {
            action = Some(GameAction::InteractKey(super::InteractKeyAction {
                target: pointee,
                item_slot: self.current_slot,
                player_pos,
            }))
        }

        if !self.can_dig_place {
            if input.peek_just_pressed(BoundAction::Dig) {
                self.futile_dig_since = Some(Instant::now());
            } else if !input.is_pressed(BoundAction::Dig) {
                self.futile_dig_since = None;
            }
            if self.futile_dig_since.map_or(false, |x: Instant| {
                x.elapsed() > Duration::from_secs_f64(0.5)
            }) {
                self.futile_dig_since = None;
                client_state
                    .chat
                    .lock()
                    .show_client_message("You don't have permission to dig".to_string());
            }
            if input.peek_just_pressed(BoundAction::Place) {
                client_state
                    .chat
                    .lock()
                    .show_client_message("You don't have permission to place".to_string());
            }
        }

        if let Some(action) = &action {
            log::info!("Sending player action: {:?}", action);
        }

        self.hover_block = Some(block_id);

        ToolState {
            pointee: Some(pointee),
            neighbor,
            action,
        }
    }

    pub(crate) fn pointee_block_id(&self) -> Option<BlockId> {
        self.hover_block
    }

    fn compute_dig_behavior(item: &ItemDef, block_def: &BlockTypeDef) -> Option<DigBehavior> {
        let block_groups = block_def.groups.iter().collect::<FxHashSet<_>>();
        for rule in item.interaction_rules.iter() {
            if rule.block_group.iter().all(|x| block_groups.contains(x)) {
                return rule.dig_behavior.clone();
            }
        }
        None
    }

    fn compute_pointee<'a>(
        &'a self,
        client_state: &'a ClientState,
        last_pos: &PlayerPositionUpdate,
    ) -> Option<(
        BlockCoordinate,
        Option<BlockCoordinate>,
        &'a BlockTypeDef,
        BlockId,
    )> {
        // TODO handle custom collision boxes
        let pos = last_pos.position;
        let end = pos + (POINTEE_DISTANCE * last_pos.face_unit_vector());

        let delta_inv = vec3(
            1.0 / (end.x - pos.x),
            1.0 / (end.y - pos.y),
            1.0 / (end.z - pos.z),
        );

        let chunks = client_state.chunks.read_lock();
        let mut prev = None;
        let start_pos = match (pos + RAYCAST_FUDGE_VEC).try_into() {
            Ok(x) => x,
            Err(_) => {
                log::error!("pos: {pos:?} corrupt");
                return None;
            }
        };
        let end_pos = match (end + RAYCAST_FUDGE_VEC).try_into() {
            Ok(x) => x,
            Err(_) => {
                log::error!("end: {end:?} corrupt");
                return None;
            }
        };

        for (x, y, z) in
            WalkVoxels::<f64, i64>::new(start_pos, end_pos, &line_drawing::VoxelOrigin::Corner)
        {
            let coord = BlockCoordinate {
                x: x.try_into().ok()?,
                y: y.try_into().ok()?,
                z: z.try_into().ok()?,
            };
            let chunk = chunks.get(&coord.chunk());
            if let Some(chunk) = chunk {
                let id = chunk.get_single(coord.offset());
                let block_def = client_state
                    .block_types
                    .get_blockdef(id)
                    .unwrap_or(&self.fallback_blockdef);
                if check_intersection(
                    vec3(coord.x as f64, coord.y as f64, coord.z as f64),
                    block_def,
                    pos,
                    delta_inv,
                    id.variant(),
                ) {
                    for rule in self.current_item_interacting_groups.iter() {
                        if rule.iter().all(|x| block_def.groups.contains(x)) {
                            return Some((coord, prev, block_def, id));
                        }
                    }
                }
                prev = Some(coord);
            }
        }
        None
    }
}

fn check_intersection(
    block_coord: cgmath::Vector3<f64>,
    block_def: &BlockTypeDef,
    pos: cgmath::Vector3<f64>,
    delta_inv: cgmath::Vector3<f64>,
    variant: u16,
) -> bool {
    match &block_def.physics_info {
        Some(PhysicsInfo::SolidCustomCollisionboxes(boxes)) => boxes.boxes.iter().any(|aa_box| {
            if aa_box.variant_mask != 0 && aa_box.variant_mask & variant as u32 == 0 {
                return false;
            }

            let (min, max) = apply_aabox_transformation(aa_box, block_coord, variant);

            let tx1 = (min.x - pos.x) * delta_inv.x;
            let tx2 = (max.x - pos.x) * delta_inv.x;

            let t_min = tx1.min(tx2);
            let t_max = tx1.max(tx2);

            let ty1 = (min.y - pos.y) * delta_inv.y;
            let ty2 = (max.y - pos.y) * delta_inv.y;

            let t_min = t_min.max(ty1.min(ty2));
            let t_max = t_max.min(ty1.max(ty2));

            let tz1 = (min.z - pos.z) * delta_inv.z;
            let tz2 = (max.z - pos.z) * delta_inv.z;

            let t_min = t_min.max(tz1.min(tz2));
            let t_max = t_max.min(tz1.max(tz2));

            t_max >= t_min && t_max >= 0.
        }),
        _ => true,
    }
}

fn get_dig_interacting_groups(item: &ItemDef) -> Vec<Vec<String>> {
    let mut result = vec![];
    for rule in &item.interaction_rules {
        if rule.dig_behavior.is_some() {
            result.push(rule.block_group.clone())
        }
    }
    result
}

fn default_item() -> ItemDef {
    let rules = default_item_interaction_rules();
    ItemDef {
        short_name: String::new(),
        display_name: String::new(),
        inventory_texture: None,
        groups: vec![],
        interaction_rules: rules,
        quantity_type: None,
        block_apperance: "".to_string(),
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ToolState {
    // The block being pointed at
    pub(crate) pointee: Option<BlockCoordinate>,
    // The previous block coordinate, where we would place a block
    // if the place button were pressed
    pub(crate) neighbor: Option<BlockCoordinate>,
    // The action taken during this frame
    pub(crate) action: Option<GameAction>,
}

const POINTEE_DISTANCE: f64 = 6.;
// line_drawing seems to have problems when using Center rather than Corner
// Fudge it manually
// TODO file a bug for that crate
const RAYCAST_FUDGE_VEC: cgmath::Vector3<f64> = cgmath::vec3(0.5, 0.5, 0.5);