Subversion Repositories gelsvn

Rev

Rev 394 | Rev 399 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
386 jab 1
/*
2
 *  MeshEdit is a small application which allows you to load and edit a mesh.
3
 *  The mesh will be stored in GEL's half edge based Manifold data structure.
4
 *  A number of editing operations are supported. Most of these are accessible from the 
5
 *  console that pops up when you hit 'esc'.
6
 *
7
 *  Created by J. Andreas Bærentzen on 15/08/08.
8
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
9
 *
10
 */
11
#include <iostream>
12
#include <CGLA/eigensolution.h>
13
#include <CGLA/Vec2d.h>
14
#include <CGLA/Vec3d.h>
15
#include <CGLA/Mat3x3d.h>
16
#include <CGLA/Mat2x2d.h>
17
#include <CGLA/Mat2x3d.h>
18
 
19
#include <LinAlg/Matrix.h>
20
#include <LinAlg/Vector.h>
21
#include <LinAlg/LapackFunc.h>
22
 
23
#include <Util/Timer.h>
24
#include <Util/ArgExtracter.h>
25
 
26
#include <GL/glew.h>
27
#include <GLGraphics/gel_glut.h>
28
#include <GLGraphics/draw.h>
397 jab 29
#include <GLGraphics/IDBufferWireFrameRenderer.h>
386 jab 30
#include <GLGraphics/glsl_shader.h>
31
#include <GLGraphics/GLViewController.h>
32
 
33
#include <HMesh/Manifold.h>
34
#include <HMesh/VertexCirculator.h>
35
#include <HMesh/FaceCirculator.h>
36
#include <HMesh/build_manifold.h>
37
#include <HMesh/mesh_optimization.h>
38
#include <HMesh/triangulate.h>
39
#include <HMesh/load.h>
387 jab 40
#include <HMesh/quadric_simplify.h>
41
#include <HMesh/smooth.h>
386 jab 42
#include <HMesh/x3d_save.h>
388 jab 43
#include <HMesh/obj_save.h>
387 jab 44
#include <HMesh/mesh_optimization.h>
388 jab 45
#include <HMesh/triangulate.h>
46
#include <HMesh/close_holes.h>
47
#include <HMesh/caps_and_needles.h>
48
#include <HMesh/refine_edges.h>
49
#include <HMesh/subdivision.h>
386 jab 50
 
51
#include <GLConsole/GLConsole.h>
394 jab 52
#include <Util/Timer.h>
386 jab 53
#include "harmonics.h"
54
#include "wireframe.h"
55
 
391 jab 56
using namespace std;
57
using namespace HMesh;
58
using namespace Geometry;
59
using namespace GLGraphics;
60
using namespace CGLA;
61
using namespace Util;
62
using namespace LinAlg;
386 jab 63
 
391 jab 64
int WINX=800, WINY=800;
65
 
397 jab 66
template<typename T>
67
T& get_CVar_ref(const std::string& s)
68
{
69
	return *reinterpret_cast<T*> (GetCVarData(s));
70
}
71
 
72
int maximum_face_valency(HMesh::Manifold& m)
73
{
74
	int max_val = 0;
75
	for(FaceIter f = m.faces_begin(); f != m.faces_end(); ++f)
76
		max_val = max(max_val, no_edges(f));
77
    return max_val;
78
}
79
 
391 jab 80
class VisObj
81
{
82
	string file;
83
	GLViewController view_ctrl;
84
	GLuint display_list;
85
	bool create_display_list;
86
	Manifold mani;
87
	Harmonics* harmonics;
397 jab 88
	IDBufferWireframeRenderer* idbuff_renderer;
391 jab 89
 
90
public:
91
 
92
	Manifold& mesh() {return mani;}
93
	GLViewController& view_control() {return view_ctrl;}
94
 
95
	bool reload(string _file)
96
	{
97
		if(_file != "") file = _file;
98
		mani.clear();
99
		if(!load(file, mani))
100
			return false;
101
		Vec3f c(0,0,0);
102
		float r = 5;
103
		mani.get_bsphere(c,r);
104
		view_ctrl.set_centre(c);
105
		view_ctrl.set_eye_dist(2*r);
106
		return true;
107
	}
108
 
109
	VisObj():
397 jab 110
	file(""), view_ctrl(WINX,WINY, Vec3f(0), 1.0), display_list(glGenLists(1)), create_display_list(true), harmonics(0),
111
	idbuff_renderer(0)
391 jab 112
	{
113
	}
114
 
115
	void display(bool wire, bool harm, bool flat)
116
	{
117
		if(create_display_list)
118
		{
119
			create_display_list = false;
120
 
121
			glNewList(display_list,GL_COMPILE);
122
			if(wire)
123
			{
397 jab 124
				if(idbuff_renderer)
125
				{
126
					delete idbuff_renderer;
127
					idbuff_renderer = 0;
128
				}
129
				if(GLEW_EXT_geometry_shader4)
130
				   {
131
					if(maximum_face_valency(mani) > 3)
132
						idbuff_renderer = new IDBufferWireframeRenderer(WINX, WINY, mani);
133
					else
134
						draw_triangles_in_wireframe(mani,!get_CVar_ref<int>("display.flatshading"), Vec3f(1,0,0));
135
				   }
136
				else
137
				   draw_wireframe_oldfashioned(mani,!get_CVar_ref<int>("display.flatshading"), Vec3f(1,0,0));
391 jab 138
			}
139
			else if(harm)
140
				harmonics->draw();
141
			else 
142
				draw(mani,!flat);
143
			glEndList();
144
		}
145
		view_ctrl.set_gl_modelview();
397 jab 146
		if(wire && idbuff_renderer != 0)
147
			idbuff_renderer->draw(Vec3f(1,0,0),Vec3f(0.5)); 
391 jab 148
		glCallList(display_list);
149
	}
150
 
151
 
152
	void post_create_display_list()
153
	{
154
		create_display_list = true;
155
	}
156
 
157
	void harmonics_analyze_mesh()
158
	{
159
		delete harmonics;
160
		harmonics = new Harmonics(mani);
161
	}
162
 
163
	void harmonics_reset_shape()
164
	{
165
		if(harmonics)
166
			harmonics->reset_shape();
167
	}
168
 
169
	void harmonics_parse_key(unsigned char key)
170
	{
171
		harmonics->parse_key(key);
172
	}
173
 
174
	void harmonics_partial_reconstruct(int eig0, int eig1, float scale)
175
	{
176
		if(harmonics)
177
			harmonics->partial_reconstruct(eig0, eig1, scale);
178
	}
179
 
180
};
181
 
