Date:2013-10-14 17:32:27 (10 years 5 months ago)
Author:Werner Almesberger
Commit:c5f54df4a0a586ecaab951667b5c3838437aea96
Message:cameo/stl.c: generate real STL (WIP)

Some facets look funny in Meshlab although it shows all the normals pointing
in the right direction.
Files: cameo/stl.c (2 diffs)

Change Details

cameo/stl.c
1111 */
1212
1313
14#include <stdlib.h>
1415#include <stdio.h>
16#include <math.h>
1517
1618#include "poly2d.h"
1719
...... 
1921#include "stl.h"
2022
2123
22void stl(const char *name, const struct path *paths)
24static void facet(FILE *file, const struct f2d *f, int a, int b, int c,
25    double za, double zb, double zc, double nx, double ny, double nz)
26{
27    double d;
28
29    d = sqrt(nx*nx+ny*ny+nz*nz);
30    if (!d)
31        d = 1;
32
33    fprintf(file, "facet normal %e %e %e\n", nx/d, ny/d, nz/d);
34    fprintf(file, "\touter loop\n");
35    fprintf(file, "\t\tvertex %e %e %e\n", f->x[a], f->y[a], za);
36    fprintf(file, "\t\tvertex %e %e %e\n", f->x[b], f->y[b], zb);
37    fprintf(file, "\t\tvertex %e %e %e\n", f->x[c], f->y[c], zc);
38    fprintf(file, "\tendloop\n");
39    fprintf(file, "endfacet\n");
40}
41
42
43static void surface(FILE *file, const struct f2d *f)
44{
45    facet(file, f, 0, 1, 2, 1, 1, 1, 0, 0, 1);
46    facet(file, f, 2, 1, 0, 0, 0, 0, 0, 0, -1);
47}
48
49
50static void side(FILE *file, const struct f2d *f, int a, int b)
51{
52    double nx, ny;
53
54    nx = f->y[b]-f->y[a];
55    ny = f->x[a]-f->x[b];
56    facet(file, f, a, b, b, 0, 0, 1, nx, ny, 0);
57    facet(file, f, b, a, a, 1, 1, 0, nx, ny, 0);
58}
59
60
61static void stl_write(FILE *file, const struct path *paths)
2362{
2463    struct p2d *polys;
2564    struct f2d *faces;
2665    const struct f2d *f;
66    int i;
2767
68    fprintf(file, "solid cameo\n");
2869    polys = paths_to_polys(paths);
2970    faces = f2d_tri(polys);
30    for (f = faces; f; f = f->next)
31        printf("%f/%f %f/%f %f/%f (%d %d %d)\n",
32            f->x[0], f->y[0],
33            f->x[1], f->y[1],
34            f->x[2], f->y[2],
35            f->side[0], f->side[1], f->side[2]);
71    for (f = faces; f; f = f->next) {
72        surface(file, f);
73        for (i = 0; i != 3; i++)
74            if (f->side[i])
75                side(file, f, i, (i+1) % 3);
76    }
3677    p2d_free_all(polys);
3778    f2d_free_all(faces);
79    fprintf(file, "endsolid cameo\n");
80}
81
82
83void stl(const char *name, const struct path *paths)
84{
85    FILE *file = stdout;
86
87    if (name) {
88        file = fopen(name, "w");
89        if (!file) {
90            perror(name);
91            exit(1);
92        }
93    }
94    stl_write(file, paths);
95    if (name && fclose(file)) {
96        perror(name);
97        exit(1);
98    }
3899}

Archive Download the corresponding diff file

Branches:
master



interactive