Subversion Repositories gelsvn

Rev

Rev 663 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
647 janba 1
//
2
//  MeshEditor.cpp
3
//  GEL
4
//
5
//  Created by J. Andreas Bærentzen on 09/10/13.
6
//
7
//
662 janba 8
#include <thread>
9
#include <unistd.h>
647 janba 10
#include <GL/glew.h>
11
#include <functional>
12
#include "MeshEditor.h"
13
#include <string>
14
#include <iostream>
15
#include <vector>
16
#include <algorithm>
17
#include <queue>
18
 
19
#include <GLGraphics/Console.h>
666 janba 20
#include <GLGraphics/glsl_shader.h>
21
#include <GLGraphics/ShadowBuffer.h>
647 janba 22
 
23
#include <CGLA/eigensolution.h>
24
#include <CGLA/Vec2d.h>
25
#include <CGLA/Vec3d.h>
26
#include <CGLA/Mat3x3d.h>
27
#include <CGLA/Mat2x2d.h>
28
#include <CGLA/Mat2x3d.h>
29
#include <CGLA/Mat4x4d.h>
30
 
31
#include <LinAlg/Matrix.h>
32
#include <LinAlg/Vector.h>
33
#include <LinAlg/LapackFunc.h>
34
 
35
#include <HMesh/Manifold.h>
36
#include <HMesh/AttributeVector.h>
37
#include <HMesh/mesh_optimization.h>
38
#include <HMesh/curvature.h>
39
#include <HMesh/triangulate.h>
40
#include <HMesh/flatten.h>
41
#include <HMesh/dual.h>
42
#include <HMesh/load.h>
43
#include <HMesh/quadric_simplify.h>
44
#include <HMesh/smooth.h>
45
#include <HMesh/x3d_save.h>
46
#include <HMesh/obj_save.h>
47
#include <HMesh/off_save.h>
48
#include <HMesh/mesh_optimization.h>
49
#include <HMesh/triangulate.h>
50
#include <HMesh/cleanup.h>
51
#include <HMesh/cleanup.h>
52
#include <HMesh/refine_edges.h>
53
#include <HMesh/subdivision.h>
54
#include <HMesh/harmonics.h>
55
 
56
#include <Util/Timer.h>
57
 
58
#include "VisObj.h"
59
 
60
using namespace std;
61
using namespace CGLA;
62
using namespace HMesh;
63
using namespace Util;
64
 
