/* See mtv_valve_helical_connector_make.h */
/* Last edited on 2016-04-21 21:30:54 by stolfilocal */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>

#include <bool.h>
#include <r3.h>
#include <r3_path.h>
#include <affirm.h>
#include <ppv_array.h>

#include <voxm_path.h>
#include <voxm_splat_tube.h>

#include <mtv_valve_helical_connector_make.h>

void mtv_valve_helical_connector_make
  ( ppv_array_t *a, 
    r3_t *ctr, 
    r3_path_state_t *S,
    int dir,
    double endZ,
    double inR, 
    double otR, 
    double fuzzR,
    bool_t sub,
    r3_path_state_t *T /* (OUT) State at end of connecting tube. */
  )
  {
    /* Make final state: */
    T->p = (*ctr);
    T->p.c[2] = endZ;
    r3_t TU; r3_axis(2, &TU);
    r3_t TV; r3_axis(0, &TV);
    r3_t TW; r3_axis(1, &TW);
    r3x3_from_rows(&TU, &TV, &TW, &(T->M));
    
    /* Pick starting state {R0} and final state {R1}: */
    r3_path_state_t *R0 = (dir > 0 ? S  : T);
    r3_path_state_t *R1 = (dir > 0 ? T  : S);

    /* Convert to {voxm_path_state_t}: */
    double L = 2.0 * r3_dist(&(S->p), &(T->p)); /* Estimated length of tube. */
    voxm_path_state_t V0 = voxm_path_state_from_r3_path_state(0.0, R0, L);
    voxm_path_state_t V1 = voxm_path_state_from_r3_path_state(1.0, R1, L);
    
    /* Splat the tube: */
    voxm_splat_tube_round_segment(a, &V0, &V1, inR, otR, fuzzR, sub);
  }
