<commit_before>use gl;
use std::os::raw::c_void;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

pub use glfw::{self, Action, Context, CursorMode, Key, MouseButton, Window};

pub type Keyboard = mpsc::Receiver<(Key, Action)>;
pub type Mouse = mpsc::Receiver<(MouseButton, Action)>;
pub type MouseMove = mpsc::Receiver<[f64; 2]>;
pub type Scroll = mpsc::Receiver<[f64; 2]>;

pub fn bootstrap<App: FnMut(u32, u32, Keyboard, Mouse, MouseMove, Scroll, Window)>(dim: Option<(u32, u32)>, title: &'static str, mut app: App) {
  let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

  // OpenGL hint
  glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
  glfw.window_hint(glfw::WindowHint::ContextVersionMajor(3));
  glfw.window_hint(glfw::WindowHint::ContextVersionMinor(3));

  let (mut window, events, w, h) = if let Some((w, h)) = dim {
    let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::Windowed)
      .expect("Failed to create GLFW window.");

    (window, events, w, h)
  } else {
    glfw.with_primary_monitor(|glfw, monitor| {
      let monitor = monitor.unwrap();
      let vmode = monitor.get_video_mode().expect("primary monitor’s video mode");
      let (w, h) = (vmode.width, vmode.height);
      let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");

      (window, events, w, h)
    })
  };

  window.make_current();

  if cfg!(feature = "release") {
    window.set_cursor_mode(CursorMode::Disabled);
  }

  window.set_key_polling(true);
  window.set_cursor_pos_polling(true);
  window.set_mouse_button_polling(true);
  window.set_scroll_polling(true);

  // init OpenGL
  gl::load_with(|s| window.get_proc_address(s) as *const c_void);

  info!("using resolution {}x{}", w, h);

  // create channels to stream keyboard and mouse events
  let (kbd_snd, kbd_rcv) = mpsc::channel();
  let (mouse_snd, mouse_rcv) = mpsc::channel();
  let (mouse_move_snd, mouse_move_rcv) = mpsc::channel();
  let (scroll_snd, scroll_rcv) = mpsc::channel();

  // start the event threads
  let _ = thread::spawn(move || {
    for (_, event) in glfw::flush_messages(&events) {
      glfw.poll_events();

      match event {
          glfw::WindowEvent::Key(key, _, action, _) => {
            let _ = kbd_snd.send((key, action));
          },
          glfw::WindowEvent::MouseButton(button, action, _) => {
            let _ = mouse_snd.send((button, action));
          },
          glfw::WindowEvent::CursorPos(x, y) => {
            let _ = mouse_move_snd.send([x, y]);
          },
          glfw::WindowEvent::Scroll(x, y) => {
            let _ = scroll_snd.send([x, y]);
          },
          _ => {},
      }

      thread::sleep(Duration::from_millis(100));
    }
  });

  app(w, h, kbd_rcv, mouse_rcv, mouse_move_rcv, scroll_rcv, window);
}
<commit_msg>Better interface.<commit_after>use gl;
use std::os::raw::c_void;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

pub use glfw::{self, Action, Context, CursorMode, Key, MouseButton, Window};

#[derive(Clone, Copy, Debug)]
pub enum LuminanceBackend {
  GL33
}

#[derive(Clone, Copy, Debug)]
pub enum WindowDim {
  Windowed(u32, u32),
  FullScreen,
  FullScreenRestricted(u32, u32)
}

pub type Keyboard = mpsc::Receiver<(Key, Action)>;
pub type Mouse = mpsc::Receiver<(MouseButton, Action)>;
pub type MouseMove = mpsc::Receiver<[f64; 2]>;
pub type Scroll = mpsc::Receiver<[f64; 2]>;

pub fn bootstrap<App: FnMut(u32, u32, Keyboard, Mouse, MouseMove, Scroll, Window)>(dim: WindowDim, title: &'static str, backend: LuminanceBackend, mut app: App) {
  let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

  match backend {
    LuminanceBackend::GL33 => {
      // OpenGL hints; implements luminance-gl’s core contexts creation
      glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
      glfw.window_hint(glfw::WindowHint::ContextVersionMajor(3));
      glfw.window_hint(glfw::WindowHint::ContextVersionMinor(3));
    }
  }

  // open a window in windowed or fullscreen mode
  let (mut window, events, w, h) = match dim {
    WindowDim::Windowed(w, h) => {
      let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::Windowed).expect("Failed to create GLFW window.");
      (window, events, w, h)
    },
    WindowDim::FullScreen => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();
        let vmode = monitor.get_video_mode().expect("primary monitor’s video mode");
        let (w, h) = (vmode.width, vmode.height);

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    },
    WindowDim::FullScreenRestricted(w, h) => {
      glfw.with_primary_monitor(|glfw, monitor| {
        let monitor = monitor.unwrap();

        let (window, events) = glfw.create_window(w, h, title, glfw::WindowMode::FullScreen(monitor)).expect("Failed to create GLFW window.");
        (window, events, w, h)
      })
    }
  };

  window.make_current();

  if cfg!(feature = "release") {
    window.set_cursor_mode(CursorMode::Disabled);
  }

  window.set_key_polling(true);
  window.set_cursor_pos_polling(true);
  window.set_mouse_button_polling(true);
  window.set_scroll_polling(true);

  // init OpenGL
  gl::load_with(|s| window.get_proc_address(s) as *const c_void);

  info!("using resolution {}x{}", w, h);

  // create channels to stream keyboard and mouse events
  let (kbd_snd, kbd_rcv) = mpsc::channel();
  let (mouse_snd, mouse_rcv) = mpsc::channel();
  let (mouse_move_snd, mouse_move_rcv) = mpsc::channel();
  let (scroll_snd, scroll_rcv) = mpsc::channel();

  // start the event threads
  let _ = thread::spawn(move || {
    for (_, event) in glfw::flush_messages(&events) {
      glfw.poll_events();

      match event {
          glfw::WindowEvent::Key(key, _, action, _) => {
            let _ = kbd_snd.send((key, action));
          },
          glfw::WindowEvent::MouseButton(button, action, _) => {
            let _ = mouse_snd.send((button, action));
          },
          glfw::WindowEvent::CursorPos(x, y) => {
            let _ = mouse_move_snd.send([x, y]);
          },
          glfw::WindowEvent::Scroll(x, y) => {
            let _ = scroll_snd.send([x, y]);
          },
          _ => {},
      }

      thread::sleep(Duration::from_millis(100));
    }
  });

  app(w, h, kbd_rcv, mouse_rcv, mouse_move_rcv, scroll_rcv, window);
}
<|endoftext|>


<commit_before>//
use std::rc::Rc;
use std::cell::RefCell;

//
use core::document::Document;
use core::screen::Screen;

use core::mark::Mark;

use core::codec::text::utf8;

pub type Id = u64;

// TODO: add the main mark as a ref
#[derive(Debug)]
pub struct View {
    pub id: Id,
    pub start_offset: u64,
    pub end_offset: u64,
    pub document: Option<Rc<RefCell<Document>>>,
    pub screen: Box<Screen>,

    // TODO: in future version marks will be stored in buffer meta data
    pub moving_marks: Rc<RefCell<Vec<Mark>>>,
    pub fixed_marks: Rc<RefCell<Vec<Mark>>>,
}

impl View {
    pub fn new(id: Id,
               start_offset: u64,
               width: usize,
               height: usize,
               document: Option<Rc<RefCell<Document>>>)
               -> View {

        let screen = Box::new(Screen::new(width, height));

        // TODO: in future version will be stored in buffer meta data
        let moving_marks = Rc::new(RefCell::new(vec![Mark { offset: 0 }]));

        View {
            id,
            start_offset,
            end_offset: start_offset, // will be recomputed later
            document,
            screen,
            moving_marks,
            fixed_marks: Rc::new(RefCell::new(Vec::new())),
        }
    }

    pub fn move_marks_backward(&mut self) {
        let doc = self.document.as_mut().unwrap().borrow_mut();

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            m.move_backward(&doc.buffer, utf8::get_previous_codepoint_start);
        }
    }

    pub fn move_marks_forward(&mut self) {

        let doc = self.document.as_mut().unwrap().borrow_mut();

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            m.move_forward(&doc.buffer, utf8::get_next_codepoint_start);
        }
    }

    pub fn move_marks_to_beginning_of_line(&mut self) {

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {

            if m.offset == 0 {
                continue;
            }

            let doc = self.document.as_mut().unwrap().borrow_mut();

            let start_offset = m.offset;
            let mut prev_offset = m.offset;
            loop {
                let (cp, offset, size) = utf8::get_prev_codepoint(&doc.buffer.data, prev_offset);
                if offset == 0 {
                    m.offset = 0;
                    break;
                }

                match cp {
                    '\n' => {
                        m.offset = offset + 1;

                        if prev_offset > 0 {
                            match utf8::get_prev_codepoint(&doc.buffer.data, prev_offset) {
                                ('\r', offset, _) => {
                                    m.offset = offset;
                                }
                                _ => {}
                            }
                        }
                        break;
                    }

                    '\r' => {
                        m.offset = offset + 1;
                        break;
                    }

                    _ => prev_offset = offset,
                }
            }
        }
    }

    pub fn move_marks_to_end_of_line(&mut self) {

        let doc = self.document.as_mut().unwrap().borrow_mut();
        let max_offset = doc.buffer.data.len() as u64;

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {

            let mut prev_offset = m.offset;

            loop {
                let (cp, mut offset, size) = utf8::get_codepoint(&doc.buffer.data, prev_offset);
                if prev_offset == max_offset {
                    break;
                }
                match cp {

                    '\r' => {
                        match utf8::get_codepoint(&doc.buffer.data, offset) {
                            ('\n', _, _) => {
                                offset += 1;
                            }
                            _ => {}
                        }
                        break;
                    }

                    '\n' => {
                        break;
                    }

                    _ => {}
                }
                prev_offset = offset + size as u64;
            }
            m.offset = prev_offset;
        }
    }
}
<commit_msg>update view api : add insert/remove functions<commit_after>//
use std::rc::Rc;
use std::cell::RefCell;

//
use core::document::Document;
use core::screen::Screen;

use core::mark::Mark;

use core::codec::text::utf8;

pub type Id = u64;

// TODO: add the main mark as a ref
#[derive(Debug)]
pub struct View {
    pub id: Id,
    pub start_offset: u64,
    pub end_offset: u64,
    pub document: Option<Rc<RefCell<Document>>>,
    pub screen: Box<Screen>,

    // TODO: in future version marks will be stored in buffer meta data
    pub moving_marks: Rc<RefCell<Vec<Mark>>>,
    pub fixed_marks: Rc<RefCell<Vec<Mark>>>,
}

impl View {
    pub fn new(id: Id,
               start_offset: u64,
               width: usize,
               height: usize,
               document: Option<Rc<RefCell<Document>>>)
               -> View {

        let screen = Box::new(Screen::new(width, height));

        // TODO: in future version will be stored in buffer meta data
        let moving_marks = Rc::new(RefCell::new(vec![Mark { offset: 0 }]));

        View {
            id,
            start_offset,
            end_offset: start_offset, // will be recomputed later
            document,
            screen,
            moving_marks,
            fixed_marks: Rc::new(RefCell::new(Vec::new())),
        }
    }