182
inline VisObj& get_vis_obj(int i)
183
{
184
	static VisObj vo[9];
185
	return vo[i];
186
}
187
 
188
inline VisObj& avo()
189
{
190
	static CVar<int> active("active_mesh",0);
191
	return get_vis_obj(active);
192
}
193
 
194
inline Manifold& active_mesh()
195
{
196
	return avo().mesh();
197
}
198
 
199
inline GLViewController& active_view_control()
200
{
201
	return avo().view_control();
202
}
203
 
386 jab 204
// Single global instance so glut can get access
205
GLConsole theConsole;
206
 
207
////////////////////////////////////////////////////////////////////////////////
208
char* ConsoleHelp(std::vector<std::string> &args)
209
{
210
    theConsole.Printf("");
211
    theConsole.Printf("----------------- HELP -----------------");
391 jab 212
    theConsole.Printf("Press ESC key to open and close console");
386 jab 213
    theConsole.Printf("Press TAB to see the available commands and functions");
214
    theConsole.Printf("Functions are shown in green and variables in yellow");
215
    theConsole.Printf("Setting a value: [command] = value");
216
    theConsole.Printf("Getting a value: [command]");
217
    theConsole.Printf("Functions: [function] [arg1] [arg2] ...");
391 jab 218
    theConsole.Printf("Entering arg1=? or arg1=help will give a description.");
386 jab 219
    theConsole.Printf("History: Up and Down arrow keys move through history.");
220
    theConsole.Printf("Tab Completion: TAB does tab completion and makes suggestions.");
391 jab 221
    theConsole.Printf("");
222
    theConsole.Printf("Keyboard commands (when console is not active):");
223
    theConsole.Printf("w   : toggle wireframe");
224
    theConsole.Printf("f   : toggle flatshading");
225
    theConsole.Printf("1-9 : switch between active meshes.");
394 jab 226
    theConsole.Printf("d   : (display.show_harmonics = 1) diffuse light on and off");
227
    theConsole.Printf("h   : (display.show_harmonics = 1) highlight on and off ");
228
    theConsole.Printf("+/- : (display.show_harmonics = 1) which eigenvector to show");
391 jab 229
    theConsole.Printf("q   : quit program");
230
    theConsole.Printf("ESC : open console");
231
    theConsole.Printf("");
232
    theConsole.Printf("Mouse: Left button rotates, middle zooms, right pans");
386 jab 233
    theConsole.Printf("----------------- HELP -----------------");
234
    theConsole.Printf("");
235
    return "";
236
}
237
 
391 jab 238
bool wantshelp(std::vector<std::string> &args)
239
{
240
	if(args.size()==0) return false;
241
	string str = args[0];
242
	if(str=="help" || str=="HELP" || str=="Help" || str=="?") return true;
243
	return false;
244
}
386 jab 245
 
