Giter Site home page Giter Site logo

cubic_spline's Introduction

cubic_spline

Crates.io npm

Interpolation method for computation of cubic spline points within the range of a discrete set of known points.

Online documentation
Demo

example

Example

use cubic_spline::{Points, Point, SplineOpts, TryFrom};


fn main() {
  let source = vec![(10.0, 200.0), (256.0, 390.0), (512.0, 10.0), (778.0, 200.0)];
  
  let opts = SplineOpts::new()
    .tension(0.5);
  
  let mut points = Points::try_from(&source).expect("expect valid points but");
  let result = points.calc_spline(&opts).expect("cant construct spline points");
  
  assert_eq!(result.get_ref().len(), 49);
  
  let inner_vec: &mut Vec<Point> = points.get_mut();
  inner_vec.push(Point::new(7.7, 1.3));
  inner_vec[1].x += 0.79;
  inner_vec.last_mut().iter_mut().for_each(|mut p| {p.tension = Some(0.7);});
  
  points.invert_vertically(400.0);
  
  assert_eq!(points.get_ref()[1].y, 10.0);
  
  let calculated_points = points
    .calc_spline(&opts.num_of_segments(33))
    .unwrap();
  
  assert_eq!(calculated_points.into_inner().len(), 133);

}

For information on how a curve can be constructed and which points to accept, see the appropriate structures.

Custom points

If you already have some points you can implement From trait for Point struct and pass your points directly.

Example

use cubic_spline::{SplineOpts, Point, Points};

#[derive(Default)]
struct MyPoint {
  vertical: u8,
  horizontal: u8,
  color: String,
}

impl<'a> From<&'a MyPoint> for Point {
  fn from(p: &'a MyPoint) -> Self {
    Point::new(&p.horizontal as f64, &p.vertical as f64)
  }
}

fn main() {
  let my_points: Vec<MyPoint> = vec![MyPoint::default(),MyPoint::default()];
  let spline = Points::from(&my_points)
    .calc_spline(&SplineOpts::default())
    .unwrap();
  
  assert_eq!(spline.get_ref().len(), 17);
}

Use in Javascript

It also compiled as wasm module. And you can use it in your js code but not completely. Now available only one function

import { getCurvePoints } from 'cubic-spline-rs'

const NUM_OF_SEGMENTS = 22

const points = [10.0, 200.0, 256.0, 390.0, 512.0, 10.0, 778.0, 200.0]

const curvePoints = getCurvePoints( points, {
  num_of_segments: NUM_OF_SEGMENTS, // *optional
  // tension: 0.5, // *optional
  // ...  
} )

If you want to draw result points to canvas - code like this:

const ctx = getMyCanvas2DContext()

ctx.beginPath()
ctx.lineWidth = 3
ctx.strokeStyle = '#ffcc00'

ctx.moveTo(curvePoints[0], curvePoints[1])
const length = curvePoints.length - 1
for (let i = 2; i < length; i += 2) {
  ctx.lineTo(curvePoints[i], curvePoints[i + 1])
}

ctx.stroke()
ctx.closePath()

Options

Name Type Default Description
tension f64 0.5 Tension
num_of_segments u32 16 Number of calculated points between known points
hidden_point_at_start Option<(f64,f64)> None A point that will not be drawn, but the beginning of the graph will bend as if it is there.
hidden_point_at_end Option<(f64,f64)> None A point that will not be drawn, but the end of the graph will bend as if it is there.
use cubic_spline::{SplineOpts};

fn main() {
  let options = SplineOpts::new()
    .tension(0.6)
    .num_of_segments(54)
    // .hidden_point_at_start((1.2, 3.1))
    // .hidden_point_at_end((397.9, 105.5))
    ;

}

License

This module is MIT licensed.

cubic_spline's People

Contributors

emgyrz avatar minecrawler avatar

Stargazers

 avatar José Luis Cruz avatar  avatar Moritz Mœller avatar Kohei Shinohara avatar  avatar Elena avatar  avatar  avatar  avatar

Watchers

James Cloos avatar  avatar  avatar

cubic_spline's Issues

Tension per vertex

Could support for specifying tension per vertex be added?
I'm using this crate to draw splines for some UI widget the user manipulates and I need to support a case where a single vertex is either smooth or hard (discontinuous).

Set a rational ratio between initial frequency anf final frequency

Would it be possible to have a rational sample frequency ratio between the finals points and the initials points? for example, now if I want a 3/2 ratio I have to set the variable "num_of_segments" at 2 to multiply the sample frequency by 3 and then only save one point every 2 points to get a 3/2 sample frequency ratio. It's work fine but points I don't need are calculated so it's is not very efficient in this use case.
The idea would be to only calculate the needed points in the case of a rational ratio.

circular cubic spline

For my application, I need the spline to form a closed graph. The last point should connect back to the first one and form a smooth figure. For example, let's say I define two points, then I would want to call a method so that a circle is calculated from it. More points would work, too, but then form an abstract form.

At the moment, this is not possible from what I see. There are 4 points defined, however they form a hard corner (at the top).
image
image

Would this be feasible and in scope of this library? Unfortunately, my math is a bit rusty, so it would be hard for me to contribute without doing quiet a bit of research first :/

cubic_spline redefines Result in the crate root.

Aka, if a user imports the crate like this, for convenience:

use cubic_spline::*;

Their Result type is tainted. So if they have code that assumes std::result::Result that code breaks then with sth. like:

error[E0107]: wrong number of type arguments: expected 1, found 2
   --> src/foo.rs:42:13
    |
 42 | ) -> Result<(), Box<dyn std::error::Error>> {
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ unexpected type argument

The reason is that it is in cubic_spline::Result.
A redefined std type It should be behind a module namespace. E.g. cubic_spline::err::Result.

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.