    pub fn move_marks_backward(&mut self) {
        let doc = self.document.as_mut().unwrap().borrow_mut();

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            m.move_backward(&doc.buffer, utf8::get_previous_codepoint_start);
        }
    }

    pub fn move_marks_forward(&mut self) {

        let doc = self.document.as_mut().unwrap().borrow_mut();

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            m.move_forward(&doc.buffer, utf8::get_next_codepoint_start);
        }
    }

    pub fn move_marks_to_beginning_of_line(&mut self) {

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {

            if m.offset == 0 {
                continue;
            }

            let doc = self.document.as_mut().unwrap().borrow_mut();

            let start_offset = m.offset;
            let mut prev_offset = m.offset;
            loop {
                let (cp, offset, size) = utf8::get_prev_codepoint(&doc.buffer.data, prev_offset);
                if offset == 0 {
                    m.offset = 0;
                    break;
                }

                match cp {
                    '\n' => {
                        m.offset = offset + 1;

                        if prev_offset > 0 {
                            match utf8::get_prev_codepoint(&doc.buffer.data, prev_offset) {
                                ('\r', offset, _) => {
                                    m.offset = offset;
                                }
                                _ => {}
                            }
                        }
                        break;
                    }

                    '\r' => {
                        m.offset = offset + 1;
                        break;
                    }

                    _ => prev_offset = offset,
                }
            }
        }
    }

    pub fn move_marks_to_end_of_line(&mut self) {

        let doc = self.document.as_mut().unwrap().borrow_mut();
        let max_offset = doc.buffer.data.len() as u64;

        for m in &mut self.moving_marks.borrow_mut().iter_mut() {

            let mut prev_offset = m.offset;

            loop {
                let (cp, mut offset, size) = utf8::get_codepoint(&doc.buffer.data, prev_offset);
                if prev_offset == max_offset {
                    break;
                }
                match cp {

                    '\r' => {
                        match utf8::get_codepoint(&doc.buffer.data, offset) {
                            ('\n', _, _) => {
                                offset += 1;
                            }
                            _ => {}
                        }
                        break;
                    }

                    '\n' => {
                        break;
                    }

                    _ => {}
                }
                prev_offset = offset + size as u64;
            }
            m.offset = prev_offset;
        }
    }

    pub fn insert_codepoint(&mut self, codepoint: char) {

        let mut data: &mut [u8; 4] = &mut [0, 0, 0, 0];

        let data_size = utf8::encode(codepoint as u32, &mut data);
        let mut doc = self.document.as_mut().unwrap().borrow_mut();
        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            doc.buffer.write(m.offset, data_size, data);
            m.offset += data_size as u64;
        }
    }

    pub fn remove_codepoint(&mut self) {

        let mut doc = self.document.as_mut().unwrap().borrow_mut();
        for m in &mut self.moving_marks.borrow_mut().iter_mut() {
            let (cp, offset, size) = utf8::get_codepoint(&doc.buffer.data, m.offset);
            doc.buffer.remove(m.offset, size, None);
        }
    }

    pub fn remove_previous_codepoint(&mut self) {

        let mut doc = self.document.as_mut().unwrap().borrow_mut();
        for m in &mut self.moving_marks.borrow_mut().iter_mut() {

            if m.offset == 0 {
                continue;
            }

            m.move_backward(&doc.buffer, utf8::get_previous_codepoint_start);
            let (cp, offset, size) = utf8::get_codepoint(&doc.buffer.data, m.offset);

            doc.buffer.remove(m.offset, size, None);
        }
    }
}
<|endoftext|>


<commit_before>use rand::Rng;

