1
0
mirror of git://projects.qi-hardware.com/cae-tools.git synced 2024-12-23 09:28:58 +02:00
cae-tools/cameo/stl.c
Werner Almesberger c5f54df4a0 cameo/stl.c: generate real STL (WIP)
Some facets look funny in Meshlab although it shows all the normals pointing
in the right direction.
2013-10-14 12:32:27 -03:00

100 lines
2.1 KiB
C

/*
* stl.c - Genererate STL slice from polygon set
*
* Written 2013 by Werner Almesberger
* Copyright 2013 Werner Almesberger
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "poly2d.h"
#include "path.h"
#include "stl.h"
static void facet(FILE *file, const struct f2d *f, int a, int b, int c,
double za, double zb, double zc, double nx, double ny, double nz)
{
double d;
d = sqrt(nx*nx+ny*ny+nz*nz);
if (!d)
d = 1;
fprintf(file, "facet normal %e %e %e\n", nx/d, ny/d, nz/d);
fprintf(file, "\touter loop\n");
fprintf(file, "\t\tvertex %e %e %e\n", f->x[a], f->y[a], za);
fprintf(file, "\t\tvertex %e %e %e\n", f->x[b], f->y[b], zb);
fprintf(file, "\t\tvertex %e %e %e\n", f->x[c], f->y[c], zc);
fprintf(file, "\tendloop\n");
fprintf(file, "endfacet\n");
}
static void surface(FILE *file, const struct f2d *f)
{
facet(file, f, 0, 1, 2, 1, 1, 1, 0, 0, 1);
facet(file, f, 2, 1, 0, 0, 0, 0, 0, 0, -1);
}
static void side(FILE *file, const struct f2d *f, int a, int b)
{
double nx, ny;
nx = f->y[b]-f->y[a];
ny = f->x[a]-f->x[b];
facet(file, f, a, b, b, 0, 0, 1, nx, ny, 0);
facet(file, f, b, a, a, 1, 1, 0, nx, ny, 0);
}
static void stl_write(FILE *file, const struct path *paths)
{
struct p2d *polys;
struct f2d *faces;
const struct f2d *f;
int i;
fprintf(file, "solid cameo\n");
polys = paths_to_polys(paths);
faces = f2d_tri(polys);
for (f = faces; f; f = f->next) {
surface(file, f);
for (i = 0; i != 3; i++)
if (f->side[i])
side(file, f, i, (i+1) % 3);
}
p2d_free_all(polys);
f2d_free_all(faces);
fprintf(file, "endsolid cameo\n");
}
void stl(const char *name, const struct path *paths)
{
FILE *file = stdout;
if (name) {
file = fopen(name, "w");
if (!file) {
perror(name);
exit(1);
}
}
stl_write(file, paths);
if (name && fclose(file)) {
perror(name);
exit(1);
}
}