65
namespace GLGraphics {
66
 
67
    namespace {
68
 
69
        bool wantshelp(const std::vector<std::string> & args)
70
        {
71
            if(args.size() == 0)
72
                return false;
73
 
74
            string str = args[0];
75
 
76
            if(str=="help" || str=="HELP" || str=="Help" || str=="?")
77
                return true;
78
 
79
            return false;
80
        }
81
 
82
 
83
        bool wantshelp(MeshEditor* me, const std::vector<std::string> & args)
84
        {
85
            if(args.size() == 0)
86
                return false;
87
 
88
            string str = args[0];
89
 
90
            if(str=="help" || str=="HELP" || str=="Help" || str=="?")
91
                return true;
92
 
93
            return false;
94
        }
95
 
96
        /// Function that aligns two meshes.
97
        void console_align(MeshEditor* me, const std::vector<std::string> & args)
98
        {
99
            if(wantshelp(args)) {
100
                me->printf("usage: align <dest> <src>");
101
                me->printf("This function aligns dest mesh with src");
102
                me->printf("In practice the GLViewController of src is copied to dst.");
103
                me->printf("both arguments are mandatory and must be numbers between 1 and 9.");
104
                me->printf("Note that results might be unexpexted if the meshes are not on the same scale");
105
            }
106
 
107
            int dest = 0;
108
 
109
            if(args.size()>0){
110
                istringstream a0(args[0]);
111
                a0 >> dest;
112
                --dest;
113
 
114
                if(dest <0 || dest>8)
115
                {
116
                    me->printf("dest mesh out of range (1-9)");
117
                    return;
118
                }
119
            }
120
            else
121
            {
122
                me->printf("neither source nor destination mesh?!");
123
                return;
124
            }
125
 
126
            int src = 0;
127
            if(args.size()>1){
128
                istringstream a1(args[1]);
129
                a1 >> src;
130
                --src;
131
 
132
                if(src <0 || src>8)
133
                {
134
                    me->printf("src mesh out of range (1-9)");
135
                    return;
136
                }
137
            }
138
            else
139
            {
140
                me->printf("no src mesh?");
141
                return;
142
            }
143
            me->align(src,dest);
144
        }
145
 
146
 
147
 
148
 
149
        void console_ridge_lines(MeshEditor* me, const std::vector<std::string> & args)
150
        {
151
            if(wantshelp(args)) {
152
                me->printf("usage: ridge_lines");
153
                return;
154
            }
155
 
156
            me->save_active_mesh();
157
 
158
            Manifold& mani = me->active_mesh();
159
 
160
            VertexAttributeVector<Mat3x3d> curvature_tensors(mani.allocated_vertices());
161
            VertexAttributeVector<Vec3d> min_curv_direction(mani.allocated_vertices());
162
            VertexAttributeVector<Vec3d> max_curv_direction(mani.allocated_vertices());
163
            VertexAttributeVector<Vec2d> curvature(mani.allocated_vertices());
164
 
165
 
166
 
167
            curvature_paraboloids(mani,
168
                                  min_curv_direction,
169
                                  max_curv_direction,
170
                                  curvature);
171
 
172
            for(auto vid : mani.vertices())
173
            {
174
                Vec3d max_curv_dir = normalize(max_curv_direction[vid]);
175
                Vec3d min_curv_dir = normalize(min_curv_direction[vid]);
176
                double vid_min_pc = curvature[vid][0];
177
                double vid_max_pc = curvature[vid][1];
178
                bool ridge = true;
179
                bool ravine = true;
180
                Walker w = mani.walker(vid);
181
                Vec3d r(0);
182
                for(; !w.full_circle();w = w.circulate_vertex_ccw())
183
                {
184
                    Vec3d e = (mani.pos(w.vertex()) - mani.pos(vid));
185
 
186
                    if(abs(dot(min_curv_dir,e)) > abs(dot(max_curv_dir,e)))
187
                    {
188
                        if(curvature[w.vertex()][0]<vid_min_pc+20)
189
                            ravine = false;
190
 
191
                    }
192
                    else
193
                    {
194
                        if(curvature[w.vertex()][1]>vid_max_pc-20)
195
                            ridge = false;
196
                    }
197
                }
198
                DebugRenderer::vertex_colors[vid] = Vec3f(ridge,ravine,0.0);
199
            }
200
            for(auto fid : mani.faces())
201
                DebugRenderer::face_colors[fid] = Vec3f(.3,.3,.6);
202
            for(auto hid : mani.halfedges()) {
203
 
204
                Walker w = mani.walker(hid);
205
                Vec3f c0 = DebugRenderer::vertex_colors[w.opp().vertex()];
206
                Vec3f c1 = DebugRenderer::vertex_colors[w.vertex()];
207
 
208
                DebugRenderer::edge_colors[hid] = (c0==c1) ? c0 : Vec3f(0.1,0.1,0.3);
209
 
210
            }
211
        }
212
 
213
        void transform_mesh(Manifold& mani, const Mat4x4d& m)
214
        {
215
            for(VertexIDIterator vid = mani.vertices_begin(); vid != mani.vertices_end(); ++vid)
216
                mani.pos(*vid) = m.mul_3D_point(mani.pos(*vid));
217
        }
218
 
219
        void console_scale(MeshEditor* me, const std::vector<std::string> & args)
220
        {
221
            if(wantshelp(args)) {
222
                me->printf("usage: scale sx sy sz");
223
                return;
224
            }
225
 
226
            Vec3d s;
227
 
228
            if(args.size() > 0){
229
                istringstream a0(args[0]);
230
                a0 >> s[0];
231
            }
232
            if(args.size() > 1){
233
                istringstream a0(args[0]);
234
                a0 >> s[1];
235
            }
236
            if(args.size() > 2){
237
                istringstream a0(args[0]);
238
                a0 >> s[2];
239
            }
240
 
241
            me->save_active_mesh();
242
            transform_mesh(me->active_mesh(),scaling_Mat4x4d(s));
243
            me->refit();
244
        }
245
 
657 janba 246
        void console_test(MeshEditor* me, const std::vector<std::string> & args)
247
        {
248
            if(wantshelp(args)) {
249
                me->printf("usage: test");
250
                return;
251
            }
252
 
253
            me->save_active_mesh();
254
            me->active_mesh().slit_edges(me->get_vertex_selection());
255
        }
256
 
647 janba 257
 
258
        void console_flatten(MeshEditor* me, const std::vector<std::string> & args)
259
        {
260
            if(wantshelp(args)) {
261
                me->printf("usage: flatten <floater|harmonic|barycentric>");
262
                me->printf("This function flattens a meshs with a simple boundary. It is mostly for showing mesh");
263
                me->printf("parametrization methods. The current mesh MUST have a SINGLE boundary loop");
264
                me->printf("This loop is mapped to the unit circle in a regular fashion (equal angle intervals).");
265
                me->printf("All non boundary vertices are placed at the origin. Then the system is relaxed iteratively");
266
                me->printf("using the weight scheme given as argument.");
267
                return;
268
            }
269
 
270
            me->save_active_mesh();
271
 
272
            WeightScheme ws = BARYCENTRIC_W;
273
            if(args.size()>0){
274
                if(args[0] == "floater")
275
                    ws = FLOATER_W;
276
                else if(args[0] == "harmonic")
277
                    ws = HARMONIC_W;
278
                else if(args[0] == "lscm")
279
                    ws = LSCM_W;
280
            }
281
            else
282
                return;
283
 
284
            flatten(me->active_mesh(), ws);
285
 
286
            return;
287
        }
288
 
289
        void console_save(MeshEditor* me, const std::vector<std::string> & args)
290
        {
291
            if(wantshelp(args)) {
292
                me->printf("usage: save <name->x3d|name->obj> ");
293
 
294
                return;
295
            }
296
            const string& file_name = args[0];
297
            if(args.size() == 1){
298
                if(file_name.substr(file_name.length()-4,file_name.length())==".obj"){
299
                    obj_save(file_name, me->active_mesh());
300
 
301
                    return;
302
                }
303
                else if(file_name.substr(file_name.length()-4,file_name.length())==".off"){
304
                    off_save(file_name, me->active_mesh());
305
 
306
                    return;
307
                }
308
                else if(file_name.substr(file_name.length()-4,file_name.length())==".x3d"){
309
                    x3d_save(file_name, me->active_mesh());
310
 
311
                    return;
312
                }
313
                me->printf("unknown format");
314
                return;
315
            }
316
            me->printf("usage: save <name->x3d|name->obj> ");
317
        }
318
 
319
 
320
        void console_refine_edges(MeshEditor* me, const std::vector<std::string> & args)
321
        {
322
            if(wantshelp(args)) {
323
                me->printf("usage: refine.split_edges <length>");
324
                me->printf("splits edges longer than <length>; default is 0.5 times average length");
325
                return;
326
            }
327
 
328
            me->save_active_mesh();
329
 
330
            float thresh = 0.5f;
331
 
332
            if(args.size() > 0){
333
                istringstream a0(args[0]);
334
                a0 >> thresh;
335
            }
336
 
337
            float avg_length = average_edge_length(me->active_mesh());
338
 
339
            refine_edges(me->active_mesh(), thresh * avg_length);
340
 
341
            return;
342
 
343
        }
344
 
345
        void console_refine_faces(MeshEditor* me, const std::vector<std::string> & args)
346
        {
347
            if(wantshelp(args)) {
348
                me->printf("usage: refine.split_faces ");
349
                me->printf("usage:  Takes no arguments. Inserts a vertex at the centre of each face.");
350
 
351
                return;
352
            }
353
            me->save_active_mesh();
354
 
355
            triangulate_by_vertex_face_split(me->active_mesh());
356
 
357
            return;
358
 
359
        }
360
 
361
        void console_cc_subdivide(MeshEditor* me, const std::vector<std::string> & args)
362
        {
363
            if(wantshelp(args)) {
364
                me->printf("usage: subdivide.catmull_clark ");
365
                me->printf("Does one step of Catmull-Clark subdivision");
366
 
367
                return;
368
            }
369
            me->save_active_mesh();
370
 
371
            cc_split(me->active_mesh(),me->active_mesh());
372
            cc_smooth(me->active_mesh());
373
 
374
            return;
375
        }
376
 
666 janba 377
        void console_root_cc_subdivide(MeshEditor* me, const std::vector<std::string> & args)
378
        {
379
            if(wantshelp(args)) {
380
                me->printf("usage: subdivide.catmull_clark ");
381
                me->printf("Does one step of Catmull-Clark subdivision");
382
 
383
                return;
384
            }
385
            me->save_active_mesh();
386
 
387
            rootCC_subdivide(me->active_mesh(),me->active_mesh());
388
            return;
389
        }
390
 
391
 
647 janba 392
        void console_loop_subdivide(MeshEditor* me, const std::vector<std::string> & args)
393
        {
394
            if(wantshelp(args)) {
395
                me->printf("usage: subdivide.loop");
396
                me->printf("Does one step of Loop subdivision");
397
 
398
                return;
399
            }
400
            me->save_active_mesh();
401
 
402
            loop_split(me->active_mesh(),me->active_mesh());
403
            loop_smooth(me->active_mesh());
404
 
405
            return;
406
        }
666 janba 407
 
663 janba 408
        void console_stitch(MeshEditor* me, const std::vector<std::string> & args)
409
        {
410
            if(wantshelp(args)) {
666 janba 411
                me->printf("usage: cleanup.stitch <rad>");
663 janba 412
                me->printf("Stitches faces");
413
 
414
                return;
415
            }
666 janba 416
            double r = 0.001;
417
 
418
            if(args.size() > 0){
419
                istringstream a0(args[0]);
420
                a0 >> r;
421
            }
422
 
663 janba 423
            me->save_active_mesh();
666 janba 424
            Manifold& m = me->active_mesh();
425
            Vec3d c;
426
            float rad;
427
            bsphere(m, c, rad);
428
            stitch_mesh(me->active_mesh(), r * rad);
663 janba 429
            return;
430
        }
647 janba 431
 
666 janba 432
        void console_remove_val2(MeshEditor* me, const std::vector<std::string> & args)
433
        {
434
            if(wantshelp(args)) {
435
                me->printf("usage: cleanup.remove_val2");
436
                me->printf("Removes valence 2 vertices");
437
 
438
                return;
439
            }
440
            me->save_active_mesh();
441
            Manifold& m = me->active_mesh();
442
            remove_valence_two_vertices(m);
443
            return;
444
        }
445
 
446
 
647 janba 447
        void console_root3_subdivide(MeshEditor* me, const std::vector<std::string> & args)
448
        {
449
            if(wantshelp(args)) {
450
                me->printf("usage: subdivide.root3");
451
                me->printf("Does one step of sqrt(3) subdivision");
452
 
453
                return;
454
            }
455
            me->save_active_mesh();
456
 
457
            root3_subdivide(me->active_mesh(),me->active_mesh());
458
 
459
            return;
460
        }
461
 
462
 
463
        void console_doosabin_subdivide(MeshEditor* me, const std::vector<std::string> & args)
464
        {
465
            if(wantshelp(args)) {
466
                me->printf("usage: subdivide.doo_sabin ");
467
                me->printf("Does one step of Doo-Sabin Subdivision");
468
 
469
                return;
470
            }
471
            me->save_active_mesh();
472
 
473
            cc_split(me->active_mesh(),me->active_mesh());
474
            dual(me->active_mesh());
475
 
476
            return;
477
        }
478
 
479
        void console_butterfly_subdivide(MeshEditor* me, const std::vector<std::string> & args)
480
        {
481
            if(wantshelp(args)) {
482
                me->printf("usage: subdivide.butterfly ");
483
                me->printf("Does one step of Modified Butterfly Subdivision");
484
 
485
                return;
486
            }
487
            me->save_active_mesh();
488
 
489
            butterfly_subdivide(me->active_mesh(),me->active_mesh());
490
 
491
            return;
492
        }
493
 
494
        void console_dual(MeshEditor* me, const std::vector<std::string> & args)
495
        {
496
            if(wantshelp(args))
497
            {
498
                me->printf("usage: dual ");
499
                me->printf("Produces the dual by converting each face to a vertex placed at the barycenter.");
500
                return;
501
            }
502
            me->save_active_mesh();
503
 
504
            dual(me->active_mesh());
505
 
506
            return;
507
        }
508
 
509
 
510
        void console_minimize_curvature(MeshEditor* me, const std::vector<std::string> & args)
511
        {
512
            if(wantshelp(args))
513
            {
514
                me->printf("usage: optimize.minimize_curvature <anneal>");
515
                me->printf("Flip edges to minimize mean curvature.");
516
                me->printf("If anneal is true, simulated annealing (slow) is used rather than a greedy scheme");
517
                return;
518
            }
519
            me->save_active_mesh();
520
 
521
            bool anneal=false;
522
            if(args.size() > 0)
523
            {
524
                istringstream a0(args[0]);
525
                a0 >> anneal;
526
            }
527
 
528
            minimize_curvature(me->active_mesh(), anneal);
529
            me->post_create_display_list();
530
            return;
531
        }
532
 
533
        void console_minimize_dihedral(MeshEditor* me, const std::vector<std::string> & args)
534
        {
535
            if(wantshelp(args))
536
            {
537
                me->printf("usage: optimize.minimize_dihedral <iter> <anneal> <use_alpha> <gamma> ");
538
                me->printf("Flip edges to minimize dihedral angles.");
539
                me->printf("Iter is the max number of iterations. anneal tells us whether to use ");
540
                me->printf("simulated annealing and not greedy optimization. use_alpha (default=true) ");
541
                me->printf("means to use angle and not cosine of anglegamma (default=4) is the power ");
542
                me->printf("to which we raise the dihedral angle");
543
                return;
544
            }
545
            me->save_active_mesh();
546
 
547
            int iter = 1000;
548
            if(args.size() > 0)
549
            {
550
                istringstream a0(args[0]);
551
                a0 >> iter;
552
            }
553
 
554
            bool anneal = false;
555
            if(args.size() > 1)
556
            {
557
                istringstream a0(args[1]);
558
                a0 >> anneal;
559
            }
560
 
561
            bool use_alpha = true;
562
            if(args.size() > 2)
563
            {
564
                istringstream a0(args[2]);
565
                a0 >> use_alpha;
566
            }
567
 
568
            float gamma = 4.0f;
569
            if(args.size() > 3)
570
            {
571
                istringstream a0(args[3]);
572
                a0 >> gamma;
573
            }
574
 
575
 
576
            minimize_dihedral_angle(me->active_mesh(), iter, anneal, use_alpha, gamma);
577
            return;
578
        }
579
 
580
        void console_maximize_min_angle(MeshEditor* me, const std::vector<std::string> & args)
581
        {
582
            if(wantshelp(args))
583
            {
584
                me->printf("usage: optimize.maximize_min_angle <thresh> <anneal>");
585
                me->printf("Flip edges to maximize min angle - to make mesh more Delaunay.");
586
                me->printf("If the dot product of the normals between adjacent faces < thresh");
587
                me->printf("no flip will be made. anneal selects simulated annealing rather ");
588
                me->printf("nthan greedy optimization.");
589
                return;
590
            }
591
            me->save_active_mesh();
592
 
593
            float thresh = 0.0f;
594
            if(args.size() > 0)
595
            {
596
                istringstream a0(args[0]);
597
                a0 >> thresh;
598
            }
599
            bool anneal = false;
600
            if(args.size() > 1)
601
            {
602
                istringstream a0(args[1]);
603
                a0 >> anneal;
604
            }
605
            maximize_min_angle(me->active_mesh(),thresh,anneal);
606
            return;
607
        }
608
 
609
 
610
        void console_optimize_valency(MeshEditor* me, const std::vector<std::string> & args)
611
        {
612
            if(wantshelp(args))
613
            {
614
                me->printf("usage: optimize.valency <anneal> ");
615
                me->printf("Optimizes valency for triangle meshes. Anneal selects simulated annealing rather than greedy optim.");
616
                return;
617
            }
618
            me->save_active_mesh();
619
 
620
            bool anneal = false;
621
            if(args.size() > 0)
622
            {
623
                istringstream a0(args[0]);
624
                a0 >> anneal;
625
            }
626
            optimize_valency(me->active_mesh(), anneal);
627
            return;
628
        }
629
 
630
            void console_analyze(MeshEditor* me, const std::vector<std::string> & args)
631
            {
632
                if(wantshelp(args))
633
                {
634
                    me->printf("usage:  harmonics.analyze");
635
                    me->printf("Creates the Laplace Beltrami operator for the mesh and finds all eigensolutions.");
636
                    me->printf("It also projects the vertices onto the eigenvectors - thus transforming the mesh");
637
                    me->printf("to this basis.");
638
                    me->printf("Note that this will stall the computer for a large mesh - as long as we use Lapack.");
639
                    return;
640
                }
641
                me->harmonics_analyze_mesh();
642
                return;
643
            }
644
 
645
 
663 janba 646
        void console_partial_reconstruct(MeshEditor* me, const std::vector<std::string> & args)
647
        {
648
            if(args.size() != 3)
649
                me->printf("usage: haramonics.partial_reconstruct <e0> <e1> <s>");
650
 
651
            if(wantshelp(args)) {
652
                me->printf("Reconstruct from projections onto eigenvectors. The two first arguments indicate");
653
                me->printf("the eigenvector interval that we reconstruct from. The last argument is the ");
654
                me->printf("scaling factor. Thus, for a vertex, v, the formula for computing the position, p, is:");
655
                me->printf("for (i=e0; i<=e1;++i) p += proj[i] * Q[i][v] * s;");
656
                me->printf("where proj[i] is the 3D vector containing the x, y, and z projections of the mesh onto");
657
                me->printf("eigenvector i. Q[i][v] is the v'th coordinate of the i'th eigenvector.");
658
                me->printf("Note that if vertex coordinates are not first reset, the result is probably unexpected.");
659
            }
660
            me->save_active_mesh();
661
 
662
            if(args.size() != 3)
663
                return;
664
 
665
            int E0,E1;
666
            float scale;
667
            istringstream a0(args[0]);
668
            a0 >> E0;
669
            istringstream a1(args[1]);
670
            a1 >> E1;
671
            istringstream a2(args[2]);
672
            a2 >> scale;
673
            me->harmonics_partial_reconstruct(E0,E1,scale);
674
            return;
675
        }
647 janba 676
 
663 janba 677
        void console_reset_shape(MeshEditor* me, const std::vector<std::string> & args)
678
        {
679
            if(wantshelp(args))
680
            {
681
                me->printf("usage: harmonics.reset_shape ");
682
                me->printf("Simply sets all vertices to 0,0,0. Call this before doing partial_reconstruct");
683
                me->printf("unless you know what you are doing.");
684
                return;
685
            }
686
            me->save_active_mesh();
687
            me->harmonics_reset_shape();
688
            return;
689
        }
647 janba 690
 
663 janba 691
 
647 janba 692
        void console_close_holes(MeshEditor* me, const std::vector<std::string> & args)
693
        {
694
            if(wantshelp(args))
695
            {
696
                me->printf("usage: cleanup.close_holes");
697
                me->printf("This function closes holes. It simply follows the loop of halfvectors which");
698
                me->printf("enclose the hole and add a face to which they all point.");
699
                return;
700
            }
701
            me->save_active_mesh();
702
 
703
            close_holes(me->active_mesh());
704
            return;
705
        }
706
 
707
        void console_reload(MeshEditor* me, const std::vector<std::string> & args)
708
        {
709
            if(wantshelp(args))
710
            {
711
                me->printf("usage:  load <file>");
712
                me->printf("(Re)loads the current file if no argument is given, but");
713
                me->printf("if an argument is given, then that becomes the current file");
714
                return;
715
            }
716
            me->save_active_mesh();
717
 
718
            if(!me->reload_active_from_file(args.size() > 0 ? args[0]:""))
719
                me->printf("failed to load");
720
 
721
            return;
722
        }
723
 
724
 
725
        void console_add_mesh(MeshEditor* me, const std::vector<std::string> & args)
726
        {
727
            if(wantshelp(args))
728
            {
729
                me->printf("usage:  add_mesh <file>");
730
                me->printf("Loads the file but without clearing the mesh. Thus, the loaded mesh is added to the");
731
                me->printf("current model.");
732
                return;
733
            }
734
            me->save_active_mesh();
735
 
736
            if(!me->add_to_active_from_file(args.size() > 0 ? args[0]:""))
737
                me->printf("failed to load");
738
 
739
            return;
740
        }
741
 
742
        void console_valid(MeshEditor* me, const std::vector<std::string> & args)
743
        {
744
            if(wantshelp(args))
745
            {
746
                me->printf("usage:  validity");
747
                me->printf("Tests validity of Manifold");
748
                return;
749
            }
750
            if(valid(me->active_mesh()))
751
                me->printf("Mesh is valid");
752
            else
753
                me->printf("Mesh is invalid - check console output");
754
            return;
755
        }
756
 
757
        void console_Dijkstra(MeshEditor* me, const std::vector<std::string> & args)
758
        {
759
            if(wantshelp(args))
760
            {
761
                me->printf("usage:  Dijkstra");
762
                return;
763
            }
764
 
765
            Manifold& m = me->active_mesh();
766
 
767
 
768
            VertexAttributeVector<double> dist(m.allocated_vertices(), DBL_MAX);
769
            VertexAttributeVector<int> visited(m.allocated_vertices(), 0);
770
            VertexID v = *m.vertices_begin();
771
            dist[v]=0;
772
            priority_queue<pair<double,VertexID>> pq;
773
            pq.push(make_pair(-dist[v], v));
774
            double max_dist;
775
            while(!pq.empty())
776
            {
777
                VertexID v = pq.top().second;
778
                max_dist = dist[v];
779
                pq.pop();
780
 
781
                if(!visited[v]){
782
                    visited[v]=1;
783
 
784
                    for(Walker w = m.walker(v); !w.full_circle(); w = w.circulate_vertex_ccw())
785
                        if(!visited[w.vertex()])
786
                        {
787
                            double d = dist[v] + length(m, w.halfedge());
788
                            if(d<dist[w.vertex()]) {
789
                                dist[w.vertex()] = d;
790
                                pq.push(make_pair(-d, w.vertex()));
791
                            }
792
                        }
793
                }
794
            }
795
 
796
            for(auto vid : m.vertices()) {
797
                DebugRenderer::vertex_colors[vid] = Vec3f(1-dist[vid]/max_dist,0,0);
798
                cout << dist[vid] << endl;
799
            }
800
            for(auto fid : m.faces())
801
                DebugRenderer::face_colors[fid] = Vec3f(0.3);
802
 
803
            for(auto hid : m.halfedges()) {
804
                Walker w = m.walker(hid);
805
                DebugRenderer::edge_colors[hid] = Vec3f(1.0-max(dist[w.vertex()],dist[w.opp().vertex()])/max_dist,0,0);
806
            }
807
            return;
808
        }
666 janba 809
 
810
        const Vec3f& get_color(int i)
811
        {
812
            static Vec3f ctable[100000];
813
            static bool was_here;
814
            gel_srand(0);
815
            if(!was_here)
816
            {
817
                was_here = true;
818
                ctable[0] = Vec3f(0);
819
                for(int j=1;j<100000;++j)
820
                    ctable[j] = Vec3f(0.3)+0.7*normalize(Vec3f(gel_rand(),gel_rand(),gel_rand()));
821
                ctable[3] = Vec3f(1,0,0);
822
                ctable[4] = Vec3f(0,1,0);
823
                ctable[5] = Vec3f(0,0,1);
824
                ctable[6] = Vec3f(1,0,1);
825
            }
826
            return ctable[i%100000];
827
        }
828
 
647 janba 829
        void console_info(MeshEditor* me, const std::vector<std::string> & args)
830
        {
831
            if(wantshelp(args))
832
            {
833
                me->printf("usage:  info");
834
                me->printf("Provides information about mesh.");
835
                return;
836
            }
837
            Vec3d p0, p7;
838
            bbox(me->active_mesh(), p0, p7);
839
            stringstream bbox_corners;
840
            bbox_corners << p0 << " - " << p7 << endl;
841
            me->printf("Bounding box corners : %s", bbox_corners.str().c_str());
842
            map<int,int> val_hist;
843
 
666 janba 844
            Manifold& m = me->active_mesh();
845
            for(HalfEdgeID h: m.halfedges())
846
                DebugRenderer::edge_colors[h] = Vec3f(0.3);
847
            for(VertexID v: m.vertices())
647 janba 848
            {
666 janba 849
                int val = valency(m,v);
850
                DebugRenderer::vertex_colors[v] = get_color(val);
647 janba 851
                ++val_hist[val];
666 janba 852
 
853
                if(val != 4)
854
                    circulate_vertex_ccw(m, v, [&](HalfEdgeID h){
855
                        Walker w = m.walker(h);
856
                        DebugRenderer::edge_colors[h] = Vec3f(1);
857
                        DebugRenderer::edge_colors[w.opp().halfedge()] = Vec3f(1);
858
                        while(valency(m, w.vertex())==4) {
859
                            w = w.next().opp().next();
860
                            DebugRenderer::edge_colors[w.halfedge()] = Vec3f(1);
861
                            DebugRenderer::edge_colors[w.opp().halfedge()] = Vec3f(1);
862
                        }
863
                    });
647 janba 864
            }
666 janba 865
            map<int, int> ngon_hist;
866
            for(FaceID f: m.faces()) {
867
                int ne = no_edges(m, f);
868
                ++ngon_hist[ne];
869
                DebugRenderer::face_colors[f] = 0.7*get_color(ne);
870
            }
647 janba 871
 
872
            me->printf("Valency histogam");
873
            for(map<int,int>::iterator iter = val_hist.begin(); iter != val_hist.end(); ++iter)
874
            {
875
                me->printf("%d, %d", iter->first, iter->second);
876
            }
877
 
666 janba 878
            me->printf("Ngon histogam");
879
            for(map<int,int>::iterator iter = ngon_hist.begin(); iter != ngon_hist.end(); ++iter)
880
            {
881
                me->printf("%d, %d", iter->first, iter->second);
882
            }
883
 
884
 
647 janba 885
            me->printf("Mesh contains %d faces", me->active_mesh().no_faces());
886
            me->printf("Mesh contains %d halfedges", me->active_mesh().no_halfedges());
887
            me->printf("Mesh contains %d vertices", me->active_mesh().no_vertices());
888
            return;
889
        }
890
 
891
 
892
        void console_simplify(MeshEditor* me, const std::vector<std::string> & args)
893
        {
894
            if(wantshelp(args))
895
            {
896
                me->printf("usage: simplify <fraction> ");
897
                me->printf("Performs Garland Heckbert (quadric based) mesh simplification.");
898
                me->printf("The only argument is the fraction of vertices to keep.");
899
                return;
900
            }
901
            me->save_active_mesh();
902
 
903
            float keep_fraction;
904
            if(args.size() == 0)
905
            {
906
                me->printf("you must specify fraction of vertices to keep");
907
                return;
908
            }
909
            istringstream a0(args[0]);
910
            a0 >> keep_fraction;
911
 
912
            Vec3d p0, p7;
913
            bbox(me->active_mesh(), p0, p7);
914
            Vec3d d = p7-p0;
915
            float s = 1.0/d.max_coord();
916
            Vec3d pcentre = (p7+p0)/2.0;
917
            for(VertexIDIterator vi = me->active_mesh().vertices_begin(); vi != me->active_mesh().vertices_end(); ++vi){
918
                me->active_mesh().pos(*vi) = (me->active_mesh().pos(*vi) - pcentre) * s;
919
            }
920
            cout << "Timing the Garland Heckbert (quadric based) mesh simplication..." << endl;
921
            Timer timer;
922
            timer.start();
923
 
924
            //simplify
925
            quadric_simplify(me->active_mesh(),keep_fraction,0.0001f,true);
926
 
927
            cout << "Simplification complete, process time: " << timer.get_secs() << " seconds" << endl;
928
 
929
            //clean up the mesh, a lot of edges were just collapsed
930
            me->active_mesh().cleanup();
931
 
932
            for(VertexIDIterator vi = me->active_mesh().vertices_begin(); vi != me->active_mesh().vertices_end(); ++vi)
933
                me->active_mesh().pos(*vi) = me->active_mesh().pos(*vi)*d.max_coord() + pcentre;
934
            return;
935
        }
936
 
937
        void console_vertex_noise(MeshEditor* me, const std::vector<std::string> & args)
938
        {
939
            if(wantshelp(args))
940
            {
941
                me->printf("usage: noise.perturb_vertices <amplitude>");
942
                me->printf("adds a random vector to each vertex. A random vector in the unit cube is generated and");
943
                me->printf("to ensure an isotropic distribution, vectors outside the unit ball are discarded.");
944
                me->printf("The vector is multiplied by the average edge length and then by the amplitude specified.");
945
                me->printf("If no amplitude is specified, the default (0.5) is used.");
946
                return;
947
            }
948
            me->save_active_mesh();
949
 
950
            float avg_length = average_edge_length(me->active_mesh());
951
 
952
            float noise_amplitude = 0.5f;
953
            if(args.size() > 0) {
954
                istringstream a0(args[0]);
955
                a0 >> noise_amplitude;
956
            }
957
 
958
            gel_srand(0);
959
            for(VertexIDIterator vi = me->active_mesh().vertices_begin(); vi != me->active_mesh().vertices_end(); ++vi){
960
                Vec3d v;
961
                do{
962
                    v = Vec3d(gel_rand(),gel_rand(),gel_rand());
963
                    v /= (float)(GEL_RAND_MAX);
964
                    v -= Vec3d(0.5);
965
                    v *= 2.0;
966
                }
967
                while(sqr_length(v) > 1.0);
968
 
969
                v *= noise_amplitude;
970
                v *= avg_length;
971
                me->active_mesh().pos(*vi) += v;
972
            }
973
            return;
974
        }
975
 
976
        void console_perpendicular_vertex_noise(MeshEditor* me, const std::vector<std::string> & args)
977
        {
978
            if(wantshelp(args)) {
979
                me->printf("usage: noise.perturb_vertices_perpendicular <amplitude>");
980
                me->printf("adds the normal times a random scalar times amplitude times");
981
                me->printf("times average edge length to the vertex. (default amplitude=0.5)");
982
                return;
983
            }
984
            me->save_active_mesh();
985
 
986
            float avg_length = average_edge_length(me->active_mesh());
987
 
988
            float noise_amplitude = 0.5;
989
            if(args.size() > 0)
990
            {
991
                istringstream a0(args[0]);
992
                a0 >> noise_amplitude;
993
            }
994
 
995
            VertexAttributeVector<Vec3d> normals(me->active_mesh().allocated_vertices());
996
            for(VertexIDIterator vi = me->active_mesh().vertices_begin(); vi != me->active_mesh().vertices_end(); ++vi)
997
                normals[*vi] = normal(me->active_mesh(), *vi);
998
 
999
            gel_srand(0);
1000
            for(VertexIDIterator vi = me->active_mesh().vertices_begin(); vi != me->active_mesh().vertices_end(); ++vi)
1001
            {
1002
                float rval = 0.5-gel_rand() / float(GEL_RAND_MAX);
1003
                me->active_mesh().pos(*vi) += normals[*vi]*rval*noise_amplitude*avg_length*2.0;
1004
            }
1005
            return;
1006
        }
1007
 
1008
        void console_noisy_flips(MeshEditor* me, const std::vector<std::string> & args)
1009
        {
1010
            if(wantshelp(args)){
1011
                me->printf("usage:  noise.perturb_topology <iter>");
1012
                me->printf("Perform random flips. iter (default=1) is the number of iterations.");
1013
                me->printf("mostly for making nasty synthetic test cases.");
1014
                return;
1015
            }
1016
            me->save_active_mesh();
1017
 
1018
            int iter = 1;
1019
            if(args.size() > 0){
1020
                istringstream a0(args[0]);
1021
                a0 >> iter;
1022
            }
1023
 
1024
            randomize_mesh(me->active_mesh(),  iter);
1025
            return;
1026
        }
1027
 
1028
        void console_laplacian_smooth(MeshEditor* me, const std::vector<std::string> & args)
1029
        {
1030
            if(wantshelp(args)) {
1031
                me->printf("usage:  smooth.laplacian <weight> <iter>");
1032
                me->printf("Perform Laplacian smoothing. weight is the scaling factor for the Laplacian.");
1033
                me->printf("default weight = 1.0. Default number of iterations = 1");
1034
                return;
1035
            }
1036
            me->save_active_mesh();
1037
 
1038
            float t=1.0;
1039
            if(args.size() > 0){
1040
                istringstream a0(args[0]);
1041
                a0 >> t;
1042
            }
1043
            int iter = 1;
1044
            if(args.size()>1){
1045
                istringstream a0(args[1]);
1046
                a0 >> iter;
1047
            }
1048
            Util::Timer tim;
1049
            tim.start();
1050
            /// Simple laplacian smoothing with an optional weight.
1051
            laplacian_smooth(me->active_mesh(), t, iter);
1052
            cout << "It took "<< tim.get_secs();
1053
            return;
1054
        }
1055
 
1056
 
1057
        void console_mean_curvature_smooth(MeshEditor* me, const std::vector<std::string> & args){
1058
            if(wantshelp(args)) {
1059
                me->printf("usage:  smooth.mean_curvature <weight> <iter>");
1060
                me->printf("Perform mean curvature smoothing. weight is the scaling factor for the");
1061
                me->printf("mean curvature vector which has been normalized by dividing by edge lengths");
1062
                me->printf("this allows for larger steps as suggested by Desbrun et al.");
1063
                me->printf("default weight = 1.0. Default number of iterations = 1");
1064
                return;
1065
            }
1066
            me->save_active_mesh();
1067
 
1068
            double t=1.0;
1069
            if(args.size() > 0){
1070
                istringstream a0(args[0]);
1071
                a0 >> t;
1072
            }
1073
            int iter=1;
1074
            if(args.size() > 1){
1075
                istringstream a0(args[1]);
1076
                a0 >> iter;
1077
            }
1078
            VertexAttributeVector<Vec3d> new_pos(me->active_mesh().allocated_vertices());
1079
            for(int j = 0; j < iter; ++j){
1080
                for(VertexIDIterator v = me->active_mesh().vertices_begin(); v != me->active_mesh().vertices_end(); ++v) {
1081
                    Vec3d m;
1082
                    double w_sum;
1083
                    unnormalized_mean_curvature_normal(me->active_mesh(), *v, m, w_sum);
1084
                    new_pos[*v] = Vec3d(me->active_mesh().pos(*v))  + (t * m/w_sum);
1085
                }
1086
                for(VertexIDIterator v = me->active_mesh().vertices_begin(); v != me->active_mesh().vertices_end(); ++v)
1087
                    me->active_mesh().pos(*v) = new_pos[*v];
1088
            }
1089
            return;
1090
        }
1091
 
1092
        void console_taubin_smooth(MeshEditor* me, const std::vector<std::string> & args)
1093
        {
1094
            if(wantshelp(args)){
1095
                me->printf("usage:  smooth.taubin <iter>");
1096
                me->printf("Perform Taubin smoothing. iter (default=1) is the number of iterations.");
1097
                return;
1098
            }
1099
            me->save_active_mesh();
1100
 
1101
            int iter = 1;
1102
            if(args.size() > 0){
1103
                istringstream a0(args[0]);
1104
                a0 >> iter;
1105
            }
1106
            /// Taubin smoothing is similar to laplacian smoothing but reduces shrinkage
1107
            taubin_smooth(me->active_mesh(),  iter);
1108
 
1109
            return;
1110
        }
1111
 
1112
        void console_fvm_anisotropic_smooth(MeshEditor* me, const std::vector<std::string> & args)
1113
        {
1114
            if(wantshelp(args)){
1115
                me->printf("usage: smooth.fuzzy_vector_median <iter>");
1116
                me->printf("Smooth normals using fuzzy vector median smoothing. iter (default=1) is the number of iterations");
1117
                me->printf("This function does a very good job of preserving sharp edges.");
1118
                return;
1119
            }
1120
            me->save_active_mesh();
1121
 
1122
            int iter=1;
1123
            if(args.size() > 0){
1124
                istringstream a0(args[0]);
1125
                a0 >> iter;
1126
            }
1127
            // Fuzzy vector median smoothing is effective when it comes to preserving sharp edges.
1128
            anisotropic_smooth(me->active_mesh(),  iter, FVM_NORMAL_SMOOTH);
1129
 
1130
            return;
1131
        }
1132
 
1133
        void console_bilateral_anisotropic_smooth(MeshEditor* me, const std::vector<std::string> & args)
1134
        {
1135
            if(wantshelp(args)){
1136
                me->printf("usage: smooth.fuzzy_vector_median <iter>");
1137
                me->printf("Smooth normals using fuzzy vector median smoothing. iter (default=1) is the number of iterations");
1138
                me->printf("This function does a very good job of preserving sharp edges.");
1139
                return;
1140
            }
1141
            me->save_active_mesh();
1142
 
1143
            int iter=1;
1144
            if(args.size() > 0){
1145
                istringstream a0(args[0]);
1146
                a0 >> iter;
1147
            }
1148
 
1149
            anisotropic_smooth(me->active_mesh(),  iter, BILATERAL_NORMAL_SMOOTH);
1150
 
1151
            return;
1152
        }
1153
 
1154
        void console_triangulate(MeshEditor* me, const std::vector<std::string> & args)
1155
        {
1156
            if(wantshelp(args)) {
1157
                me->printf("usage:  triangulate");
1158
                me->printf("This function triangulates all non triangular faces of the mesh.");
1159
                me->printf("you may want to call it after hole closing. For a polygon it simply connects");
1160
                me->printf("the two closest vertices in a recursive manner until only triangles remain");
1161
                return;
1162
            }
1163
            me->save_active_mesh();
1164
 
1165
            shortest_edge_triangulate(me->active_mesh());
1166
            me->active_mesh().cleanup();
1167
            valid(me->active_mesh());
1168
            return;
1169
        }
1170
 
1171
 
1172
        void console_remove_caps(MeshEditor* me, const std::vector<std::string> & args)
1173
        {
1174
            if(wantshelp(args)) {
1175
                me->printf("usage:  cleanup.remove_caps thresh");
1176
                me->printf("Remove caps (triangles with one very big angle). The thresh argument is the fraction of PI to");
1177
                me->printf("use as threshold for big angle. Default is 0.85. Caps are removed by flipping.");
1178
                return;
1179
            }
1180
            me->save_active_mesh();
1181
 
1182
            float t = 0.85f;
1183
            if(args.size() > 0){
1184
                istringstream a0(args[0]);
1185
                a0 >> t;
1186
            }
1187
            remove_caps(me->active_mesh(), static_cast<float>(M_PI) *t);
1188
            me->active_mesh().cleanup();
1189
 
1190
            return;
1191
        }
1192
 
1193
        void console_remove_needles(MeshEditor* me, const std::vector<std::string> & args)
1194
        {
1195
            if(wantshelp(args)){
1196
                me->printf("usage: cleanup.remove_needles <thresh>");
1197
                me->printf("Removes very short edges by collapse. thresh is multiplied by the average edge length");
1198
                me->printf("to get the length shorter than which we collapse. Default = 0.1");
1199
                return;
1200
            }
1201
            me->save_active_mesh();
1202
 
1203
            float thresh = 0.1f;
1204
            if(args.size() > 0){
1205
                istringstream a0(args[0]);
1206
                a0 >> thresh;
1207
            }
1208
            float avg_length = average_edge_length(me->active_mesh());
1209
            remove_needles(me->active_mesh(), thresh * avg_length);
1210
            me->active_mesh().cleanup();
1211
 
1212
            return;
1213
        }
1214
 
666 janba 1215
        void console_flip_orientation(MeshEditor* me, const std::vector<std::string> & args)
1216
        {
1217
            if(wantshelp(args)){
1218
                me->printf("usage: cleanup.flip_orientation");
1219
                me->printf("reorients all faces - flipping normal direction");
1220
                return;
1221
            }
1222
            me->save_active_mesh();
1223
            flip_orientation(me->active_mesh());
1224
            return;
1225
        }
1226
 
1227
 
647 janba 1228
        void console_undo(MeshEditor* me, const std::vector<std::string> & args)
1229
        {
1230
            if(wantshelp(args)) {
1231
                me->printf("usage:  undo");
1232
                me->printf("This function undoes one operation. Repeated undo does nothing");
1233
                return;
1234
            }
1235
            me->restore_active_mesh();
1236
            return;
1237
        }
1238
 
662 janba 1239
        void console_save_trackball(MeshEditor* me, const std::vector<std::string> & args)
1240
        {
1241
            if(wantshelp(args)) {
1242
                me->printf("usage:  display.save_trackball");
1243
                me->printf("This function saves the trackball to disk");
1244
                return;
1245
            }
1246
            me->save_ball();
1247
            return;
1248
        }
1249
 
1250
        void console_load_trackball(MeshEditor* me, const std::vector<std::string> & args)
1251
        {
1252
            if(wantshelp(args)) {
1253
                me->printf("usage:  display.load_trackball");
1254
                me->printf("This function loads the trackball from disk");
1255
                return;
1256
            }
1257
            me->load_ball();
1258
            return;
1259
        }
1260
 
647 janba 1261
 
1262
    }
1263
 
1264
 
1265
    void MeshEditor::register_console_function(const std::string& name,
1266
                                               const std::function<void(MeshEditor*, const std::vector<std::string>&)>& con_fun,
1267
                                               const std::string& help_txt)
1268
    {
1269
        std::function<void (const std::vector<std::string>&)> f = bind(con_fun, this, placeholders::_1);
1270
        theConsole.reg_cmdN(name, f, help_txt);
1271
    }
1272
 
1273
    void MeshEditor::keyparse(unsigned short key){
1274
        //toggle console with ESC
1275
        if (key == 27)
1276
        {
1277
            console_visible = !console_visible;
1278
            return;
1279
        }
1280
 
1281
        if (console_visible)
1282
        {
662 janba 1283
            static Timer tim;
1284
            if(key==13)
1285
                tim.start();
647 janba 1286
            theConsole.keyboard(key);
1287
            if(key == 13)
1288
            {
1289
                active_visobj().post_create_display_list();
662 janba 1290
                double t = tim.get_secs();
1291
                printf("%f seconds",t);
647 janba 1292
            }
1293
            return;
1294
        }
1295
        else {
1296
 
1297
            switch(key) {
666 janba 1298
                    case 'R':
1299
                {
1300
                    theConsole.key_up();
1301
                    theConsole.keyboard(13);
1302
                    active_visobj().post_create_display_list();
1303
                }
1304
                    break;
647 janba 1305
                case 'q': exit(0);
1306
                case '\033':
1307
                    console_visible = false;
1308
                    break;
1309
                case '1':
1310
                case '2':
1311
                case '3':
1312
                case '4':
1313
                case '5':
1314
                case '6':
1315
                case '7':
1316
                case '8':
1317
                case '9':
1318
                {
1319
                    int w[4];
1320
                    glGetIntegerv(GL_VIEWPORT, w);
1321
                    active = key - '1';
1322
                    active_view_control().reshape(w[2],w[3]);
1323
                }
1324
                    break;
1325
                case 'f': display_smooth_shading = !display_smooth_shading; break;
1326
                case 'w':
1327
                    display_render_mode = "wire"; break;
1328
                case 'n':
1329
                    display_render_mode = "normal"; break;
1330
                case 'i':
1331
                    display_render_mode = "isophotes"; break;
1332
                case 'r':
1333
                    display_render_mode = "reflection"; break;
1334
                case 'h':
1335
                    display_render_mode = "harmonics"; break;
1336
                case 't':
1337
                    display_render_mode = "toon"; break;
1338
                case 'g':
1339
                    display_render_mode = "glazed"; break;
1340
                case 'a':
1341
                    display_render_mode = "ambient_occlusion"; break;
1342
                case 'c':
1343
                    display_render_mode = "copper"; break;
1344
                case 'C':
1345
                    display_render_mode = "curvature_lines"; break;
1346
                case 'M':
1347
                    display_render_mode = "mean_curvature"; break;
1348
                case 'G':
1349
                    display_render_mode = "gaussian_curvature"; break;
657 janba 1350
                case ' ':
1351
                    active_visobj().clear_selection();
1352
                    break;
1353
 
647 janba 1354
            }
1355
 
1356
            if(key != '\033') post_create_display_list();
1357
        }
1358
 
1359
    }
1360
 
1361
    void MeshEditor::printf(const char* format, ...)
1362
    {
1363
        //format text
1364
        char buffer[1024];
1365
        va_list args;
1366
        va_start(args, format);
1367
        vsprintf(buffer, format, args);
1368
        va_end(args);
1369
        theConsole.print(buffer);
1370
    }
1371
 
1372
    void MeshEditor::key_up(){theConsole.key_up();}
1373
    void MeshEditor::key_down(){theConsole.key_down();}
1374
    void MeshEditor::key_left(){theConsole.key_left();}
1375
    void MeshEditor::key_right(){theConsole.key_right();}
1376
    void MeshEditor::key_home(){theConsole.key_home();}
1377
    void MeshEditor::key_end(){theConsole.key_end();}
1378
 
662 janba 1379
 
1380
 
647 janba 1381
    void MeshEditor::grab_ball(TrackBallAction action, const CGLA::Vec2i& pos){
1382
        active_view_control().grab_ball(action, pos);
1383
    }
1384
    void MeshEditor::roll_ball(const CGLA::Vec2i& pos){
1385
        active_view_control().roll_ball(pos);
1386
    }
1387
    void MeshEditor::release_ball(){
1388
        active_view_control().release_ball();
1389
    }
1390
    bool MeshEditor::try_spinning_ball(){
1391
        return active_view_control().try_spin();
1392
    }
1393
 
662 janba 1394
    void MeshEditor::save_ball() {
1395
        ofstream ofs("trackball.bin", ios_base::binary);
1396
        active_view_control().save(ofs);
1397
 
1398
    }
1399
    void MeshEditor::load_ball() {
1400
        ifstream ifs("trackball.bin", ios_base::binary);
1401
        active_view_control().load(ifs);
1402
 
1403
    }
1404
 
1405
 
656 janba 1406
    bool MeshEditor::grab_mesh(const CGLA::Vec2i& pos)
1407
    {
1408
        if(depth_pick(pos[0], pos[1], depth))
1409
        {
1410
            dragging = true;
1411
            mouse_x = pos[0];
1412
            mouse_y = pos[1];
1413
            Vec3d p0 = screen2world(mouse_x, mouse_y, depth);
1414
            Manifold& m = active_mesh();
1415
            active_visobj().save_old();
1416
            Vec3d c;
1417
            float r;
1418
            bsphere(m, c, r);
1419
            for(auto vid : m.vertices())
1420
            {
1421
                double l = sqr_length(p0-m.pos(vid));
657 janba 1422
                weight_vector[vid] = exp(-l/(brush_size*r*r));
656 janba 1423
            }
1424
            return true;
1425
        }
1426
        return false;
1427
    }
1428
 
1429
    bool MeshEditor::drag_mesh(const CGLA::Vec2i& pos)
1430
    {
1431
        if(dragging)
1432
        {
1433
            Vec3d p0 = screen2world(mouse_x, mouse_y, depth);
1434
            Vec3d p1 = screen2world(pos[0], pos[1], depth);
1435
            Vec3d v = p1-p0;
1436
            Manifold& m = active_mesh();
1437
            for(auto vid : m.vertices())
1438
                m.pos(vid) = active_visobj().mesh_old().pos(vid) + weight_vector[vid] * v;
1439
            post_create_display_list();
1440
            return true;
1441
        }
1442
        return false;
1443
    }
1444
 
1445
    void MeshEditor::release_mesh()
1446
    {
1447
        dragging = false;
1448
    }
1449
 
666 janba 1450
 
1451
 
1452
 
662 janba 1453
    mutex parallel_work;
647 janba 1454
    void MeshEditor::display(int scale){
666 janba 1455
        // Clear screen.
647 janba 1456
        glClearColor(1, 1, 1, 0);
1457
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
662 janba 1458
 
666 janba 1459
        //        parallel_work.lock();
1460
        //        active_visobj().post_create_display_list();
1461
 
1462
 
1463
        // Display object.
647 janba 1464
        active_visobj().display(display_render_mode, theConsole, display_smooth_shading, display_gamma);
666 janba 1465
 
1466
        // Draw console
647 janba 1467
        if(console_visible)
1468
        {
1469
            glUseProgram(0);
1470
            theConsole.display(scale);
1471
        }
666 janba 1472
 
1473
        // Static variable controlling whether we render shadow at all.
1474
        static Console::variable<int> shadow_enable(0);
1475
        shadow_enable.reg(theConsole, "display.shadow.enable", "");
1476
        if(shadow_enable) {
1477
            // Static variables that control the shadow display created and linked to console
1478
            static Console::variable<float> zenith(1.571);
1479
            static Console::variable<float> azimuth(0);
1480
            static Console::variable<float> shadow_alpha(0.3);
1481
            azimuth.reg(theConsole, "display.shadow.azimuth", "");
1482
            zenith.reg(theConsole, "display.shadow.zenith", "");
1483
            shadow_alpha.reg(theConsole, "display.shadow.shadow_alpha", "");
1484
 
1485
 
1486
            // Shadow buffer (really a frame buffer object)
1487
            static ShadowBuffer sb;
1488
 
1489
            // String containing fragment program for shadow rendering
1490
            static string shadow_shdr_fp = "#version 120\n"
1491
            "    uniform sampler2DShadow shadow_map;\n"
1492
            "    uniform mat4 Mat;\n"
1493
            "   uniform float shadow_alpha;\n"
1494
            "    varying vec4 ep;\n"
1495
            "    void main()\n"
1496
            "    {\n"
1497
            "        vec4 light_pos =  Mat * ep;\n"
1498
            "        light_pos.z = max(0.001,min(0.999,light_pos.z-0.003));\n"
1499
            "        if(light_pos.x <=0 || light_pos.x >=1 || light_pos.y <=0 || light_pos.y>=1) gl_FragColor = vec4(1);"
1500
            "   else      gl_FragColor= vec4(1.0-shadow_alpha)+shadow_alpha*0.25*(shadow2D(shadow_map, light_pos.xyz+vec3(0.001,-0.001,0))+shadow2D(shadow_map, light_pos.xyz+vec3(0.001,0.001,0))+shadow2D(shadow_map, light_pos.xyz-vec3(0.001,0.001,0))+shadow2D(shadow_map, light_pos.xyz+vec3(-0.001,0.001,0)));\n"
1501
            "    }\n";
1502
 
1503
            // Shader program for shadow rendering is compiled and linked.
1504
            static GLuint prog = 0;
1505
            if(!prog)
1506
            {
1507
                GLuint vp = create_glsl_shader(GL_VERTEX_SHADER,"#version 120\n varying vec4 ep; void main(){ep = gl_Vertex; gl_Position = ftransform();}");
1508
                GLuint fp = create_glsl_shader(GL_FRAGMENT_SHADER, shadow_shdr_fp);
1509
                prog = glCreateProgram();
1510
 
1511
                glAttachShader(prog, vp);
1512
                glAttachShader(prog, fp);
1513
                glLinkProgram(prog);
1514
            }
1515
 
1516
 
1517
            // Setup OpenGL state for lighting - used when rendering 3D object casting shadow
1518
            Vec4f lpos = Vec4f(cos(azimuth)*cos(zenith),sin(zenith),sin(azimuth)*cos(zenith),0);
1519
            glLightfv(GL_LIGHT0, GL_POSITION, lpos.get());
1520
            Vec4f mamb(.8,.8,.8,0);
1521
            Vec4f lamb(.4,.4,.5,0);
1522
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mamb.get());
1523
            glLightfv(GL_LIGHT0, GL_AMBIENT, lamb.get());
1524
 
1525
            // Get old viewport dimensions. Setup rendering to FBO and set viewport
1526
            // dimensions for rendering shadows.
1527
            GLint viewp[4];
1528
            glGetIntegerv(GL_VIEWPORT, viewp);
1529
            sb.enable();
1530
            glViewport(0, 0, 1024, 1024);
1531
 
1532
            // Setup object transformations using old school GL.
1533
            Mat4x4f m;
1534
            float r = active_visobj().get_bsphere_radius();
1535
            glMatrixMode(GL_MODELVIEW);
1536
            glPushMatrix();
1537
            glLoadIdentity();
1538
            glMatrixMode(GL_PROJECTION);
1539
            glPushMatrix();
1540
            glLoadIdentity();
1541
            glOrtho(-2*r, 2*r, -2*r, 2*r, -2*r, 2*r);
1542
            gluLookAt(0.1*r*cos(azimuth)*cos(zenith),0.1*r*sin(zenith),0.1*r*sin(azimuth)*cos(zenith), 0,0,0, 0,1,0);
1543
 
1544
            // Copy the transformation matrix to user code.
1545
            glGetFloatv(GL_PROJECTION_MATRIX, m.get());
1546
 
1547
            // Draw the object in light space.
1548
            draw(active_visobj().mesh());
1549
 
1550
            // Restore transformation matrices.
1551
            glPopMatrix();
1552
            glMatrixMode(GL_MODELVIEW);
1553
            glPopMatrix();
1554
 
1555
            // Restore the usual on screen framebuffer.
1556
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
1557
            glDrawBuffer(GL_BACK);
1558
            glViewport(0, 0, viewp[2], viewp[3]);
1559
 
1560
            // Use shadow: bind the shadow texture to unit 0.
1561
            sb.bind_textures(0);
1562
 
1563
            // Use the shadow rendering shader program.
1564
            glUseProgram(prog);
1565
            active_visobj().view_control().set_gl_modelview();
1566
            glUniform1i(glGetUniformLocation(prog, "shadow_map"), 0);
1567
            glUniform1f(glGetUniformLocation(prog, "shadow_alpha"), shadow_alpha);
1568
            m = translation_Mat4x4f(Vec3f(0.5)) * scaling_Mat4x4f(Vec3f(0.5)) * transpose(m);
1569
            glUniformMatrix4fv(glGetUniformLocation(prog, "Mat"), 1, 1, m.get());
1570
 
1571
 
1572
            // Setup blending such that the shadow is alpha blended with model.
1573
            glDepthFunc(GL_LEQUAL);
1574
            glEnable(GL_BLEND);
1575
            glBlendFunc(GL_ZERO, GL_SRC_COLOR);
1576
 
1577
            // Draw ground plane for shadows.
1578
            Vec3d p0, p7;
1579
            bbox(active_visobj().mesh(), p0, p7);
1580
            glBegin(GL_QUADS);
1581
            glVertex3f(-100*r, p0[1],-100*r);
1582
            glVertex3f(-100*r, p0[1],100*r);
1583
            glVertex3f(100*r, p0[1],100*r);
1584
            glVertex3f(100*r, p0[1],-100*r);
1585
            glEnd();
1586
 
1587
            // Draw model again ... just to add shadow.
1588
            draw(active_visobj().mesh());
1589
 
1590
            // Disable blending and shader program.
1591
            glDisable(GL_BLEND);
1592
            glUseProgram(0);
1593
        }
1594
        //        parallel_work.unlock();
1595
        //        std::this_thread::sleep_for(std::chrono::milliseconds(10));
647 janba 1596
    }