#[inline]
fn sbx_beta(u: f32, eta: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    if u <= 0.5 {
        2.0 * u
    } else {
        1.0 / (2.0 * (1.0 - u))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
fn sbx_beta_bounded(u: f32, eta: f32, gamma: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    let g = 1.0 - gamma;
    let ug = u * g;

    if u <= 0.5 / g {
        2.0 * ug
    } else {
        1.0 / (2.0 * (1.0 - ug))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
pub fn sbx_single_var<R: Rng>(rng: &mut R, p: (f32, f32), eta: f32) -> (f32, f32) {
    let u = rng.gen::<f32>();
    let beta = sbx_beta(u, eta);

    (0.5 * (((1.0 + beta) * p.0) + ((1.0 - beta) * p.1)),
     0.5 * (((1.0 - beta) * p.0) + ((1.0 + beta) * p.1)))
}

#[inline]
fn _sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                   p: (f32, f32),
                                   bounds: (f32, f32),
                                   eta: f32)
                                   -> (f32, f32) {
    let (a, b) = bounds;
    let p_diff = p.1 - p.0;

    assert!(a <= b);
    assert!(p_diff > 0.0);
    assert!(p.0 >= a && p.0 <= b);
    assert!(p.1 >= a && p.1 <= b);

    let beta_a = 1.0 + (p.0 - a) / p_diff;
    let beta_b = 1.0 + (b - p.1) / p_diff;

    fn gamma(beta: f32, eta: f32) -> f32 {
        1.0 / (2.0 * beta.powf(eta + 1.0))
    }

    let gamma_a = gamma(beta_a, eta);
    let gamma_b = gamma(beta_b, eta);

    let u = rng.gen::<f32>();
    let beta_ua = sbx_beta_bounded(u, eta, gamma_a);
    let beta_ub = sbx_beta_bounded(u, eta, gamma_b);

    let c = (0.5 * (((1.0 + beta_ua) * p.0) + ((1.0 - beta_ua) * p.1)),
             0.5 * (((1.0 - beta_ub) * p.0) + ((1.0 + beta_ub) * p.1)));

    assert!(c.0 >= a && c.0 <= b);
    assert!(c.1 >= a && c.1 <= b);

    return c;
}

#[inline]
pub fn sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                      p: (f32, f32),
                                      bounds: (f32, f32),
                                      eta: f32)
                                      -> (f32, f32) {
    if p.0 < p.1 {
        _sbx_single_var_bounded(rng, (p.0, p.1), bounds, eta)
    } else if p.0 > p.1 {
        let r = _sbx_single_var_bounded(rng, (p.1, p.0), bounds, eta);
        (r.1, r.0)
    } else {
        debug_assert!(p.0 == p.1);
        (p.0, p.1)
    }
}

/// Modifies ind1 and ind2 in-place.
/// Reference: http://www.iitk.ac.in/kangal/papers/k2011017.pdf
pub fn simulated_binary_crossover<R: Rng>(rng: &mut R,
                                          ind1: &mut [f32],
                                          ind2: &mut [f32],
                                          eta: f32) {
    assert!(ind1.len() == ind2.len());

    let iter = ind1.iter_mut().zip(ind2.iter_mut());
    for (x1, x2) in iter {
        let (c1, c2) = sbx_single_var(rng, (*x1, *x2), eta);
        *x1 = c1;
        *x2 = c2;
    }
}

#[test]
fn test_sbx() {
    let mut rng = ::rand::isaac::Isaac64Rng::new_unseeded();

    let parent1 = vec![1.0, 2.0];
    let parent2 = vec![100.0, 1.0];

    let mut child1 = parent1.clone();
    let mut child2 = parent2.clone();

    simulated_binary_crossover(&mut rng, &mut child1[..], &mut child2[..], 2.0);

    let beta: Vec<_> = (0..2)
                           .map(|i| (child2[i] - child1[i]) / (parent2[i] - parent1[i]))
                           .collect();

    println!("({:?}, {:?}) => ({:?}, {:?})",
             parent1,
             parent2,
             child1,
             child2);
    println!("beta: {:?}", beta);
}

pub fn linear_2point_crossover<T:Clone>(p1: &[T], p2: &[T], cut_pt1: (usize, usize), cut_pt2: (usize, usize)) -> Vec<T> {
    assert!(cut_pt1.0 <= cut_pt1.1);
    assert!(cut_pt2.0 <= cut_pt2.1);
    assert!(cut_pt1.0 <= p1.len());
    assert!(cut_pt1.1 <= p1.len());
    assert!(cut_pt2.0 <= p2.len());
    assert!(cut_pt2.1 <= p2.len());

    let len1 = cut_pt1.1 - cut_pt1.0;
    let len2 = cut_pt2.1 - cut_pt2.0;

    let len = p1.len() - /* cut out */ len1 + /* insert */ len2;

    let mut res = Vec::with_capacity(len);
    for e in &p1[..cut_pt1.0] { res.push(e.clone()); }
    for e in &p2[cut_pt2.0..cut_pt2.1] { res.push(e.clone()); }
    for e in &p1[cut_pt1.1..] { res.push(e.clone()); }

    assert!(res.len() == len);
    return res;
}

#[test]
fn test_linear_2point_crossover() {
    let p1 = vec![1,2,3,4];
    //             ^ ^
    let p2 = vec![5,6,7,8,9];
    //             ^     ^

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (1, 4));
    assert_eq!(&[1, 6,7,8, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (1, 5));
    assert_eq!(&[1, 6,7,8,9, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (0, 5));
    assert_eq!(&[1, 5,6,7,8,9, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,1), (0, 5));
    assert_eq!(&[1, 5,6,7,8,9, 2,3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (0,4), (0, 5));
    assert_eq!(&[5,6,7,8,9], &c[..]);
}
<commit_msg>Add randomized linear crossover<commit_after>use rand::Rng;
use rand::distributions::{IndependentSample, Range};

#[inline]
fn sbx_beta(u: f32, eta: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    if u <= 0.5 {
        2.0 * u
    } else {
        1.0 / (2.0 * (1.0 - u))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
fn sbx_beta_bounded(u: f32, eta: f32, gamma: f32) -> f32 {
    assert!(u >= 0.0 && u < 1.0);

    let g = 1.0 - gamma;
    let ug = u * g;

    if u <= 0.5 / g {
        2.0 * ug
    } else {
        1.0 / (2.0 * (1.0 - ug))
    }
    .powf(1.0 / (eta + 1.0))
}

#[inline]
pub fn sbx_single_var<R: Rng>(rng: &mut R, p: (f32, f32), eta: f32) -> (f32, f32) {
    let u = rng.gen::<f32>();
    let beta = sbx_beta(u, eta);

    (0.5 * (((1.0 + beta) * p.0) + ((1.0 - beta) * p.1)),
     0.5 * (((1.0 - beta) * p.0) + ((1.0 + beta) * p.1)))
}

#[inline]
fn _sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                   p: (f32, f32),
                                   bounds: (f32, f32),
                                   eta: f32)
                                   -> (f32, f32) {
    let (a, b) = bounds;
    let p_diff = p.1 - p.0;

    assert!(a <= b);
    assert!(p_diff > 0.0);
    assert!(p.0 >= a && p.0 <= b);
    assert!(p.1 >= a && p.1 <= b);

    let beta_a = 1.0 + (p.0 - a) / p_diff;
    let beta_b = 1.0 + (b - p.1) / p_diff;

    fn gamma(beta: f32, eta: f32) -> f32 {
        1.0 / (2.0 * beta.powf(eta + 1.0))
    }

    let gamma_a = gamma(beta_a, eta);
    let gamma_b = gamma(beta_b, eta);

    let u = rng.gen::<f32>();
    let beta_ua = sbx_beta_bounded(u, eta, gamma_a);
    let beta_ub = sbx_beta_bounded(u, eta, gamma_b);

    let c = (0.5 * (((1.0 + beta_ua) * p.0) + ((1.0 - beta_ua) * p.1)),
             0.5 * (((1.0 - beta_ub) * p.0) + ((1.0 + beta_ub) * p.1)));

    assert!(c.0 >= a && c.0 <= b);
    assert!(c.1 >= a && c.1 <= b);

    return c;
}

#[inline]
pub fn sbx_single_var_bounded<R: Rng>(rng: &mut R,
                                      p: (f32, f32),
                                      bounds: (f32, f32),
                                      eta: f32)
                                      -> (f32, f32) {
    if p.0 < p.1 {
        _sbx_single_var_bounded(rng, (p.0, p.1), bounds, eta)
    } else if p.0 > p.1 {
        let r = _sbx_single_var_bounded(rng, (p.1, p.0), bounds, eta);
        (r.1, r.0)
    } else {
        debug_assert!(p.0 == p.1);
        (p.0, p.1)
    }
}

/// Modifies ind1 and ind2 in-place.
/// Reference: http://www.iitk.ac.in/kangal/papers/k2011017.pdf
pub fn simulated_binary_crossover<R: Rng>(rng: &mut R,
                                          ind1: &mut [f32],
                                          ind2: &mut [f32],
                                          eta: f32) {
    assert!(ind1.len() == ind2.len());

    let iter = ind1.iter_mut().zip(ind2.iter_mut());
    for (x1, x2) in iter {
        let (c1, c2) = sbx_single_var(rng, (*x1, *x2), eta);
        *x1 = c1;
        *x2 = c2;
    }
}

#[test]
fn test_sbx() {
    let mut rng = ::rand::isaac::Isaac64Rng::new_unseeded();

    let parent1 = vec![1.0, 2.0];
    let parent2 = vec![100.0, 1.0];

    let mut child1 = parent1.clone();
    let mut child2 = parent2.clone();

    simulated_binary_crossover(&mut rng, &mut child1[..], &mut child2[..], 2.0);

    let beta: Vec<_> = (0..2)
                           .map(|i| (child2[i] - child1[i]) / (parent2[i] - parent1[i]))
                           .collect();

    println!("({:?}, {:?}) => ({:?}, {:?})",
             parent1,
             parent2,
             child1,
             child2);
    println!("beta: {:?}", beta);
}

pub fn linear_2point_crossover<T:Clone>(p1: &[T], p2: &[T], cut_pt1: (usize, usize), cut_pt2: (usize, usize)) -> Vec<T> {
    assert!(cut_pt1.0 <= cut_pt1.1);
    assert!(cut_pt2.0 <= cut_pt2.1);
    assert!(cut_pt1.0 <= p1.len());
    assert!(cut_pt1.1 <= p1.len());
    assert!(cut_pt2.0 <= p2.len());
    assert!(cut_pt2.1 <= p2.len());

    let len1 = cut_pt1.1 - cut_pt1.0;
    let len2 = cut_pt2.1 - cut_pt2.0;

    let len = p1.len() - /* cut out */ len1 + /* insert */ len2;

    let mut res = Vec::with_capacity(len);
    for e in &p1[..cut_pt1.0] { res.push(e.clone()); }
    for e in &p2[cut_pt2.0..cut_pt2.1] { res.push(e.clone()); }
    for e in &p1[cut_pt1.1..] { res.push(e.clone()); }

    assert!(res.len() == len);
    return res;
}

pub fn linear_2point_crossover_random<R:Rng, T:Clone>(rng: &mut R, p1: &[T], p2: &[T]) -> Vec<T> {
    let r1 = Range::new(0, p1.len());
    let r2 = Range::new(0, p2.len());
    let pt1 = (r1.ind_sample(rng), r1.ind_sample(rng));
    let pt2 = (r2.ind_sample(rng), r2.ind_sample(rng));

    let pt1 = if pt1.0 > pt1.1 {
        (pt1.1, pt1.0)
    } else {
        pt1
    };
    let pt2 = if pt2.0 > pt2.1 {
        (pt2.1, pt2.0)
    } else {
        pt2
    };
    linear_2point_crossover(p1, p2, pt1, pt2)
}

#[test]
fn test_linear_2point_crossover() {
    let p1 = vec![1,2,3,4];
    //             ^ ^
    let p2 = vec![5,6,7,8,9];
    //             ^     ^

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (1, 4));
    assert_eq!(&[1, 6,7,8, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (1, 5));
    assert_eq!(&[1, 6,7,8,9, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,2), (0, 5));
    assert_eq!(&[1, 5,6,7,8,9, 3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (1,1), (0, 5));
    assert_eq!(&[1, 5,6,7,8,9, 2,3,4], &c[..]);

    let c = linear_2point_crossover(&p1[..], &p2[..], (0,4), (0, 5));
    assert_eq!(&[5,6,7,8,9], &c[..]);
}
<|endoftext|>


<commit_before>extern mod kiss3d;
extern mod nalgebra;

use std::rand::random;
use kiss3d::window;

fn main()
{
  do window::Window::spawn(~"Kiss3d: cube") |window|
  {
    let c    = window.add_quad(5.0, 4.0, 500, 400).set_color(random(), random(), random());
    let time = @mut 0.016f32;

    do window.set_loop_callback |_|
    {
      do c.modify_vertices |vs|
      {
        for vs.mut_iter().advance |v|
        {
          v.at[2] = time.sin() * (((v.at[0] + *time) * 4.0).cos() +
                    time.sin() * ((v.at[1] + *time) * 4.0 + *time).cos()) / 2.0
        }

        true
      }

      *time = *time + 0.016;
    }

    window.set_light(window::StickToCamera);
  }
}
<commit_msg>Renamed quad demo window title.<commit_after>extern mod kiss3d;
extern mod nalgebra;

use std::rand::random;
use kiss3d::window;

fn main()
{
  do window::Window::spawn(~"Kiss3d: quad waves") |window|
  {
    let c    = window.add_quad(5.0, 4.0, 500, 400).set_color(random(), random(), random());
    let time = @mut 0.016f32;

    do window.set_loop_callback |_|
    {
      do c.modify_vertices |vs|
      {
        for vs.mut_iter().advance |v|
        {
          v.at[2] = time.sin() * (((v.at[0] + *time) * 4.0).cos() +
                    time.sin() * ((v.at[1] + *time) * 4.0 + *time).cos()) / 2.0
        }

        true
      }

      *time = *time + 0.016;
    }

    window.set_light(window::StickToCamera);
  }
}
<|endoftext|>


<commit_before>use std::fmt;
use ansi_term::Colour;

#[derive(Debug)]
pub enum ErrorLevel {
    Info,
    Warning,
    Error,
}

pub struct Error(pub (ErrorLevel, &'static str));

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let colour_level = match (self.0).0 {
            ErrorLevel::Info => Colour::Yellow.paint("Info"),

            // ansi_term does not have orange for some reason
            ErrorLevel::Warning => Colour::RGB(255, 210, 0).paint("Warning"),
            ErrorLevel::Error => Colour::Red.paint("Error"),
        };

        write!(f, "[{}] {}\n", colour_level, (self.0).1)
    }
}

// Use a hashmap which contains an error level and a string
pub struct ErrorStack(pub Vec<Error>);

impl fmt::Display for ErrorStack {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for error in &self.0 {
            // TODO: Remove this unwrap
            write!(f, "{}", error).unwrap();
        }

        write!(f, "")
    }
}
<commit_msg>Remove newline (TEST).<commit_after>use std::fmt;
use ansi_term::Colour;

#[derive(Debug)]
pub enum ErrorLevel {
    Info,
    Warning,
    Error,
}

pub struct Error(pub (ErrorLevel, &'static str));

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let colour_level = match (self.0).0 {
            ErrorLevel::Info => Colour::Yellow.paint("Info"),

            // ansi_term does not have orange for some reason
            ErrorLevel::Warning => Colour::RGB(255, 210, 0).paint("Warning"),
            ErrorLevel::Error => Colour::Red.paint("Error"),
        };

        write!(f, "[{}] {}", colour_level, (self.0).1)
    }
}

// Use a hashmap which contains an error level and a string
pub struct ErrorStack(pub Vec<Error>);

impl fmt::Display for ErrorStack {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for error in &self.0 {
            // TODO: Remove this unwrap
            write!(f, "{}", error).unwrap();
        }

        write!(f, "")
    }
}
<|endoftext|>


<commit_before>use lexer::{Symbol, Token, Tokens};
use function::{Function, Functions, functions};
use error::EvaluatorError;
use constants::{VERSION, KEYWORDS, HELP, LICENSE};
use std::u32;

pub struct Evaluator {
    functions: Functions,
}

fn is_keyword(variable: &String) -> Option<&str> {
    for keyword in KEYWORDS {
        if keyword.to_string() == variable.to_lowercase() {
            return Some(keyword);
        }
    }

    None
}

impl Evaluator {
    pub fn new() -> Evaluator {
        Evaluator { functions: Functions::new() }
    }

    pub fn evaluate(&self, tokens: Tokens) -> Result<Vec<String>, EvaluatorError> {
        let mut result: Vec<String> = Vec::new();
        let mut stack: Vec<u32> = Vec::new();

        if tokens.is_empty() {
            return Ok(result);
        }

        for (position, token) in tokens {
            match token {
                Token::Decimal(ref dec) => {
                    stack.push(dec.parse().unwrap());
                }
                Token::Hexadecimal(ref hex) => {
                    stack.push(u32::from_str_radix(hex.as_str().split_at(2).1, 16).unwrap());
                }
                Token::Keyword(ref kw) => {
                    if let Some(keyword) = is_keyword(kw) {
                        match keyword {
                            "version" => result.push(VERSION.to_string()),
                            "help" => {
                                result = HELP.lines().map(|line| line.to_string()).collect();
                            }
                            "license" => {
                                result = LICENSE.lines().map(|line| line.to_string()).collect();
                            }
                            "exit" => return Err(EvaluatorError::Exit),
                            _ => unreachable!(),
                        }
                        return Ok(result);
                    } else {
                        return Err(EvaluatorError::UnknownKeyword(position));
                    }
                }
                Token::Operator(ref op) => {
                    let function = self.functions.get(&op).unwrap();
                    if stack.len() < function.arity {
                        return Err(EvaluatorError::MissingArgument(position));
                    }
                    let stack_len = stack.len();
                    let args: Vec<u32> = stack.split_off(stack_len - function.arity);
                    let interm_result = try!((function.handle)(args, position));
                    stack.push(interm_result.0);
                    result.push(interm_result.1);
                    result.push(interm_result.0.to_string());
                }
                _ => continue,

            }
        }

        // The last element on the stack should be the final result
        if stack.len() != 1 {
            return Err(EvaluatorError::TooManyArguments);
        } else if result.is_empty() {
            result.push(stack.pop().unwrap().to_string());
        }

        Ok(result)
    }
}

impl Default for Evaluator {
    fn default() -> Evaluator {
        let mut evaluator = Evaluator::new();

        evaluator.functions.insert(Symbol::NOT, Function::new(1, Box::new(functions::not)));
        evaluator.functions.insert(Symbol::XOR, Function::new(2, Box::new(functions::xor)));
        evaluator.functions.insert(Symbol::OR, Function::new(2, Box::new(functions::or)));
        evaluator.functions.insert(Symbol::AND, Function::new(2, Box::new(functions::and)));
        evaluator.functions.insert(Symbol::LSHIFT,
                                   Function::new(2, Box::new(functions::lshift)));
        evaluator.functions.insert(Symbol::RSHIFT,
                                   Function::new(2, Box::new(functions::rshift)));

        evaluator
    }
}
<commit_msg>Any other token in the evaluator should be unreachable<commit_after>use lexer::{Symbol, Token, Tokens};
use function::{Function, Functions, functions};
use error::EvaluatorError;
use constants::{VERSION, KEYWORDS, HELP, LICENSE};
use std::u32;

pub struct Evaluator {
    functions: Functions,
}

fn is_keyword(variable: &String) -> Option<&str> {
    for keyword in KEYWORDS {
        if keyword.to_string() == variable.to_lowercase() {
            return Some(keyword);
        }
    }

    None
}

impl Evaluator {
    pub fn new() -> Evaluator {
        Evaluator { functions: Functions::new() }
    }

    pub fn evaluate(&self, tokens: Tokens) -> Result<Vec<String>, EvaluatorError> {
        let mut result: Vec<String> = Vec::new();
        let mut stack: Vec<u32> = Vec::new();

        if tokens.is_empty() {
            return Ok(result);
        }

        for (position, token) in tokens {
            match token {
                Token::Decimal(ref dec) => {
                    stack.push(dec.parse().unwrap());
                }
                Token::Hexadecimal(ref hex) => {
                    stack.push(u32::from_str_radix(hex.as_str().split_at(2).1, 16).unwrap());
                }
                Token::Keyword(ref kw) => {
                    if let Some(keyword) = is_keyword(kw) {
                        match keyword {
                            "version" => result.push(VERSION.to_string()),
                            "help" => {
                                result = HELP.lines().map(|line| line.to_string()).collect();
                            }
                            "license" => {
                                result = LICENSE.lines().map(|line| line.to_string()).collect();
                            }
                            "exit" => return Err(EvaluatorError::Exit),
                            _ => unreachable!(),
                        }
                        return Ok(result);
                    } else {
                        return Err(EvaluatorError::UnknownKeyword(position));
                    }
                }
                Token::Operator(ref op) => {
                    let function = self.functions.get(&op).unwrap();
                    if stack.len() < function.arity {
                        return Err(EvaluatorError::MissingArgument(position));
                    }
                    let stack_len = stack.len();
                    let args: Vec<u32> = stack.split_off(stack_len - function.arity);
                    let interm_result = try!((function.handle)(args, position));
                    stack.push(interm_result.0);
                    result.push(interm_result.1);
                    result.push(interm_result.0.to_string());
                }
                _ => unreachable!(),

            }
        }

        // The last element on the stack should be the final result
        if stack.len() != 1 {
            return Err(EvaluatorError::TooManyArguments);
        } else if result.is_empty() {
            result.push(stack.pop().unwrap().to_string());
        }

        Ok(result)
    }
}

impl Default for Evaluator {
    fn default() -> Evaluator {
        let mut evaluator = Evaluator::new();

        evaluator.functions.insert(Symbol::NOT, Function::new(1, Box::new(functions::not)));
        evaluator.functions.insert(Symbol::XOR, Function::new(2, Box::new(functions::xor)));
        evaluator.functions.insert(Symbol::OR, Function::new(2, Box::new(functions::or)));
        evaluator.functions.insert(Symbol::AND, Function::new(2, Box::new(functions::and)));
        evaluator.functions.insert(Symbol::LSHIFT,
                                   Function::new(2, Box::new(functions::lshift)));
        evaluator.functions.insert(Symbol::RSHIFT,
                                   Function::new(2, Box::new(functions::rshift)));

        evaluator
    }
}
<|endoftext|>


<commit_before>fn main() {
    println!("Value in cents of Penny: {}", value_in_cents(Coin::Penny));
    println!(
        "Value in cents of Quarter: {}",
        value_in_cents(Coin::Quarter(UsState::California)));
}

#[derive(Debug)]
enum UsState {
    California,
    Georgia,
    Texas
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState)
}

fn value_in_cents(coin: Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("Quarter from state: {:?}", state);
            25
        },
    }
}<commit_msg>Example of matching with Option<T><commit_after>fn main() {
    println!("Value in cents of Penny: {}", value_in_cents(Coin::Penny));
    println!(
        "Value in cents of Quarter: {}",
        value_in_cents(Coin::Quarter(UsState::California)));

    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}

#[derive(Debug)]
enum UsState {
    California,
    Georgia,
    Texas
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState)
}

