2 * We try to find an optimal triangle grid
9 static void compute_vertex_areas(const Vertices vertices, double areas[N]);
10 static double best_energy= DBL_MAX;
12 static void addcost(double *energy, double tweight, double tcost, int pr);
13 #define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
15 /*---------- main energy computation and subroutines ----------*/
17 double compute_energy(const struct Vertices *vs) {
18 double vertex_areas[N], energy;
21 compute_vertex_areas(vs->a, vertex_areas);
24 printing= printing_check(pr_cost);
26 if (printing) printf("cost > energy |");
28 COST(1e2, edgewise_vertex_displacement_cost(vs->a));
29 COST(1e2, graph_layout_cost(vs->a,vertex_areas));
30 // COST(1e4, noncircular_rim_cost(vs->a));
32 if (printing) printf("| total %# e |", energy);
34 if (energy < best_energy) {
38 if (printing) printf(" BEST");
40 best_f= fopen(output_file_tmp,"wb"); if (!best_f) diee("fopen new out");
41 r= fwrite(vs->a,sizeof(vs->a),1,best_f); if (r!=1) diee("fwrite");
42 if (fclose(best_f)) diee("fclose new best");
43 if (rename(output_file_tmp,output_file)) diee("rename install new best");
55 static void addcost(double *energy, double tweight, double tcost, int pr) {
56 double tenergy= tweight * tcost;
57 if (pr) printf(" %# e > %# e |", tcost, tenergy);
61 static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
62 int v0,v1,v2, e1,e2, k;
73 double e1v[D3], e2v[D3], av[D3];
75 e1v[k]= vertices[v1][k] - vertices[v0][k];
76 e2v[k]= vertices[v2][k] - vertices[v0][k];
82 areas[v0]= total / count;
86 /*---------- Edgewise vertex displacement ----------*/
104 * Let delta = 180deg - angle RMS
109 * Giving energy contribution:
117 * (The dimensions of this are those of F_vd.)
119 * We calculate delta as atan2(|AxB|, A.B)
120 * where A = PQ, B = QR
122 * In practice to avoid division by zero we'll add epsilon to d and
123 * |AxB| and the huge energy ought then to be sufficient for the
124 * model to avoid being close to R=S.
127 double edgewise_vertex_displacement_cost(const Vertices vertices) {
128 static const double axb_epsilon= 1e-6;
130 int pi,e,qi,ri, k; //,si
131 double a[D3], b[D3], axb[D3]; //m[D3],
132 double total_cost= 0;
135 pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
137 // K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
138 K a[k]= -vertices[pi][k] + vertices[qi][k];
139 K b[k]= -vertices[qi][k] + vertices[ri][k];
143 double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
144 double cost= pow(delta,3);
146 if (!e && !(qi & YMASK))
154 /*---------- noncircular rim cost ----------*/
156 double noncircular_rim_cost(const Vertices vertices) {
160 FOR_RIM_VERTEX(vy,vx,v) {
162 /* By symmetry, nearest point on circle is the one with
163 * the same angle subtended at the z axis. */
164 oncircle[0]= vertices[v][0];
165 oncircle[1]= vertices[v][1];
167 double mult= 1.0/ magnD(oncircle);
170 double d2= hypotD2(vertices[v], oncircle);