1597
 
1598
    void MeshEditor::reshape(int w, int h) {
1599
        for(VisObj& v : vo)
1600
            v.view_control().reshape(w, h);
1601
    }
1602
 
1603
    void MeshEditor::init() {
1604
        glewInit();
1605
 
1606
        GLint vp[4];
1607
        glGetIntegerv(GL_VIEWPORT, vp);
1608
        for(VisObj& vis_obj : vo)
1609
            vis_obj.view_control().reshape(vp[2], vp[3]);
1610
 
1611
        glEnable(GL_CULL_FACE);
1612
        glCullFace(GL_BACK);
1613
        glEnable(GL_LIGHTING);
1614
        glEnable(GL_LIGHT0);
1615
        glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
1616
 
1617
        glMatrixMode(GL_MODELVIEW);
1618
        glLoadIdentity();
1619
        glClearColor(1,1,0, 0.f);
1620
        glColor4f(1.0f, 1.0f, 1.0f, 0.f);
1621
        float material[4] = {1,1,1,1};
1622
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material);
1623
        glEnable(GL_DEPTH_TEST);
1624
 
1625
        register_console_function("simplify", console_simplify,"");
1626
 
1627
        register_console_function("ridge_lines", console_ridge_lines,"");
1628
 
1629
        register_console_function("smooth.mean_curvature", console_mean_curvature_smooth,"");