fn value_in_cents(coin: Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("Quarter from state: {:?}", state);
            25
        },
    }
}

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1)
    }
}
<|endoftext|>


<commit_before>use Addr;
use system::memory::{ptr, read};

#[derive(Copy, Clone)]
pub struct Flag(pub Addr, pub u8);

pub const HAS_SEEN_HELMAROC_ARRIVING_AT_OUTSET: Flag = Flag(0x803B872C, 1 << 0);
pub const FOREST_OF_FAIRIES_BOKOBLINS_SPAWNED: Flag = Flag(0x803B872C, 1 << 2);
pub const TALKED_TO_MESA_ON_OUTSET: Flag = Flag(0x803B872C, 1 << 4);
pub const RESCUED_TETRA: Flag = Flag(0x803B872D, 1 << 0);
pub const GOT_A_RUPEE_ON_THE_OUTSET_ROCKS: Flag = Flag(0x803B872D, 1 << 2);
pub const TALKED_TO_ORCA_AFTER_HELMAROC_ARRIVED: Flag = Flag(0x803B872D, 1 << 3);
pub const SAW_A_LIGHT_OPERATOR_BOKOBLIN: Flag = Flag(0x803B872E, 1 << 0);
pub const TALKED_TO_ZILL_ON_OUTSET: Flag = Flag(0x803B872E, 1 << 5);
pub const SAW_TETRA_IN_FOREST_OF_FAIRIES: Flag = Flag(0x803B872E, 1 << 7);
pub const KILLED_ONE_FOREST_OF_FAIRIES_BOKOBLIN: Flag = Flag(0x803B872F, 1 << 0);
pub const PIRATE_SHIP_ARRIVING_ON_OUTSET: Flag = Flag(0x803B872F, 1 << 4);
pub const PICKED_UP_FIRST_BARREL_IN_FF1: Flag = Flag(0x803B8730, 1 << 0);
pub const GRABBED_FIRST_ROPE_IN_FF1: Flag = Flag(0x803B8730, 1 << 1);
pub const GOT_THROWN_INTO_JAIL_IN_FF1: Flag = Flag(0x803B8730, 1 << 2);
pub const KILLED_BOTH_FOREST_OF_FAIRIES_BOKOBLINS: Flag = Flag(0x803B8730, 1 << 7);
pub const GOSSIP_STONE_AT_FF1: Flag = Flag(0x803B8731, 1 << 5);
pub const COMPLETED_PIRATE_SHIP_MINIGAME: Flag = Flag(0x803B8733, 1 << 4);
pub const SAW_PIRATE_SHIP_MINIGAME_INTRO: Flag = Flag(0x803B8733, 1 << 5);
pub const GOT_CATAPULTED_TO_FF1_AND_SPAWN_THERE: Flag = Flag(0x803B8734, 1 << 0);
pub const LONG_TETRA_TEXT_ON_OUTSET: Flag = Flag(0x803B8734, 1 << 1);
pub const TETRA_TOLD_YOU_TO_CLIMB_UP_THE_LADDER: Flag = Flag(0x803B8734, 1 << 2);
pub const COMPLETED_PIRATE_SHIP_MINIGAME_AND_SPAWN_ON_PIRATE_SHIP: Flag = Flag(0x803B8734, 1 << 3);
pub const SAIL_INTRODUCTION_TEXT_AND_MAP_UNLOCKED: Flag = Flag(0x803B8735, 1 << 3);
pub const ENDLESS_NIGHT: Flag = Flag(0x803B8736, 1 << 1);
pub const KORL_DINS_PEARL_TEXT_ALLOWING_YOU_TO_ENTER_HIM: Flag = Flag(0x803B8736, 1 << 7);
pub const HURRICANE_SPIN_UNLOCKED: Flag = Flag(0x803B8737, 1 << 5);
pub const PIRATES_ON_OUTSET: Flag = Flag(0x803B873A, 1 << 5);
pub const KORL_UNLOCKED_AND_SPAWN_ON_WINDFALL: Flag = Flag(0x803B873B, 1 << 7);
pub const WATCHED_FIRE_AND_ICE_ARROWS_CUTSCENE: Flag = Flag(0x803B873C, 1 << 0);
pub const MEDLI_ON_DRI_INTRODUCTION_CUTSCENE_WATCHED: Flag = Flag(0x803B8740, 1 << 1);
pub const SHOWED_MEDLI_THE_WIND_WAKER_ON_DRI: Flag = Flag(0x803B8741, 1 << 2);
pub const HAS_MAKAR_ON_BOAT_1: Flag = Flag(0x803B8742, 1 << 2);
pub const HAS_MEDLI_ON_BOAT_1: Flag = Flag(0x803B8742, 1 << 3);
pub const HAS_MAKAR_ON_BOAT_2_AND_IS_GRABABLE: Flag = Flag(0x803B8742, 1 << 4);
pub const HAS_MEDLI_ON_BOAT_2_AND_CAN_CARRY_YOU: Flag = Flag(0x803B8742, 1 << 5);
pub const TALKED_TO_KORL_AFTER_HYRULE_2_AND_FF3_ACTIVE: Flag = Flag(0x803B8744, 1 << 5);
pub const IS_ALLOWED_TO_ENTER_KORL: Flag = Flag(0x803B8745, 1 << 7);
pub const TOWER_OF_THE_GODS_RAISED: Flag = Flag(0x803B874A, 1 << 6);
pub const WATCHED_DEPARTURE_CUTSCENE_AND_SPAWN_ON_PIRATE_SHIP: Flag = Flag(0x803B8750, 1 << 0);
pub const TALKED_TO_SAIL_SHOP_NPC: Flag = Flag(0x803B8750, 1 << 5);
pub const WATCHED_FIND_SISTER_IN_FF1_CUTSCENE: Flag = Flag(0x803B8751, 1 << 7);
pub const SOME_WEIRD_FIRE_AND_ICE_ARROWS_CUTSCENE_FLAG: Flag = Flag(0x803B8753, 1 << 6);
pub const MAKAR_IN_WIND_TEMPLE: Flag = Flag(0x803B8755, 1 << 4);
pub const MEDLI_IN_EARTH_TEMPLE: Flag = Flag(0x803B8755, 1 << 5);
pub const ENTER_KORL_FOR_THE_FIRST_TIME_AND_SPAWN_ANYWHERE: Flag = Flag(0x803B8756, 1 << 3);
pub const HAS_HEROS_CLOTHES: Flag = Flag(0x803B8756, 1 << 7);
pub const MIGHTY_DARKNUTS_DEFEATED: Flag = Flag(0x803B8758, 1 << 0);
pub const BARRIER_DOWN: Flag = Flag(0x803B8758, 1 << 1);
pub const ANIMATION_SET_2: Flag = Flag(0x803B8759, 1 << 0);
pub const TETRA_TO_ZELDA_CUTSCENE: Flag = Flag(0x803B8759, 1 << 1);
pub const MASTER_SWORD_CUTSCENE: Flag = Flag(0x803B8759, 1 << 2);
pub const HYRULE_3_WARP_CUTSCENE: Flag = Flag(0x803B8759, 1 << 3);
pub const RINGING_BELL_AND_HYRULE_1_CUTSCENE: Flag = Flag(0x803B8759, 1 << 4);
pub const WIND_GODS_ARIA_CUTSCENE: Flag = Flag(0x803B8759, 1 << 5);
pub const EARTH_GODS_LYRIC_CUTSCENE: Flag = Flag(0x803B8759, 1 << 6);
pub const WATCHED_MEETING_KORL_CUTSCENE: Flag = Flag(0x803B875A, 1 << 0);
pub const MAKAR_IN_WIND_TEMPLE_ENTRANCE: Flag = Flag(0x803B875A, 1 << 1);
pub const MEDLI_IN_EARTH_TEMPLE_ENTRANCE: Flag = Flag(0x803B875A, 1 << 2);
pub const PEARL_TOWER_CUTSCENE: Flag = Flag(0x803B875A, 1 << 7);
pub const DID_SWORD_FIGHTING_TUTORIAL: Flag = Flag(0x803B875B, 1 << 4);
pub const GOT_SHIELD_FROM_GRANDMA: Flag = Flag(0x803B875E, 1 << 1);
pub const WATCHED_DESCENDING_DOWN_TO_HYRULE_2_CUTSCENE: Flag = Flag(0x803B875E, 1 << 7);
pub const WATCHED_TEXT_AFTER_FIRE_AND_ICE_ARROWS_CUTSCENE: Flag = Flag(0x803B875F, 1 << 7);
pub const HAS_SEEN_INTRO: Flag = Flag(0x803B8761, 1 << 4);
pub const MIGHTY_DARKNUTS_SPAWNED: Flag = Flag(0x803B8761, 1 << 5);
pub const COLORS_IN_HYRULE: Flag = Flag(0x803B8764, 1 << 1);
pub const WATCHED_COURTYARD_CUTSCENE: Flag = Flag(0x803B8764, 1 << 2);
pub const MOVED_STATUE_IN_HYRULE: Flag = Flag(0x803B8764, 1 << 5);
pub const WATCHED_FF2_GANONDORF_CUTSCENE: Flag = Flag(0x803B8765, 1 << 4);
pub const HYRULE_3_ELECTRICAL_BARRIER_CUTSCENE_1: Flag = Flag(0x803B8765, 1 << 7);
pub const TRIALS_JALHALLA: Flag = Flag(0x803B8765, 1 << 0);
pub const TRIALS_KALLE_DEMOS: Flag = Flag(0x803B8765, 1 << 1);
pub const TRIALS_GOHMA: Flag = Flag(0x803B8765, 1 << 2);
pub const TRIALS_MOLGERA: Flag = Flag(0x803B8766, 1 << 7);
pub const PULLED_MASTER_SWORD_IN_HYRULE_1_SWINGING_CUTSCENE: Flag = Flag(0x803B8766, 1 << 2);
pub const MEDLI_DRAGON_ROOST_CUTSCENE_WATCHED: Flag = Flag(0x803B8767, 1 << 4);
pub const HYRULE_1_ELECTRICAL_BARRIER_DEACTIVATED: Flag = Flag(0x803B8767, 1 << 6);
pub const FF3_TO_HYRULE_WARP_ACTIVE: Flag = Flag(0x803B8769, 1 << 1);
pub const DONT_SHOW_WEAPONS: Flag = Flag(0x803B876B, 1 << 6);

