F. 有向線分 (矢印) の描画


/*
 * arrow.c --- 有向線分の描画
 */

#include <stdio.h>
#include <math.h>
#define G_DOUBLE
#include <glsc.h>

/* ------------------------------------------------------------- */

/* π, 度とラジアンの換算用の比 */
double arrow_pi, arrow_degree;
int arrow_initialized = 0;

void init_arrow()
{
  arrow_initialized = 1;
  arrow_pi = 4 * atan(1.0); arrow_degree = arrow_pi / 180.0;
}

/* 有向線分(矢印のある線分)を描く */
void arrow(double p1, double p2,
           double q1, double q2,
           double lambda)
{
  double e1, e2, norm;
  double fl1, fl2, fu1, fu2, theta, cost, sint;
  double qu1, qu2, ql1, ql2, r1, r2, t;
  double phi;
  double vx[5], vy[5];
  int fill;

  if (!arrow_initialized)
    init_arrow();
  /* */
  theta = 15.0 * arrow_degree; phi = 30.0 * arrow_degree;
  /* e=(p-q)/||p-q|| */
  e1 = p1 - q1; e2 = p2 - q2; norm = hypot(e1, e2);
  e1 /= norm; e2 /= norm;
  /* fl = λ R(θ) e */
  cost = cos(theta); sint = sin(theta);
  fl1 = lambda * (cost * e1 - sint * e2);
  fl2 = lambda * (sint * e1 + cost * e2);
  /* fu = λ R(-θ) e */
  fu1 = lambda * (  cost * e1 + sint * e2);
  fu2 = lambda * (- sint * e1 + cost * e2);
  /* ql = q + fl */
  ql1 = q1 + fl1; ql2 = q2 + fl2;
  /* qu = q + fu */
  qu1 = q1 + fu1; qu2 = q2 + fu2;
  /* r = q + λ cosθ(1-tanθ/tanφ)e */
  t = lambda * cost * (1 - tan(theta) / tan(phi));
  r1 = q1 + t * e1; r2 = q2 + t * e2;
  /* */
  vx[0] = q1; vy[0] = q2;
  vx[1] = qu1; vy[1] = qu2;
  vx[2] = r1;  vy[2] = r2;
  vx[3] = ql1; vy[3] = ql2;
  vx[4] = q1;  vy[4] = q2;
  g_sel_area(0);
  fill = G_YES;
  /* */
  g_move(p1, p2); g_plot(r1, r2);
  g_polygon(vx, vy, 5, G_NO, fill);
}

/* ------------------------------------------------------------- */

int main()
{
  g_init("META", 220.0, 220.0);
  g_device(G_BOTH);
  g_def_scale(0,
              -1.0, 5.0, -1.0, 5.0,
              10.0, 10.0, 200.0, 200.0);
  g_sel_scale(0);
  /* arrow のために必要 */
  g_def_area(0, G_BLACK);

  g_def_line(0, G_BLACK, 3, G_LINE_SOLID);
  g_sel_line(0);

  arrow(1.0, 1.0, 4.0, 1.0, 0.8);
  g_sleep(-1.0);
  g_term();
  return 0;
}



桂田 祐史