391 jab 246
/// Function that aligns two meshes.
247
char* console_align(std::vector<std::string> &args)
248
{
249
	if(wantshelp(args)) 
250
		{
251
			theConsole.Printf("usage: align <dest> <src>");
252
			theConsole.Printf("This function aligns dest mesh with src");
253
			theConsole.Printf("In practice the GLViewController of src is copied to dst.");
254
			theConsole.Printf("both arguments are mandatory and must be numbers between 1 and 9.");
255
			theConsole.Printf("Note that results might be unexpexted if the meshes are not on the same scale");
256
			return "";
257
		}
386 jab 258
 
391 jab 259
	int dest = 0;
260
	if(args.size()>0)
261
	{
262
		istringstream a0(args[0]);
263
		a0 >> dest;
264
		--dest;
265
		if(dest <0 || dest>8) return "dest mesh out of range (1-9)";
266
	}
267
	else return "neither source nor destination mesh?!";
268
	int src = 0;
269
	if(args.size()>1)
270
	{
271
		istringstream a1(args[1]);
272
		a1 >> src;
273
		--src;
274
		if(src <0 || src>8) return "src mesh out of range (1-9)";
275
	}	
276
	else return "no src mesh?";
386 jab 277
 
391 jab 278
	get_vis_obj(dest).view_control() = get_vis_obj(src).view_control();
279
 
280
	return "";
386 jab 281
}
282
 
391 jab 283
 
388 jab 284
char* console_save(std::vector<std::string> &args)
285
{
391 jab 286
	if(wantshelp(args)) 
287
		{
288
			theConsole.Printf("usage: save <name.x3d|name.obj> ");
289
			return "";
290
		}
388 jab 291
	string& file_name = args[0];
292
	if(args.size() == 1)
293
	{
294
		if(file_name.substr(file_name.length()-4,file_name.length())==".obj")
295
		{
391 jab 296
			obj_save(file_name, active_mesh());
388 jab 297
			return "";
298
		}
299
		else if(file_name.substr(file_name.length()-4,file_name.length())==".x3d")
300
		{
391 jab 301
			x3d_save(file_name, active_mesh());
388 jab 302
			return "";
303
		}
304
		return "unknown format";
305
	}
306
	return "usage: save <name.x3d|name.obj> ";
307
}
386 jab 308
 
388 jab 309
char* console_refine_edges(std::vector<std::string> &args)
310
{
391 jab 311
	if(wantshelp(args)) 
312
		{
313
			theConsole.Printf("usage: refine.split_edges <length>");
314
			theConsole.Printf("splits edges longer than <length>; default is 0.5 times average length");
315
			return "";
316
		}
317
 
388 jab 318
	float thresh = 0.5;
319
	if(args.size()>0)
320
	{
321
		istringstream a0(args[0]);
322
		a0 >> thresh;
323
	}
391 jab 324
	float avg_length = average_edge_length(active_mesh());
325
	refine_edges(active_mesh(), thresh * avg_length);
388 jab 326
	return "";
391 jab 327
 
388 jab 328
}
329
 
330
char* console_refine_faces(std::vector<std::string> &args)
331
{
391 jab 332
	if(wantshelp(args)) 
333
		{
334
			theConsole.Printf("usage: refine.split_faces ");
335
			theConsole.Printf("usage:  Takes no arguments. Inserts a vertex at the centre of each face.");
336
			return "";
337
		}
338
 
339
	safe_triangulate(active_mesh());
388 jab 340
	return "";
391 jab 341
 
388 jab 342
}
343
 
344
char* console_cc_subdivide(std::vector<std::string> &args)
345
{
391 jab 346
	if(wantshelp(args)) 
347
		{
348
			theConsole.Printf("usage: refine.catmull_clark ");
349
			theConsole.Printf("Splits each polygon into four (Catmull Clark style)");
350
			return "";
351
		}
352
	cc_split(active_mesh(),active_mesh());
388 jab 353
	return "";
354
}
355
 
394 jab 356
char* console_dual(std::vector<std::string> &args)
357
{
358
	if(wantshelp(args)) 
359
	{
360
		theConsole.Printf("usage: dual ");
361
		theConsole.Printf("Produces the dual by converting each face to a vertex placed at the barycenter.");
362
		return "";
363
	}
364
 
365
	Manifold& m = active_mesh();
366
 
367
	// make sure every face knows its number
368
	m.enumerate_faces();
369
 
370
	vector<Vec3f> vertices(m.no_faces());
371
	vector<int> faces(m.no_vertices());
372
	vector<int> indices;
373
 
374
	// Create new vertices. Each face becomes a vertex whose position
375
	// is the centre of the face
376
	int i=0;
377
	for(FaceIter f=m.faces_begin(); f!=m.faces_end(); ++f,++i)
378
		vertices[i] = centre(f);
379
 
380
	// Create new faces. Each vertex is a new face with N=valency of vertex
381
	// edges.
382
	i=0;
383
	for(VertexIter v=m.vertices_begin(); v!= m.vertices_end(); ++v,++i)
384
	{
385
		VertexCirculator vc(v);
386
		vector<int> index_tmp;
387
		for(; !vc.end(); ++vc)
388
			index_tmp.push_back(vc.get_face()->touched);
389
 
390
		// Push vertex indices for this face onto indices vector.
391
		// The circulator moves around the face in a clockwise fashion
392
		// so we just reverse the ordering.
393
		indices.insert(indices.end(), index_tmp.rbegin(), index_tmp.rend());
394
 
395
		// Insert face valency in the face vector.
396
		faces[i] = vc.no_steps();
397
	}
398
 
399
	// Clear the manifold before new geometry is inserted.
400
	m.clear();
401
 
402
	// And build
403
	build_manifold(m, vertices.size(), &vertices[0], faces.size(),
404
				   &faces[0],&indices[0]);
405
 
406
	return "";
407
}
388 jab 408
 