impl Flag {
    pub fn activate(self) {
        let Flag(addr, value) = self;
        let ptr = ptr::<u8>(addr);
        unsafe {
            *ptr |= value;
        }
    }

    pub fn deactivate(self) {
        let Flag(addr, value) = self;
        let ptr = ptr::<u8>(addr);
        unsafe {
            *ptr &= 0xFF ^ value;
        }
    }

    pub fn is_active(self) -> bool {
        let Flag(addr, mask) = self;
        let value = read::<u8>(addr);
        value & mask != 0
    }

    pub fn toggle(self) {
        if self.is_active() {
            self.deactivate()
        } else {
            self.activate()
        }
    }
}
<commit_msg>Add Flags<commit_after>use Addr;
use system::memory::{ptr, read};

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Flag(pub Addr, pub u8);

pub const HAS_SEEN_HELMAROC_ARRIVING_AT_OUTSET: Flag = Flag(0x803B872C, 1 << 0);
pub const FOREST_OF_FAIRIES_BOKOBLINS_SPAWNED: Flag = Flag(0x803B872C, 1 << 2);
pub const TALKED_TO_MESA_ON_OUTSET: Flag = Flag(0x803B872C, 1 << 4);
pub const RESCUED_TETRA: Flag = Flag(0x803B872D, 1 << 0);
pub const GOT_A_RUPEE_ON_THE_OUTSET_ROCKS: Flag = Flag(0x803B872D, 1 << 2);
pub const TALKED_TO_ORCA_AFTER_HELMAROC_ARRIVED: Flag = Flag(0x803B872D, 1 << 3);
pub const SAW_A_LIGHT_OPERATOR_BOKOBLIN: Flag = Flag(0x803B872E, 1 << 0);
pub const TALKED_TO_ZILL_ON_OUTSET: Flag = Flag(0x803B872E, 1 << 5);
pub const SAW_TETRA_IN_FOREST_OF_FAIRIES: Flag = Flag(0x803B872E, 1 << 7);
pub const KILLED_ONE_FOREST_OF_FAIRIES_BOKOBLIN: Flag = Flag(0x803B872F, 1 << 0);
pub const PIRATE_SHIP_ARRIVING_ON_OUTSET: Flag = Flag(0x803B872F, 1 << 4);
pub const SAW_LAVA_PLATFORMS_FORMING: Flag = Flag(0x803B872F, 1 << 7);
pub const PICKED_UP_FIRST_BARREL_IN_FF1: Flag = Flag(0x803B8730, 1 << 0); // Don't show Jail Text anymore
pub const GRABBED_FIRST_ROPE_IN_FF1: Flag = Flag(0x803B8730, 1 << 1);
pub const GOT_THROWN_INTO_JAIL_IN_FF1: Flag = Flag(0x803B8730, 1 << 2);
pub const GRAPPLED_VALOOS_TAIL: Flag = Flag(0x803B8730, 1 << 5);
pub const KILLED_BOTH_FOREST_OF_FAIRIES_BOKOBLINS: Flag = Flag(0x803B8730, 1 << 7);
pub const GOSSIP_STONE_AT_FF1: Flag = Flag(0x803B8731, 1 << 5);
pub const GRAPPLED_VALOOS_TAIL_2: Flag = Flag(0x803B8731, 1 << 6);
pub const USED_GRAPPLING_HOOK: Flag = Flag(0x803B8731, 1 << 7);
pub const COMPLETED_PIRATE_SHIP_MINIGAME: Flag = Flag(0x803B8733, 1 << 4);
pub const SAW_PIRATE_SHIP_MINIGAME_INTRO: Flag = Flag(0x803B8733, 1 << 5);
pub const GOT_CATAPULTED_TO_FF1_AND_SPAWN_THERE: Flag = Flag(0x803B8734, 1 << 0);
pub const LONG_TETRA_TEXT_ON_OUTSET: Flag = Flag(0x803B8734, 1 << 1);
pub const TETRA_TOLD_YOU_TO_CLIMB_UP_THE_LADDER: Flag = Flag(0x803B8734, 1 << 2);
pub const COMPLETED_PIRATE_SHIP_MINIGAME_AND_SPAWN_ON_PIRATE_SHIP: Flag = Flag(0x803B8734, 1 << 3);
pub const SAW_DRAGON_ROOST_ISLAND_INTRO: Flag = Flag(0x803B8735, 1 << 1);
pub const SAIL_INTRODUCTION_TEXT_AND_MAP_UNLOCKED: Flag = Flag(0x803B8735, 1 << 3);
pub const ENDLESS_NIGHT: Flag = Flag(0x803B8736, 1 << 1);
pub const TALKED_TO_KORL_ON_DRI: Flag = Flag(0x803B8736, 1 << 4);
pub const KORL_DINS_PEARL_TEXT_ALLOWING_YOU_TO_ENTER_HIM: Flag = Flag(0x803B8736, 1 << 7);
pub const TALKED_TO_TOTT_ON_WINDFALL: Flag = Flag(0x803B8737, 1 << 3);
pub const HURRICANE_SPIN_UNLOCKED: Flag = Flag(0x803B8737, 1 << 5);
pub const TALKED_TO_TINGLE_IN_JAIL: Flag = Flag(0x803B8737, 1 << 6);
pub const RESCUED_TINGLE: Flag = Flag(0x803B8737, 1 << 7);
pub const GOT_KOMALIS_LETTER: Flag = Flag(0x803B873A, 1 << 1);
pub const PIRATES_ON_OUTSET: Flag = Flag(0x803B873A, 1 << 5);
pub const TALKED_TO_KOMALI_AFTER_SHOWING_THE_LETTER: Flag = Flag(0x803B873B, 1 << 2);
pub const TALKED_TO_KOMALI_WITHOUT_THE_LETTER: Flag = Flag(0x803B873B, 1 << 3);
pub const KORL_UNLOCKED_AND_SPAWN_ON_WINDFALL: Flag = Flag(0x803B873B, 1 << 7);
pub const WATCHED_FIRE_AND_ICE_ARROWS_CUTSCENE: Flag = Flag(0x803B873C, 1 << 0);
pub const GOT_GRAPPLING_HOOK_FROM_MEDLI: Flag = Flag(0x803B873D, 1 << 0);
pub const GOT_BOTTLE_FROM_MEDLI: Flag = Flag(0x803B873D, 1 << 1);
pub const TALKED_TO_MEDLI_IN_THE_POND: Flag = Flag(0x803B873D, 1 << 2);
pub const RESCUED_MEDLI_IN_DRC: Flag = Flag(0x803B873D, 1 << 6);
pub const MEDLI_EXPLAINED_GRAPPLING_HOOK: Flag = Flag(0x803B873E, 1 << 7);
pub const MEDLI_ON_DRI_INTRODUCTION_CUTSCENE_WATCHED: Flag = Flag(0x803B8740, 1 << 1);
pub const SHOWED_MEDLI_THE_WIND_WAKER_ON_DRI: Flag = Flag(0x803B8741, 1 << 2);
pub const HAS_MAKAR_ON_BOAT_1: Flag = Flag(0x803B8742, 1 << 2);
pub const HAS_MEDLI_ON_BOAT_1: Flag = Flag(0x803B8742, 1 << 3);
pub const HAS_MAKAR_ON_BOAT_2_AND_IS_GRABBABLE: Flag = Flag(0x803B8742, 1 << 4);
pub const HAS_MEDLI_ON_BOAT_2_AND_CAN_CARRY_YOU: Flag = Flag(0x803B8742, 1 << 5);
pub const SAW_KOMALI_IN_HIS_ROOM: Flag = Flag(0x803B8744, 1 << 4);
pub const TALKED_TO_KORL_AFTER_HYRULE_2_AND_FF3_ACTIVE: Flag = Flag(0x803B8744, 1 << 5);
pub const IS_ALLOWED_TO_ENTER_KORL: Flag = Flag(0x803B8745, 1 << 7);
pub const TALKED_TO_GARRICKSON_ON_WINDFALL: Flag = Flag(0x803B874A, 1 << 3);
pub const TOWER_OF_THE_GODS_RAISED: Flag = Flag(0x803B874A, 1 << 6);
pub const SAW_QUILL_CUTSCENE_ON_DRI: Flag = Flag(0x803B874B, 1 << 6);
pub const TALKED_TO_ANTON_ON_WINDFALL: Flag = Flag(0x803B874E, 1 << 3);
pub const WATCHED_DEPARTURE_CUTSCENE_AND_SPAWN_ON_PIRATE_SHIP: Flag = Flag(0x803B8750, 1 << 0);
pub const TALKED_TO_ZUNARI_ON_WINDFALL: Flag = Flag(0x803B8750, 1 << 5);
pub const GOT_DELIVERY_BAG: Flag = Flag(0x803B8751, 1 << 1);
pub const WATCHED_FIND_SISTER_IN_FF1_CUTSCENE: Flag = Flag(0x803B8751, 1 << 7);
pub const LEARNED_WINDS_REQUIEM: Flag = Flag(0x803B8753, 1 << 3); // Doesn't trigger if you do Zephos Skip
pub const SOME_WEIRD_FIRE_AND_ICE_ARROWS_CUTSCENE_FLAG: Flag = Flag(0x803B8753, 1 << 6);
pub const TALKED_TO_JOANNA_ON_WINDFALL: Flag = Flag(0x803B8754, 1 << 7);
pub const MAKAR_IN_WIND_TEMPLE: Flag = Flag(0x803B8755, 1 << 4);
pub const MEDLI_IN_EARTH_TEMPLE: Flag = Flag(0x803B8755, 1 << 5);
pub const ENTER_KORL_FOR_THE_FIRST_TIME_AND_SPAWN_ANYWHERE: Flag = Flag(0x803B8756, 1 << 3);
pub const HAS_HEROS_CLOTHES: Flag = Flag(0x803B8756, 1 << 7);
pub const TALKED_TO_POTOVA_ON_WINDFALL: Flag = Flag(0x803B8757, 1 << 3);
pub const MIGHTY_DARKNUTS_DEFEATED: Flag = Flag(0x803B8758, 1 << 0);
pub const BARRIER_DOWN: Flag = Flag(0x803B8758, 1 << 1);
pub const ANIMATION_SET_2: Flag = Flag(0x803B8759, 1 << 0);
pub const TETRA_TO_ZELDA_CUTSCENE: Flag = Flag(0x803B8759, 1 << 1);
pub const MASTER_SWORD_CUTSCENE: Flag = Flag(0x803B8759, 1 << 2);
pub const HYRULE_3_WARP_CUTSCENE: Flag = Flag(0x803B8759, 1 << 3);
pub const RINGING_BELL_AND_HYRULE_1_CUTSCENE: Flag = Flag(0x803B8759, 1 << 4);
pub const WIND_GODS_ARIA_CUTSCENE: Flag = Flag(0x803B8759, 1 << 5);
pub const EARTH_GODS_LYRIC_CUTSCENE: Flag = Flag(0x803B8759, 1 << 6);
pub const WATCHED_MEETING_KORL_CUTSCENE: Flag = Flag(0x803B875A, 1 << 0);
pub const MAKAR_IN_WIND_TEMPLE_ENTRANCE: Flag = Flag(0x803B875A, 1 << 1);
pub const MEDLI_IN_EARTH_TEMPLE_ENTRANCE: Flag = Flag(0x803B875A, 1 << 2);
pub const PEARL_TOWER_CUTSCENE: Flag = Flag(0x803B875A, 1 << 7);
pub const DID_SWORD_FIGHTING_TUTORIAL: Flag = Flag(0x803B875B, 1 << 4);
pub const GOT_SHIELD_FROM_GRANDMA: Flag = Flag(0x803B875E, 1 << 1);
pub const WATCHED_DESCENDING_DOWN_TO_HYRULE_2_CUTSCENE: Flag = Flag(0x803B875E, 1 << 7);
pub const WATCHED_TEXT_AFTER_FIRE_AND_ICE_ARROWS_CUTSCENE: Flag = Flag(0x803B875F, 1 << 7);
pub const HAS_SEEN_INTRO: Flag = Flag(0x803B8761, 1 << 4);
pub const MIGHTY_DARKNUTS_SPAWNED: Flag = Flag(0x803B8761, 1 << 5);
pub const COLORS_IN_HYRULE: Flag = Flag(0x803B8764, 1 << 1);
pub const WATCHED_COURTYARD_CUTSCENE: Flag = Flag(0x803B8764, 1 << 2);
pub const MOVED_STATUE_IN_HYRULE: Flag = Flag(0x803B8764, 1 << 5);
pub const WATCHED_FF2_GANONDORF_CUTSCENE: Flag = Flag(0x803B8765, 1 << 4);
pub const HYRULE_3_ELECTRICAL_BARRIER_CUTSCENE_1: Flag = Flag(0x803B8765, 1 << 7);
pub const TRIALS_JALHALLA: Flag = Flag(0x803B8765, 1 << 0);
pub const TRIALS_KALLE_DEMOS: Flag = Flag(0x803B8765, 1 << 1);
pub const TRIALS_GOHMA: Flag = Flag(0x803B8765, 1 << 2);
pub const SAW_DRC_BEATEN_CUTSCENE: Flag = Flag(0x803B8765, 1 << 3);
pub const TRIALS_MOLGERA: Flag = Flag(0x803B8766, 1 << 7);
pub const PULLED_MASTER_SWORD_IN_HYRULE_1_SWINGING_CUTSCENE: Flag = Flag(0x803B8766, 1 << 2);
pub const WATCHED_MEDLI_DRAGON_ROOST_CUTSCENE: Flag = Flag(0x803B8767, 1 << 4);
pub const HYRULE_1_ELECTRICAL_BARRIER_DEACTIVATED: Flag = Flag(0x803B8767, 1 << 6);
pub const FF3_TO_HYRULE_WARP_ACTIVE: Flag = Flag(0x803B8769, 1 << 1);
pub const DEFEATED_GOHMA: Flag = Flag(0x803B8769, 1 << 7);
pub const DONT_SHOW_WEAPONS: Flag = Flag(0x803B876B, 1 << 6);