1630
        register_console_function("smooth.laplacian", console_laplacian_smooth,"");
1631
        register_console_function("smooth.taubin", console_taubin_smooth,"");
1632
        register_console_function("smooth.fuzzy_vector_median_anisotropic", console_fvm_anisotropic_smooth ,"");
1633
        register_console_function("smooth.bilateral_anisotropic", console_bilateral_anisotropic_smooth ,"");
1634
 
1635
        register_console_function("optimize.valency", console_optimize_valency,"");
1636
        register_console_function("optimize.minimize_dihedral_angles", console_minimize_dihedral,"");
1637
        register_console_function("optimize.minimize_curvature", console_minimize_curvature,"");
1638
        register_console_function("optimize.maximize_min_angle", console_maximize_min_angle,"");
1639
        register_console_function("cleanup.close_holes", console_close_holes,"");
1640
        register_console_function("load_mesh", console_reload,"");
1641
        register_console_function("add_mesh", console_add_mesh,"");
1642
 
663 janba 1643
        register_console_function("cleanup.stitch", console_stitch,"");
666 janba 1644
        register_console_function("cleanup.remove_val2", console_remove_val2, "");
1645
        register_console_function("cleanup.flip_orientation", console_flip_orientation,"");
647 janba 1646
        register_console_function("cleanup.remove_caps", console_remove_caps,"");