409
 
387 jab 410
char* console_minimize_curvature(std::vector<std::string> &args)
411
{
391 jab 412
	if(wantshelp(args)) 
413
		{
414
			theConsole.Printf("usage: optimize.minimize_curvature <anneal>");
415
			theConsole.Printf("Flip edges to minimize mean curvature.");
416
			theConsole.Printf("If anneal is true, simulated annealing (slow) is used rather than a greedy scheme");
417
			return "";
418
		}
387 jab 419
	bool anneal=false;
420
	if(args.size()>0)
421
	{
422
		istringstream a0(args[0]);
423
		a0 >> anneal;
424
	}
391 jab 425
 
426
	minimize_curvature(active_mesh(), anneal);
427
	avo().post_create_display_list();
387 jab 428
	return "";
429
}
430
 
431
char* console_minimize_dihedral(std::vector<std::string> &args)
432
{
391 jab 433
	if(wantshelp(args)) 
434
		{
435
			theConsole.Printf("usage: optimize.minimize_dihedral <iter> <anneal> <use_alpha> <gamma> ");
436
			theConsole.Printf("Flip edges to minimize dihedral angles.");
437
			theConsole.Printf("Iter is the max number of iterations. anneal tells us whether to use ");
438
			theConsole.Printf("simulated annealing and not greedy optimization. use_alpha (default=true) ");
439
			theConsole.Printf("means to use angle and not cosine of anglegamma (default=4) is the power ");
440
			theConsole.Printf("to which we raise the dihedral angle");
441
			return "";
442
		}
387 jab 443
	int iter = 1000;
444
	if(args.size()>0)
445
	{
446
		istringstream a0(args[0]);
447
		a0 >> iter;
448
	}
391 jab 449
 
387 jab 450
	bool anneal = false;
451
	if(args.size()>1)
452
	{
453
		istringstream a0(args[0]);
454
		a0 >> anneal;
455
	}
391 jab 456
 
387 jab 457
	bool use_alpha = true;
388 jab 458
	if(args.size()>2)
387 jab 459
	{
460
		istringstream a0(args[0]);
461
		a0 >> use_alpha;
462
	}
391 jab 463
 
387 jab 464
	float gamma = 4.0;
465
	if(args.size()>3)
466
	{
467
		istringstream a0(args[0]);
468
		a0 >> gamma;
469
	}
470
 
471
 
391 jab 472
	minimize_dihedral_angle(active_mesh(), iter, anneal, use_alpha, gamma);
387 jab 473
	return "";
474
}
475
 
388 jab 476
char* console_maximize_min_angle(std::vector<std::string> &args)
477
{
391 jab 478
	if(wantshelp(args)) 
479
		{
480
			theConsole.Printf("usage: optimize.maximize_min_angle <thresh> <anneal>");
481
			theConsole.Printf("Flip edges to maximize min angle - to make mesh more Delaunay.");
482
			theConsole.Printf("If the dot product of the normals between adjacent faces < thresh");
483
			theConsole.Printf("no flip will be made. anneal selects simulated annealing rather ");
484
			theConsole.Printf("nthan greedy optimization.");
485
			return "";
486
		}
388 jab 487
	float thresh=0.0;
488
	if(args.size()>0)
489
	{
490
		istringstream a0(args[0]);
491
		a0 >> thresh;
492
	}
493
	bool anneal=false;
494
	if(args.size()>1)
495
	{
496
		istringstream a0(args[0]);
497
		a0 >> anneal;
498
	}
391 jab 499
	maximize_min_angle(active_mesh(),thresh,anneal);
388 jab 500
	return "";
501
}
502
 
503
 
387 jab 504
char* console_optimize_valency(std::vector<std::string> &args)
505
{
391 jab 506
	if(wantshelp(args)) 
507
		{
508
			theConsole.Printf("usage: optimize.valency <anneal> ");
509
			theConsole.Printf("Optimizes valency for triangle meshes. Anneal selects simulated annealing rather than greedy optim.");
510
			return "";
511
		}
387 jab 512
	bool anneal=false;
513
	if(args.size()>0)
514
	{
515
		istringstream a0(args[0]);
516
		a0 >> anneal;
517
	}
391 jab 518
	optimize_valency(active_mesh(), anneal);
387 jab 519
	return "";
520
}
521
 
388 jab 522
char* console_analyze(std::vector<std::string> &args)
523
{
391 jab 524
	if(wantshelp(args)) 
525
		{
526
			theConsole.Printf("usage:  harmonics.analyze");
527
			theConsole.Printf("Creates the Laplace Beltrami operator for the mesh and finds all eigensolutions.");
528
			theConsole.Printf("It also projects the vertices onto the eigenvectors - thus transforming the mesh");
529
			theConsole.Printf("to this basis.");
530
			theConsole.Printf("Note that this will stall the computer for a large mesh - as long as we use Lapack.");
531
			return "";
532
		}
533
	avo().harmonics_analyze_mesh();
388 jab 534
	return "";
535
}
536
 