impl Flag {
    pub fn activate(self) {
        let Flag(addr, value) = self;
        let ptr = ptr::<u8>(addr);
        unsafe {
            *ptr |= value;
        }
    }

    pub fn deactivate(self) {
        let Flag(addr, value) = self;
        let ptr = ptr::<u8>(addr);
        unsafe {
            *ptr &= 0xFF ^ value;
        }
    }

    pub fn is_active(self) -> bool {
        let Flag(addr, mask) = self;
        let value = read::<u8>(addr);
        value & mask != 0
    }

    pub fn toggle(self) {
        if self.is_active() {
            self.deactivate()
        } else {
            self.activate()
        }
    }
}
<|endoftext|>


<commit_before>
use piston_window::*;
use piston_window::character::CharacterCache;

use game::block::Block;
use game::config::Config;
use game::render_options::RenderOptions;
use game::tetromino::Tetromino;

pub struct Grid {
    pub boxes: [[Option<Block>; 10]; 22],
    overlay: [[Option<Block>; 10]; 22],
    border: rectangle::Rectangle,
    block: rectangle::Rectangle,
}

impl Grid {
    pub fn new() -> Grid {
        Grid {
            boxes: [[None; 10]; 22],
            overlay: [[None; 10]; 22],
            border: rectangle::Rectangle::new([1.0; 4]),
            block: rectangle::Rectangle::new([0.0; 4]),
        }
    }

    pub fn apply_tetromino(&mut self, tetromino: &Tetromino, config: &Config) {
        // Clear the overlay
        self.overlay = [[None; 10]; 22];

        for y in 0..4 {
            for x in 0..4 {
                if let Some(ref block) = tetromino.blocks[y][x] {
                    let x = (tetromino.x + x as i32) as usize;
                    let y = (tetromino.y + y as i32) as usize;

                    let (shadow_x, shadow_y) = tetromino.find_landing_xy(&self.boxes);
                    let shadow_x = (shadow_x + x as i32) as usize;
                    let shadow_y = (shadow_y + y as i32) as usize;

                    if x >= 10 || y >= 22 {
                        continue;
                    }

                    self.overlay[y][x] = Some(*block);

                    // If the shadow is enabled, also store that in the overlay
                    if config.shadow_enabled {
                        if let Some(ref shadow) = tetromino.shadow[y][x] {
                            self.overlay[shadow_y][shadow_x] = Some(*shadow);
                        }
                    }
                }
            }
        }
    }

    pub fn store_tetromino(&mut self, tetromino: &Tetromino) {
        for y in 0..4 {
            for x in 0..4 {
                if let Some(ref block) = tetromino.blocks[y][x] {
                    let x = (tetromino.x + x as i32) as usize;
                    let y = (tetromino.y + y as i32) as usize;

                    if x >= 10 || y >= 22 {
                        continue;
                    }

                    self.boxes[y][x] = Some(*block);
                }
            }
        }
    }

    /// Removes complete lines from the grid
    pub fn remove_complete_lines(&mut self, config: &Config) -> u32 {
        // Pointer to where we're currently writing lines
        let mut y_mut = (config.grid_size.1 - 1) as usize;
        let mut cleared_lines = 0;

        for y in (0..config.grid_size.1).rev() {
            // If every column in this row has a block,
            // we consider it "complete"
            let complete = self.boxes[y as usize].iter().all(|block| block.is_some());

            // If this is not a complete line, copy it
            // into the currently pointed line
            if !complete {
                self.boxes[y_mut] = self.boxes[y as usize];
                y_mut -= 1;
                if y_mut == 0 {
                    break;
                }
            } else {
                cleared_lines += 1;
            }
        }

        cleared_lines
    }

    pub fn render<'a, G, C>(&self, options: &mut RenderOptions<'a, G, C>, e: &Event)
        where C: CharacterCache,
              G: Graphics<Texture = <C as CharacterCache>::Texture>
    {
        let grid_offset = options.config.grid_offset;
        let tile_size = options.config.tile_size;

        // Draw the "border" first
        self.border.draw([(grid_offset - 2.0) as f64,
                          (grid_offset - 2.0) as f64,
                          (tile_size * 10.0 + 4.0) as f64,
                          (tile_size * 20.0 + 4.0) as f64],
                         &Default::default(),
                         options.context.transform,
                         options.graphics);

        for y in 2..22 {
            for x in 0..10 {

                let adjusted_y = y - 2;
                if let Some(ref block) = self.overlay[y][x] {
                    block.render(x, y, options.config, options.context, options.graphics, e);
                    continue;
                }

                match self.boxes[y][x] {
                    Some(ref block) => {
                        block.render(x, y, options.config, options.context, options.graphics, e);
                    }
                    None => {
                        self.block.draw([x as f64 * tile_size + grid_offset,
                                         adjusted_y as f64 * tile_size + grid_offset,
                                         tile_size as f64,
                                         tile_size as f64],
                                        &Default::default(),
                                        options.context.transform,
                                        options.graphics);
                    }
                };
            }
        }
    }
}
<commit_msg>Fixed grid rendering<commit_after>
use piston_window::*;
use piston_window::character::CharacterCache;