1647
        register_console_function("cleanup.remove_needles", console_remove_needles,"");
1648
        register_console_function("triangulate", console_triangulate,"");
1649
        register_console_function("refine.split_edges", console_refine_edges,"");
1650
        register_console_function("refine.split_faces", console_refine_faces,"");
1651
        register_console_function("subdivide.catmull_clark", console_cc_subdivide,"");
666 janba 1652
        register_console_function("subdivide.rootcc", console_root_cc_subdivide,"");
647 janba 1653
        register_console_function("subdivide.loop", console_loop_subdivide,"");
1654
        register_console_function("subdivide.root3", console_root3_subdivide,"");
1655
        register_console_function("subdivide.doo_sabin", console_doosabin_subdivide,"");
1656
        register_console_function("subdivide.butterfly", console_butterfly_subdivide,"");
1657
        register_console_function("save_mesh", console_save,"");
1658
        register_console_function("noise.perturb_vertices", console_vertex_noise,"");
1659
        register_console_function("noise.perturb_vertices_perpendicular", console_perpendicular_vertex_noise,"");
1660
        register_console_function("noise.perturb_topology", console_noisy_flips,"");
1661
 
1662
        register_console_function("dual", console_dual,"");
1663
        register_console_function("flatten", console_flatten,"");
1664
 