537
 
386 jab 538
char* console_partial_reconstruct(std::vector<std::string> &args)
539
{
391 jab 540
	if(wantshelp(args)) 
541
		{
542
			theConsole.Printf("usage: haramonics.partial_reconstruct <e0> <e1> <s>");
543
			theConsole.Printf("Reconstruct from projections onto eigenvectors. The two first arguments indicate");
544
			theConsole.Printf("the eigenvector interval that we reconstruct from. The last argument is the ");
545
			theConsole.Printf("scaling factor. Thus, for a vertex, v, the formula for computing the position, p, is:");
546
			theConsole.Printf("for (i=e0; i<=e1;++i) p += proj[i] * Q[i][v] * s;");
547
			theConsole.Printf("where proj[i] is the 3D vector containing the x, y, and z projections of the mesh onto");
548
			theConsole.Printf("eigenvector i. Q[i][v] is the v'th coordinate of the i'th eigenvector.");
549
			theConsole.Printf("Note that if vertex coordinates are not first reset, the result is probably unexpected.");
550
			return "";
551
		}
386 jab 552
	int E0,E1;
553
	float scale;
554
	istringstream a0(args[0]);
555
	a0 >> E0;
556
	istringstream a1(args[1]);
557
	a1 >> E1;
558
	istringstream a2(args[2]);
559
	a2 >> scale;
391 jab 560
	avo().harmonics_partial_reconstruct(E0,E1,scale);
386 jab 561
	return "";
562
}
563
 
564
char* console_reset_shape(std::vector<std::string> &args)
565
{
391 jab 566
	if(wantshelp(args)) 
567
		{
568
			theConsole.Printf("usage: harmonics.reset_shape ");
569
			theConsole.Printf("Simply sets all vertices to 0,0,0. Call this before doing partial_reconstruct");
570
			theConsole.Printf("unless you know what you are doing.");
571
			return "";
572
		}
573
	avo().harmonics_reset_shape();
386 jab 574
	return "";
575
}
576
 
577
 
388 jab 578
char* console_close_holes(std::vector<std::string> &args)
579
{
391 jab 580
	if(wantshelp(args)) 
581
		{
582
			theConsole.Printf("usage: cleanup.close_holes");
583
			theConsole.Printf("This function closes holes. It simply follows the loop of halfvectors which");
584
			theConsole.Printf("enclose the hole and add a face to which they all point.");
585
			return "";
586
		}
587
	close_holes(active_mesh());
388 jab 588
	return "";
589
}
386 jab 590
 
388 jab 591
char* console_reload(std::vector<std::string> &args)
592
{
391 jab 593
	if(wantshelp(args)) 
594
		{
595
			theConsole.Printf("usage:  reload <file>");
596
			theConsole.Printf("Reloads the current file if no argument is given, but");
597
			theConsole.Printf("if an argument is given, then that becomes the current file");
598
			return "";
599
		}
600
	if(!avo().reload(args.size()>0 ? args[0]:""))
601
		return "failed to load";
388 jab 602
	return "";
603
}
604
 
605
 
387 jab 606
char* console_simplify(std::vector<std::string> &args)
607
{
391 jab 608
	if(wantshelp(args)) 
609
		{
610
			theConsole.Printf("usage: simplify <fraction> ");
611
			theConsole.Printf("Performs Garland Heckbert (quadric based) mesh simplification.");
612
			theConsole.Printf("The only argument is the fraction of vertices to keep.");
613
			return "";
614
		}
387 jab 615
	float keep_fraction;
616
	if(args.size()==0) return "you must specify fraction of vertices to keep";
617
	istringstream a0(args[0]);
618
	a0 >> keep_fraction;
391 jab 619
 
387 jab 620
	Vec3f p0, p7;
391 jab 621
	active_mesh().get_bbox(p0, p7);
387 jab 622
	Vec3f d = p7-p0;
623
	float s = 1.0/d.max_coord();
624
	Vec3f pcentre = (p7+p0)/2.0;
391 jab 625
	for(VertexIter vi = active_mesh().vertices_begin(); vi != active_mesh().vertices_end(); ++vi)
387 jab 626
		vi->pos = (vi->pos - pcentre) * s;
391 jab 627
	quadric_simplify(active_mesh(),keep_fraction,0.0001f,true);
628
	for(VertexIter vi = active_mesh().vertices_begin(); vi != active_mesh().vertices_end(); ++vi)
387 jab 629
		vi->pos = vi->pos*d.max_coord() + pcentre;
630
	return "";
631
}
632
 