use game::block::Block;
use game::config::Config;
use game::render_options::RenderOptions;
use game::tetromino::Tetromino;

pub struct Grid {
    pub boxes: [[Option<Block>; 10]; 22],
    overlay: [[Option<Block>; 10]; 22],
    border: rectangle::Rectangle,
    block: rectangle::Rectangle,
}

impl Grid {
    pub fn new() -> Grid {
        Grid {
            boxes: [[None; 10]; 22],
            overlay: [[None; 10]; 22],
            border: rectangle::Rectangle::new([1.0; 4]),
            block: rectangle::Rectangle::new([0.0, 0.0, 0.0, 1.0]),
        }
    }

    pub fn apply_tetromino(&mut self, tetromino: &Tetromino, config: &Config) {
        // Clear the overlay
        self.overlay = [[None; 10]; 22];

        for y in 0..4 {
            for x in 0..4 {
                if let Some(ref block) = tetromino.blocks[y][x] {
                    let x = (tetromino.x + x as i32) as usize;
                    let y = (tetromino.y + y as i32) as usize;

                    let (shadow_x, shadow_y) = tetromino.find_landing_xy(&self.boxes);
                    let shadow_x = (shadow_x + x as i32) as usize;
                    let shadow_y = (shadow_y + y as i32) as usize;

                    if x >= 10 || y >= 22 {
                        continue;
                    }

                    self.overlay[y][x] = Some(*block);

                    // If the shadow is enabled, also store that in the overlay
                    if config.shadow_enabled {
                        if let Some(ref shadow) = tetromino.shadow[y][x] {
                            self.overlay[shadow_y][shadow_x] = Some(*shadow);
                        }
                    }
                }
            }
        }
    }

    pub fn store_tetromino(&mut self, tetromino: &Tetromino) {
        for y in 0..4 {
            for x in 0..4 {
                if let Some(ref block) = tetromino.blocks[y][x] {
                    let x = (tetromino.x + x as i32) as usize;
                    let y = (tetromino.y + y as i32) as usize;

                    if x >= 10 || y >= 22 {
                        continue;
                    }

                    self.boxes[y][x] = Some(*block);
                }
            }
        }
    }

    /// Removes complete lines from the grid
    pub fn remove_complete_lines(&mut self, config: &Config) -> u32 {
        // Pointer to where we're currently writing lines
        let mut y_mut = (config.grid_size.1 - 1) as usize;
        let mut cleared_lines = 0;

        for y in (0..config.grid_size.1).rev() {
            // If every column in this row has a block,
            // we consider it "complete"
            let complete = self.boxes[y as usize].iter().all(|block| block.is_some());

            // If this is not a complete line, copy it
            // into the currently pointed line
            if !complete {
                self.boxes[y_mut] = self.boxes[y as usize];
                y_mut -= 1;
                if y_mut == 0 {
                    break;
                }
            } else {
                cleared_lines += 1;
            }
        }

        cleared_lines
    }

    pub fn render<'a, G, C>(&self, options: &mut RenderOptions<'a, G, C>, e: &Event)
        where C: CharacterCache,
              G: Graphics<Texture = <C as CharacterCache>::Texture>
    {
        let grid_offset = options.config.grid_offset;
        let tile_size = options.config.tile_size;

        // Draw the "border" first
        self.border.draw([(grid_offset - 2.0) as f64,
                          (grid_offset - 2.0) as f64,
                          (tile_size * 10.0 + 4.0) as f64,
                          (tile_size * 20.0 + 4.0) as f64],
                         &Default::default(),
                         options.context.transform,
                         options.graphics);

        for y in 2..22 {
            for x in 0..10 {

                let adjusted_y = y - 2;
                if let Some(ref block) = self.overlay[y][x] {
                    block.render(x, y, options.config, options.context, options.graphics, e);
                    continue;
                }

                match self.boxes[y][x] {
                    Some(ref block) => {
                        block.render(x, y, options.config, options.context, options.graphics, e);
                    }
                    None => {
                        self.block.draw([x as f64 * tile_size + grid_offset,
                                         adjusted_y as f64 * tile_size + grid_offset,
                                         tile_size as f64,
                                         tile_size as f64],
                                        &Default::default(),
                                        options.context.transform,
                                        options.graphics);
                    }
                };
            }
        }
    }
}
<|endoftext|>


<commit_before>use material;
use cgmath::{Vector2, Vector3};
use mesh::{Vertex, Mesh, Model};

pub fn generate_plane(model_material: material::Material) -> Result<Model, String> {
    let mut model = Model::new();
    model.material_list.push(model_material);

    let k = 3.0_f32;
    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(-0.5_f32,  0.5_f32, 0.0_f32),
                    &Vector2::new( 0.0_f32,  1.0_f32 * k),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new( 0.5_f32,  0.5_f32, 0.0_f32),
                    &Vector2::new( 1.0_f32 * k,  1.0_f32 * k),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new( 0.5_f32, -0.5_f32, 0.0_f32),
                    &Vector2::new( 1.0_f32 * k,  0.0_f32),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(-0.5_f32, -0.5_f32, 0.0_f32),
                    &Vector2::new( 0.0_f32,  0.0_f32),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    let mut mesh = Mesh::new();
    mesh.material_id = 0;
    mesh.index_buffer.push(0);
    mesh.index_buffer.push(1);
    mesh.index_buffer.push(2);
    mesh.index_buffer.push(0);
    mesh.index_buffer.push(2);
    mesh.index_buffer.push(3);

    model.mesh_list.push(mesh);

    Ok(model)
}
<commit_msg>add sphere generator<commit_after>use material;
use std::f32;
use cgmath::{Vector2, Vector3, EuclideanVector, rad, sin_cos};
use mesh::{Vertex, Mesh, Model};

pub fn generate_plane(model_material: material::Material) -> Result<Model, String> {
    let mut model = Model::new();
    model.material_list.push(model_material);

    let k = 3.0_f32;
    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(-0.5_f32,  0.5_f32, 0.0_f32),
                    &Vector2::new( 0.0_f32,  1.0_f32 * k),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new( 0.5_f32,  0.5_f32, 0.0_f32),
                    &Vector2::new( 1.0_f32 * k,  1.0_f32 * k),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new( 0.5_f32, -0.5_f32, 0.0_f32),
                    &Vector2::new( 1.0_f32 * k,  0.0_f32),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(-0.5_f32, -0.5_f32, 0.0_f32),
                    &Vector2::new( 0.0_f32,  0.0_f32),
                    &Vector3::new( 0.0_f32,  0.0_f32, 1.0_f32)));

    let mut mesh = Mesh::new();
    mesh.material_id = 0;
    mesh.index_buffer.push(0);
    mesh.index_buffer.push(1);
    mesh.index_buffer.push(2);
    mesh.index_buffer.push(0);
    mesh.index_buffer.push(2);
    mesh.index_buffer.push(3);

    model.mesh_list.push(mesh);

    Ok(model)
}

pub fn generate_sphere(cnt_vertex: usize, model_material: material::Material) -> Result<Model, String> {
    let k = 3.0_f32;
    let mut model = Model::new();
    model.material_list.push(model_material);

	let plg = cnt_vertex / 2 - 1;
	let vertex_cnt = plg * cnt_vertex + 2;

    let mut angle_b = rad(-f32::consts::PI / 2.0_f32);
    let mut ty = 0.0_f32;
	let step_a = rad(f32::consts::PI * 2.0_f32 / (cnt_vertex as f32));
	let step_b = rad(f32::consts::PI / (plg as f32 + 1.0_f32));
	let step_tx = 1.0_f32 / (cnt_vertex as f32);
    let step_ty = 1.0_f32 / (plg as f32 + 1.0_f32);

    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(0.0_f32, -1.0_f32, 0.0_f32),
                    &Vector2::new(0.5_f32 * k,  0.0_f32),
                    &Vector3::new(0.0_f32, -1.0_f32, 0.0_f32)));

    for _ in 0 .. plg {
		angle_b = angle_b + step_b;
        ty += step_ty;
        let (y, radius) = sin_cos(angle_b);

        let mut tx = 0.0_f32;
        let mut angle_a = rad(0.0_f32);
        for _ in 0 .. cnt_vertex {
            let (sin_a, cos_a) = sin_cos(angle_a);
            model.vertex_buffer.push(
                Vertex::new(&Vector3::new(radius * cos_a, y, radius * sin_a),
                            &Vector2::new(tx * k, ty * k),
                            &Vector3::new(radius * cos_a, y, radius * sin_a).normalize()));
            angle_a = angle_a + step_a;
            tx += step_tx;
		}
	}
    model.vertex_buffer.push(
        Vertex::new(&Vector3::new(0.0_f32, 1.0_f32, 0.0_f32),
                    &Vector2::new(0.5_f32 * k, 1.0_f32 * k),
                    &Vector3::new(0.0_f32, 1.0_f32, 0.0_f32)));

    let mut mesh = Mesh::new();
    mesh.material_id = 0;

    for ix in 0 .. (plg-1) {
		let z1 = ix * cnt_vertex + 1;
		let z2 = z1 + cnt_vertex;
		for iy in 0 .. cnt_vertex {
            let iy2 = if iy == (cnt_vertex - 1) {
                0
            } else {
                iy + 1
            };
			mesh.index_buffer.push((z1 + iy)  as u32);
            mesh.index_buffer.push((z2 + iy)  as u32);
            mesh.index_buffer.push((z1 + iy2) as u32);

			mesh.index_buffer.push((z2 + iy2) as u32);
            mesh.index_buffer.push((z1 + iy2) as u32);
            mesh.index_buffer.push((z2 + iy)  as u32);
		}
	}

    let z1 = 1;
    let z2 = vertex_cnt - cnt_vertex - 1;
    for ix in 0 .. cnt_vertex {
        let ix2 = if ix == (cnt_vertex - 1) {
            0
        } else {
            ix + 1
        };
        mesh.index_buffer.push(0 as u32);
        mesh.index_buffer.push((z1 + ix)  as u32);
        mesh.index_buffer.push((z1 + ix2) as u32);

        mesh.index_buffer.push((vertex_cnt - 1) as u32);
        mesh.index_buffer.push((z2 + ix2) as u32);
        mesh.index_buffer.push((z2 + ix) as u32);
    }
    model.mesh_list.push(mesh);

    Ok(model)
}
<|endoftext|>


<commit_before>// (C)opyleft 2013 Frank Denis

/*!
 * Bindings for the GeoIP library
 */
#[desc = "Bindings for the GeoIP library."];
#[license = "BSD"];
#[link(package_id = "geoip", name = "geoip", vers = "0.1")];
#[crate_type = "lib"];

#[warn(non_camel_case_types,
       non_uppercase_statics,
       unnecessary_qualification,
       managed_heap_memory)];

use std::c_str::CString;
use std::io::net::ip::{IpAddr,Ipv4Addr,Ipv6Addr};
use std::libc::{c_void, c_int, c_ulong};

type GeoIP_ = *c_void;
type In6Addr = [u8, ..16];

struct GeoIPLookup {
    netmask: c_int
}

