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
#[macro_use]
extern crate lazy_static;

extern crate byteorder;
extern crate crypto;

mod crc;
mod encrypt;
mod error;
#[macro_use]
mod version;
mod coordinate;

pub mod ack;
pub mod command;
pub mod frame;
pub mod header;
pub mod types;

pub use error::{Error, Result};

use types::Position;
pub use version::{Platform, sdk};

pub fn keygen(data: &str) -> Result<Vec<u8>> {
    let data = data.as_bytes();
    let mut v = Vec::new();
    let mut temp_area = [0u8; 2];

    if data.len() != 64 {
        return Err(Error::Key("key length should be 64 bytes"));
    }

    for i in 0..32 {
        let d = &data[i * 2..];

        temp_area[0] = d[0];
        temp_area[1] = d[1];
        let area = try!(::std::str::from_utf8(&temp_area).map_err(|_| Error::Key("invalid utf8")));
        v.push(try!(u8::from_str_radix(&area, 16).map_err(|_| Error::Key("invalid hex string"))));
    }
    Ok(v)
}

pub fn compute_damping(points: &[Position], size: f64) -> Vec<f64> {
    let mut dampings = Vec::with_capacity(points.len());

    const MIN_DAMPING: f64 = 0.2;
    const MAX_DAMPING: f64 = 1e3;

    if points.is_empty() {
        return dampings;
    }

    dampings.push(MIN_DAMPING);

    if points.len() == 1 {
        return dampings;
    }

    let mut damping = MIN_DAMPING;

    for (i, win) in points.windows(3).enumerate() {
        let (p, c, n) = (win[0], win[1], win[2]);

        let prev_distance = c.distance(p);
        let next_distance = c.distance(n);

        let mut temp_prev = prev_distance;
        if i > 0 {
            temp_prev -= damping;
        }
        let mut temp_next = next_distance;
        if i < points.len() - 3 {
            temp_next -= MIN_DAMPING;
        }

        let max_damping = MAX_DAMPING.min(MIN_DAMPING.max(temp_prev.min(temp_next) - 1.0));
        temp_prev = temp_prev.min(prev_distance / 2.0);
        let j = temp_prev.min(next_distance / 2.0) * size;
        damping = max_damping.min(MIN_DAMPING.max(MAX_DAMPING.min(j)));
        dampings.push(damping);
    }

    dampings.push(MIN_DAMPING);
    dampings
}