391 jab 633
char* console_vertex_noise(std::vector<std::string> &args)
634
{
635
	if(wantshelp(args)) 
636
		{
637
			theConsole.Printf("usage: noise.perturb_vertices <amplitude>");
638
			theConsole.Printf("adds a random vector to each vertex. To ensure uniformness, the vector must lie in the");
639
			theConsole.Printf("unit sphere. The length of the vector is multiplied by the average edge length and then amplitude");
640
			return "";
641
		}
642
	float avg_length = average_edge_length(active_mesh());
643
 
644
	float noise_amplitude = 0.5;
645
	if(args.size()>0) 
646
	{
647
		istringstream a0(args[0]);
648
		a0 >> noise_amplitude;
649
	}
650
 
651
	srand(0);
652
	for(VertexIter vi = active_mesh().vertices_begin(); vi != active_mesh().vertices_end(); ++vi)
653
	{
654
		Vec3f v;
655
		do {
656
			v = Vec3f(rand(),rand(),rand());
657
			v /= RAND_MAX;
658
		} while(sqr_length(v) > 1.0);
659
		v -= Vec3f(0.5);
660
		v *= 2.0;
661
		v *= noise_amplitude;
662
		v *= avg_length;
663
		vi->pos += v;
664
	}		
665
	return "";
666
}
667
 
668
char* console_noisy_flips(std::vector<std::string> &args)
669
{
670
	if(wantshelp(args)) 
671
		{
672
			theConsole.Printf("usage:  noise.perturb_topology <iter>");
673
			theConsole.Printf("Perform random flips. iter (default=1) is the number of iterations.");
674
			theConsole.Printf("mostly for making nasty synthetic test cases.");
675
			return "";
676
		}
677
	int iter=1;
678
	if(args.size()>0)
679
	{
680
		istringstream a0(args[0]);
681
		a0 >> iter;
682
	}
683
 
684
	randomize_mesh(active_mesh(),  iter);
685
	return "";
686
}
687
 
387 jab 688
char* console_laplacian_smooth(std::vector<std::string> &args)
689
{
391 jab 690
	if(wantshelp(args)) 
691
		{
692
			theConsole.Printf("usage:  smooth.laplacian <weight>");
693
			theConsole.Printf("Perform Laplacian smoothing. weight is the scaling factor for the Laplacian.");
694
			return "";
695
		}
387 jab 696
	float t=1.0;
697
	if(args.size()>0)
698
	{
699
		istringstream a0(args[0]);
700
		a0 >> t;
701
	}
702
	/// Simple laplacian smoothing with an optional weight.
391 jab 703
	laplacian_smooth(active_mesh(), t);
387 jab 704
	return "";
705
}
706
 
707
char* console_taubin_smooth(std::vector<std::string> &args)
708
{
391 jab 709
	if(wantshelp(args)) 
710
		{
711
			theConsole.Printf("usage:  smooth.taubin <iter>");
712
			theConsole.Printf("Perform Taubin smoothing. iter (default=1) is the number of iterations.");
713
			return "";
714
		}
387 jab 715
	int iter=1;
716
	if(args.size()>0)
717
	{
718
		istringstream a0(args[0]);
719
		a0 >> iter;
720
	}
721
 
722
	/// Taubin smoothing is similar to laplacian smoothing but reduces shrinkage
391 jab 723
	taubin_smooth(active_mesh(),  iter);
387 jab 724
	return "";
725
}
726
 
727
char* console_fvm_smooth(std::vector<std::string> &args)
728
{	
391 jab 729
	if(wantshelp(args)) 
730
		{
731
			theConsole.Printf("usage: smooth.fuzzy_vector_median <iter>");
732
			theConsole.Printf("Smooth normals using fuzzy vector median smoothing. iter (default=1) is the number of iterations");
733
			theConsole.Printf("This function does a very good job of preserving sharp edges.");
734
			return "";
735
		}
387 jab 736
	int iter=1;
737
	if(args.size()>0)
738
	{
739
		istringstream a0(args[0]);
740
		a0 >> iter;
741
	}
742
	/** Fuzzy vector median smoothing is effective when it comes to
743
	 preserving sharp edges. */
391 jab 744
	fvm_smooth(active_mesh(),  iter);
387 jab 745
	return "";
391 jab 746
 
387 jab 747
}
748
 
388 jab 749
char* console_triangulate(std::vector<std::string> &args)
750
{	
391 jab 751
	if(wantshelp(args)) 
752
		{
753
			theConsole.Printf("usage:  triangulate");
754
			theConsole.Printf("This function triangulates all non triangular faces of the mesh.");
755
			theConsole.Printf("you may want to call it after hole closing. For a polygon it simply connects");
756
			theConsole.Printf("the two closest vertices in a recursive manner until only triangles remain");
757
			return "";
758
		}
759
	shortest_edge_triangulate(active_mesh());
388 jab 760
	return "";
761
}
762
 
763
 
764
char* console_remove_caps(std::vector<std::string> &args)
765
{	
391 jab 766
	if(wantshelp(args)) 
767
		{
768
			theConsole.Printf("usage:  cleanup.remove_caps thresh");
769
			theConsole.Printf("Remove caps (triangles with one very big angle). The thresh argument is the fraction of PI to");
770
			theConsole.Printf("use as threshold for big angle. Default is 0.85. Caps are removed by flipping.");
771
			return "";
772
		}
773
	float t=0.85;
774
	if(args.size()>0)
775
	{
776
		istringstream a0(args[0]);
777
		a0 >> t;
778
	}
779
 
780
	remove_caps_from_trimesh(active_mesh(), static_cast<float>(M_PI) *t);
388 jab 781
	return "";
782
}
783
 