impl GeoIPLookup {
    fn new() -> GeoIPLookup {
        GeoIPLookup {
            netmask: 0
        }
    }
}

#[link_args = "-lGeoIP"]
extern {
    fn GeoIP_open(dbtype: CString, flags: c_int) -> GeoIP_;
    fn GeoIP_delete(db: GeoIP_);
    fn GeoIP_name_by_ipnum_gl(db: GeoIP_, ipnum: c_ulong, gl: &GeoIPLookup) -> CString;
    fn GeoIP_name_by_ipnum_v6_gl(db: GeoIP_, ipnum: In6Addr, gl: &GeoIPLookup) -> CString;
}

pub enum Options {
    Standard = 0,
    MemoryCache = 1,
    CheckCache = 2,
    IndexCache = 4,
    MmapCache = 8
}

pub enum DBType {
    CountryEdition = 1,
    RegionEditionRev0 = 7,
    CityEditionRev0 = 6,
    ORGEdition = 5,
    ISPEdition = 4,
    CityEditionRev1 = 2,
    RegionEditionRev1 = 3,
    ProxyEdition = 8,
    ASNUMEdition = 9,
    NetSpeedEdition = 10,
    DomainEdition = 11,
    CountryEditionV6 = 12,
    LocationAEdition = 13,
    AccuracyRadiusEdition = 14,
    LargeCountryEdition = 17,
    LargeCountryEditionV6 = 18,
    ASNumEditionV6 = 21,
    ISPEditionV6 = 22,
    ORGEditionV6 = 23,
    DomainEditionV6 = 24,
    LoctionAEditionV6 = 25,
    RegistrarEdition = 26,
    RegistrarEditionV6 = 27,
    UserTypeEdition = 28,
    UserTypeEditionV6 = 29,
    CityEditionRev1V6 = 30,
    CityEditionRev0V6 = 31,
    NetSpeedEditionRev1 = 32,
    NetSpeedEditionRev1V6 = 33,
    CountryConfEdition = 34,
    CityConfEdition = 35,
    RegionConfEdition = 36,
    PostalConfEdition = 37,
    AccuracyRadiusEditionV6 = 38
}

pub struct GeoIP {
    priv db: GeoIP_
}

pub struct ASInfo {
    asn: uint,
    name: ~str,
    netmask: uint
}

impl ToStr for ASInfo {
    fn to_str(&self) -> ~str {
        format!("{}\t{}", self.asn, self.name)
    }
}

impl GeoIP {
    pub fn open(path: &Path, options: Options) -> Result<GeoIP, ~str> {
        let file = match path.as_str() {
            None => return Err(format!("Invalid path {}", path.display())),
            Some(file) => file
        };
        let db = unsafe {
            GeoIP_open(file.to_c_str(), options as c_int)
        };
        match db.is_null() {
            true => Err(format!("Can't open {}", file)),
            false => Ok(GeoIP {
                    db: db
                })
        }
    }

    pub fn as_info_by_ip(&self, ip: IpAddr) -> Option<ASInfo> {
        let gl = GeoIPLookup::new();
        let cres = match ip {
            Ipv4Addr(a, b, c, d) => {
                let ipnum: c_ulong =
                    (a as c_ulong << 24) | (b as c_ulong << 16) |
                    (c as c_ulong << 8)  | (d as c_ulong);
                unsafe {
                    GeoIP_name_by_ipnum_gl(self.db, ipnum, &gl)
                }
            },
            Ipv6Addr(a, b, c, d, e, f, g, h) => {
                let in6_addr: In6Addr = [(a >> 8) as u8, a as u8,
                                         (b >> 8) as u8, b as u8,
                                         (c >> 8) as u8, c as u8,
                                         (d >> 8) as u8, d as u8,
                                         (e >> 8) as u8, e as u8,
                                         (f >> 8) as u8, f as u8,
                                         (g >> 8) as u8, g as u8,
                                         (h >> 8) as u8, h as u8];
                unsafe {
                    GeoIP_name_by_ipnum_v6_gl(self.db, in6_addr, &gl)
                }
            }
        };
        if cres.is_null() {
            return None;
        }
        let description = match cres.as_str() {
            None => return None,
            Some(description) => description
        };
        let mut di = description.splitn(' ', 1);
        let asn = match di.next() {
            None => return None,
            Some(asn) => {
                if ! asn.starts_with("AS") {
                    return None
                } else {
                    from_str::<uint>(asn.slice_from(2)).unwrap()
                }
            }
        };
        let name = di.next().unwrap_or("(none)");
        let asinfo = ASInfo {
            asn: asn,
            name: name.to_owned(),
            netmask: gl.netmask as uint
        };
        Some(asinfo)
    }
}

impl Drop for GeoIP {
    fn drop(&mut self) {
        unsafe {
            GeoIP_delete(self.db);
        }
    }
}

#[test]
fn geoip_test_basic() {
    let geoip = match GeoIP::open(~from_str("/opt/geoip/GeoIPASNum.dat").unwrap(), MemoryCache) {
        Err(err) => fail!(err),
        Ok(geoip) => geoip
    };
    let ip = from_str("91.203.184.192").unwrap();
    let res = geoip.as_info_by_ip(ip).unwrap();
    assert!(res.asn == 41064);
    assert!(res.name.contains("Telefun"));
    assert!(res.netmask == 22);
}
<commit_msg>Rust -master compat<commit_after>// (C)opyleft 2013 Frank Denis

/*!
 * Bindings for the GeoIP library
 */
#[desc = "Bindings for the GeoIP library."];
#[license = "BSD"];
#[link(package_id = "geoip", name = "geoip", vers = "0.1")];
#[crate_type = "lib"];

#[warn(non_camel_case_types,
       non_uppercase_statics,
       unnecessary_qualification,
       managed_heap_memory)];

use std::c_str::CString;
use std::io::net::ip::{IpAddr,Ipv4Addr,Ipv6Addr};
use std::libc::{c_void, c_int, c_ulong};

type GeoIP_ = *c_void;
type In6Addr = [u8, ..16];

struct GeoIPLookup {
    netmask: c_int
}

impl GeoIPLookup {
    fn new() -> GeoIPLookup {
        GeoIPLookup {
            netmask: 0
        }
    }
}

#[link(name = "GeoIP")]
extern {
    fn GeoIP_open(dbtype: CString, flags: c_int) -> GeoIP_;
    fn GeoIP_delete(db: GeoIP_);
    fn GeoIP_name_by_ipnum_gl(db: GeoIP_, ipnum: c_ulong, gl: &GeoIPLookup) -> CString;
    fn GeoIP_name_by_ipnum_v6_gl(db: GeoIP_, ipnum: In6Addr, gl: &GeoIPLookup) -> CString;
}

pub enum Options {
    Standard = 0,
    MemoryCache = 1,
    CheckCache = 2,
    IndexCache = 4,
    MmapCache = 8
}

pub enum DBType {
    CountryEdition = 1,
    RegionEditionRev0 = 7,
    CityEditionRev0 = 6,
    ORGEdition = 5,
    ISPEdition = 4,
    CityEditionRev1 = 2,
    RegionEditionRev1 = 3,
    ProxyEdition = 8,
    ASNUMEdition = 9,
    NetSpeedEdition = 10,
    DomainEdition = 11,
    CountryEditionV6 = 12,
    LocationAEdition = 13,
    AccuracyRadiusEdition = 14,
    LargeCountryEdition = 17,
    LargeCountryEditionV6 = 18,
    ASNumEditionV6 = 21,
    ISPEditionV6 = 22,
    ORGEditionV6 = 23,
    DomainEditionV6 = 24,
    LoctionAEditionV6 = 25,
    RegistrarEdition = 26,
    RegistrarEditionV6 = 27,
    UserTypeEdition = 28,
    UserTypeEditionV6 = 29,
    CityEditionRev1V6 = 30,
    CityEditionRev0V6 = 31,
    NetSpeedEditionRev1 = 32,
    NetSpeedEditionRev1V6 = 33,
    CountryConfEdition = 34,
    CityConfEdition = 35,
    RegionConfEdition = 36,
    PostalConfEdition = 37,
    AccuracyRadiusEditionV6 = 38
}

pub struct GeoIP {
    priv db: GeoIP_
}

pub struct ASInfo {
    asn: uint,
    name: ~str,
    netmask: uint
}

impl ToStr for ASInfo {
    fn to_str(&self) -> ~str {
        format!("{}\t{}", self.asn, self.name)
    }
}

impl GeoIP {
    pub fn open(path: &Path, options: Options) -> Result<GeoIP, ~str> {
        let file = match path.as_str() {
            None => return Err(format!("Invalid path {}", path.display())),
            Some(file) => file
        };
        let db = unsafe {
            GeoIP_open(file.to_c_str(), options as c_int)
        };
        match db.is_null() {
            true => Err(format!("Can't open {}", file)),
            false => Ok(GeoIP {
                    db: db
                })
        }
    }

    pub fn as_info_by_ip(&self, ip: IpAddr) -> Option<ASInfo> {
        let gl = GeoIPLookup::new();
        let cres = match ip {
            Ipv4Addr(a, b, c, d) => {
                let ipnum: c_ulong =
                    (a as c_ulong << 24) | (b as c_ulong << 16) |
                    (c as c_ulong << 8)  | (d as c_ulong);
                unsafe {
                    GeoIP_name_by_ipnum_gl(self.db, ipnum, &gl)
                }
            },
            Ipv6Addr(a, b, c, d, e, f, g, h) => {
                let in6_addr: In6Addr = [(a >> 8) as u8, a as u8,
                                         (b >> 8) as u8, b as u8,
                                         (c >> 8) as u8, c as u8,
                                         (d >> 8) as u8, d as u8,
                                         (e >> 8) as u8, e as u8,
                                         (f >> 8) as u8, f as u8,
                                         (g >> 8) as u8, g as u8,
                                         (h >> 8) as u8, h as u8];
                unsafe {
                    GeoIP_name_by_ipnum_v6_gl(self.db, in6_addr, &gl)
                }
            }
        };
        if cres.is_null() {
            return None;
        }
        let description = match cres.as_str() {
            None => return None,
            Some(description) => description
        };
        let mut di = description.splitn(' ', 1);
        let asn = match di.next() {
            None => return None,
            Some(asn) => {
                if ! asn.starts_with("AS") {
                    return None
                } else {
                    from_str::<uint>(asn.slice_from(2)).unwrap()
                }
            }
        };
        let name = di.next().unwrap_or("(none)");
        let asinfo = ASInfo {
            asn: asn,
            name: name.to_owned(),
            netmask: gl.netmask as uint
        };
        Some(asinfo)
    }
}

impl Drop for GeoIP {
    fn drop(&mut self) {
        unsafe {
            GeoIP_delete(self.db);
        }
    }
}

#[test]
fn geoip_test_basic() {
    let geoip = match GeoIP::open(&from_str("/opt/geoip/GeoIPASNum.dat").unwrap(), MemoryCache) {
        Err(err) => fail!(err),
        Ok(geoip) => geoip
    };
    let ip = from_str("91.203.184.192").unwrap();
    let res = geoip.as_info_by_ip(ip).unwrap();
    assert!(res.asn == 41064);
    assert!(res.name.contains("Telefun"));
    assert!(res.netmask == 22);
}
<|endoftext|>