1665
        register_console_function("align", console_align,"");
1666
        register_console_function("undo", console_undo,"");
1667
 
1668
        register_console_function("validity", console_valid,"");
1669
        register_console_function("info", console_info,"");
1670
 
663 janba 1671
        register_console_function("harmonics.reset_shape", console_reset_shape, "");
647 janba 1672
        register_console_function("harmonics.analyze", console_analyze, "");
663 janba 1673
        register_console_function("harmonics.partial_reconstruct", console_partial_reconstruct,"");
647 janba 1674
 
1675
        register_console_function("Dijkstra", console_Dijkstra,"");
1676
 
662 janba 1677
        register_console_function("display.save_trackball", console_save_trackball, "Saves trackball to disk");
1678
        register_console_function("display.load_trackball", console_load_trackball, "Load trackball to disk");
1679
 
647 janba 1680
        register_console_function("transform.scale", console_scale, "Scale mesh");
657 janba 1681
        register_console_function("test", console_test, "Test some shit");
647 janba 1682
        active.reg(theConsole, "active_mesh", "The active mesh");
1683
        display_render_mode.reg(theConsole, "display.render_mode", "Display render mode");
657 janba 1684
        brush_size.reg(theConsole, "brush_size", "Size of brush used for editing");
647 janba 1685
        display_smooth_shading.reg(theConsole, "display.smooth_shading", "1 for smooth shading 0 for flat");
1686
        display_gamma.reg(theConsole, "display.gamma", "The gamma setting for the display");
1687
 
1688
        theConsole.print("Welcome to MeshEdit");
1689
        theConsole.newline();
1690
    }
1691
 
1692
    bool MeshEditor::add_file(const std::string& str)
1693
    {
1694
        while (active_mesh().no_vertices()>0 && active<NO_MESHES)
1695
            active  = active + 1;
1696
        if(active == NO_MESHES)
1697
            active = 0;
1698
        if(active_visobj().reload(str)) {
1699
            active_visobj().post_create_display_list();
1700
            return true;
1701
        }
1702
        return false;
1703
    }
1704
 
1705
    bool MeshEditor::reload_active_from_file(const std::string& str)
1706
    {
1707
        if(active_visobj().reload(str)) {
1708
            active_visobj().post_create_display_list();
1709
            return true;
1710
        }
1711
        return false;
1712
    }
1713
 
1714
    bool MeshEditor::add_to_active_from_file(const std::string& str)
1715
    {
1716
        if(active_visobj().add_mesh(str)) {
1717
            active_visobj().post_create_display_list();
1718
            return  true;
1719
        }
1720
        return false;
1721
    }
1722
 
1723
 
1724
}