784
char* console_remove_needles(std::vector<std::string> &args)
785
{	
391 jab 786
	if(wantshelp(args)) 
787
		{
788
			theConsole.Printf("usage: cleanup.remove_needles <thresh>");
789
			theConsole.Printf("Removes very short edges by collapse. thresh is multiplied by the average edge length");
790
			theConsole.Printf("to get the length shorter than which we collapse. Default = 0.1");
791
			return "";
792
		}
388 jab 793
	float thresh = 0.1;
794
	if(args.size()>0)
795
	{
796
		istringstream a0(args[0]);
797
		a0 >> thresh;
798
	}
391 jab 799
	float avg_length = average_edge_length(active_mesh());
800
	remove_needles_from_trimesh(active_mesh(), thresh * avg_length);
388 jab 801
	return "";
802
}
803
 
391 jab 804
void reshape(int W, int H)
805
{
806
	active_view_control().reshape(W,H);
807
}
808
 
386 jab 809
void display() 
810
{
811
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
812
 
388 jab 813
	static CVar<int> display_wireframe("display.wireframe",0);
394 jab 814
	static CVar<int> display_eigenmodes("display.show_harmonics",0);
388 jab 815
	static CVar<int> display_flat("display.flatshading",0);
386 jab 816
 
817
	glPushMatrix();
818
 
391 jab 819
	avo().display(display_wireframe, display_eigenmodes, display_flat);
386 jab 820
 
821
	glPopMatrix();
822
 
823
	glUseProgram(0);
824
	theConsole.RenderConsole();
825
 
826
	glutSwapBuffers();
827
}
828
 
829
void animate() 
830
{	
394 jab 831
	//usleep( (int)1e4 );
391 jab 832
	active_view_control().try_spin();
386 jab 833
	glutPostRedisplay();
834
}
835
 
836
 
837
void mouse(int button, int state, int x, int y) 
838
{
839
	Vec2i pos(x,y);
840
	if (state==GLUT_DOWN) 
841
	{
842
		if (button==GLUT_LEFT_BUTTON) 
391 jab 843
			active_view_control().grab_ball(ROTATE_ACTION,pos);
386 jab 844
		else if (button==GLUT_MIDDLE_BUTTON) 
391 jab 845
			active_view_control().grab_ball(ZOOM_ACTION,pos);
386 jab 846
		else if (button==GLUT_RIGHT_BUTTON) 
391 jab 847
			active_view_control().grab_ball(PAN_ACTION,pos);
386 jab 848
	}
849
	else if (state==GLUT_UP)
391 jab 850
		active_view_control().release_ball();
386 jab 851
}
852
 
853
void motion(int x, int y) {
854
	Vec2i pos(x,y);
391 jab 855
	active_view_control().roll_ball(Vec2i(x,y));
386 jab 856
}
857
 
858
void keyboard_spec(int key, int x, int y)
859
{
391 jab 860
	int mod = glutGetModifiers();
861
	if( theConsole.isOpen() ) {
862
		// If shift held, scroll the console
863
		if( mod == GLUT_ACTIVE_SHIFT ) {
864
			switch (key){
865
				case GLUT_KEY_UP:
866
					theConsole.ScrollDownLine();
867
					break;
868
				case GLUT_KEY_DOWN: 
869
					theConsole.ScrollUpLine();
870
					break;
871
			}
872
		} else {
873
			theConsole.StandardKeyBindings( key );
874
		}
875
	}
386 jab 876
}
877
 
878
 
879
void keyboard(unsigned char key, int x, int y) 
880
{	
881
	if(theConsole.isOpen())
391 jab 882
	{
386 jab 883
		switch(key) {
884
			case '\033': 
885
				theConsole.ToggleConsole();
886
			default:      
887
				//send keystroke to console
888
				if( theConsole.isOpen() ){
889
					theConsole.EnterCommandCharacter(key);
890
				}
891
				break;
388 jab 892
		}
391 jab 893
		if(key == 13)	avo().post_create_display_list();
894
 
895
	}	
386 jab 896
	else {
897
		int& display_wireframe = get_CVar_ref<int>("display.wireframe");
388 jab 898
		int& display_flat = get_CVar_ref<int>("display.flatshading");
391 jab 899
		int& active  = get_CVar_ref<int>("active_mesh");
386 jab 900
 
391 jab 901
 
386 jab 902
		switch(key) {
903
			case 'q': exit(0);
904
			case '\033':
905
				theConsole.ToggleConsole();
906
				break;
391 jab 907
			case '1':
908
			case '2':
909
			case '3':
910
			case '4':
911
			case '5':
912
			case '6':
913
			case '7':
914
			case '8':
915
			case '9':
916
				active = key - '1'; break;
917
			case 'f': display_flat = !display_flat; break;
386 jab 918
			case 'w':
919
				display_wireframe = !display_wireframe;
920
				break;
921
		}
391 jab 922
 
394 jab 923
		if(get_CVar_ref<int>("display.show_harmonics"))
391 jab 924
			avo().harmonics_parse_key(key);
925
 
926
		avo().post_create_display_list();		
386 jab 927
	}
928
}
929
 
930
void init_glut(int argc, char** argv)
931
{
397 jab 932
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH|GLUT_ALPHA);
386 jab 933
	glutInitWindowSize(WINX, WINY);
934
	glutInit(&argc, argv);
935
	glutCreateWindow("Shape Harmonics");
936
	glutDisplayFunc(display);
937
	glutKeyboardFunc(keyboard);
938
	glutSpecialFunc(keyboard_spec);
939
	glutReshapeFunc(reshape);
940
	glutMouseFunc(mouse);
941
	glutMotionFunc(motion);
942
	glutIdleFunc(animate);
943
}
944
 
945
void init_gl()
946
{
947
	glewInit();
948
	glEnable(GL_LIGHTING);
949
	glEnable(GL_LIGHT0);
388 jab 950
	glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
397 jab 951
 
386 jab 952
	// Set the value of a uniform
953
	//glUniform2f(glGetUniformLocation(prog_P0,"WIN_SCALE"), win_size_x/2.0, win_size_y/2.0);
954
 
955
	glMatrixMode(GL_MODELVIEW);
956
	glLoadIdentity();
957
	glClearColor(0.50f, 0.50f, 0.50f, 0.f);
958
	glColor4f(1.0f, 1.0f, 1.0f, 0.f);
959
	glEnable(GL_DEPTH_TEST);
960
 
961
	static CVar<ConsoleFunc> help( "help", ConsoleHelp );
391 jab 962
	static CVar<ConsoleFunc> rs("harmonics.reset_shape", console_reset_shape);
963
	static CVar<ConsoleFunc> ha("harmonics.analyze", console_analyze);
964
	static CVar<ConsoleFunc> pr("harmonics.partial_reconstruct", console_partial_reconstruct);
387 jab 965
	static CVar<ConsoleFunc> simpl("simplify", console_simplify);
391 jab 966
	static CVar<ConsoleFunc> lsmooth("smooth.laplacian", console_laplacian_smooth);
967
	static CVar<ConsoleFunc> tsmooth("smooth.taubin", console_taubin_smooth);
968
	static CVar<ConsoleFunc> fsmooth("smooth.fuzzy_vector_median", console_fvm_smooth);
969
 
970
	static CVar<ConsoleFunc> opt_val("optimize.valency", console_optimize_valency);
971
	static CVar<ConsoleFunc> min_dih("optimize.minimize_dihedral_angles", console_minimize_dihedral);
972
	static CVar<ConsoleFunc> min_curv("optimize.minimize_curvature", console_minimize_curvature);
973
	static CVar<ConsoleFunc> max_min_angle("optimize.maximize_min_angle", console_maximize_min_angle);
974
	static CVar<ConsoleFunc> close_holes_fun("cleanup.close_holes", console_close_holes);
388 jab 975
	static CVar<ConsoleFunc> reload_fun("reload", console_reload);
391 jab 976
 
977
	static CVar<ConsoleFunc> rem_caps_fun("cleanup.remove_caps", console_remove_caps);
978
	static CVar<ConsoleFunc> rem_needles_fun("cleanup.remove_needles", console_remove_needles);
388 jab 979
	static CVar<ConsoleFunc> triangulate_fun("triangulate", console_triangulate);
391 jab 980
	static CVar<ConsoleFunc> refine_fun("refine.split_edges", console_refine_edges);
981
	static CVar<ConsoleFunc> refine_face_fun("refine.split_faces", console_refine_faces);
982
	static CVar<ConsoleFunc> subd_fun("refine.catmull_clark", console_cc_subdivide);
388 jab 983
	static CVar<ConsoleFunc> save_fun("save", console_save);
391 jab 984
	static CVar<ConsoleFunc> noise_fun("noise.perturb_vertices", console_vertex_noise);
985
	static CVar<ConsoleFunc> noise_fun2("noise.perturb_topology", console_noisy_flips);
986
 
394 jab 987
	static CVar<ConsoleFunc> dualize("dual", console_dual);
988
 
391 jab 989
	static CVar<ConsoleFunc> align_fun("align", console_align);
387 jab 990
 
991
 
386 jab 992
}
993
 
994
int main(int argc, char** argv)
995
{
996
	ArgExtracter ae(argc, argv);
391 jab 997
 
998
	init_glut(argc,argv);
999
	init_gl();
1000
 
1001
	Harmonics::init();
1002
 
1003
		if(argc>1)
386 jab 1004
	{		
391 jab 1005
		string file = ae.get_last_arg();
1006
		avo().reload(file);
386 jab 1007
	}
1008
 
1009
 
1010
	glutMainLoop();
1011
}
1012
 
1013