~ubuntu-branches/ubuntu/utopic/slic3r/utopic

« back to all changes in this revision

Viewing changes to lib/Slic3r/GUI/PreviewCanvas.pm

  • Committer: Package Import Robot
  • Author(s): Chow Loong Jin
  • Date: 2014-06-17 01:27:26 UTC
  • Revision ID: package-import@ubuntu.com-20140617012726-2wrs4zdo251nr4vg
Tags: upstream-1.1.4+dfsg
ImportĀ upstreamĀ versionĀ 1.1.4+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package Slic3r::GUI::PreviewCanvas;
 
2
use strict;
 
3
use warnings;
 
4
 
 
5
use Wx::Event qw(EVT_PAINT EVT_SIZE EVT_ERASE_BACKGROUND EVT_IDLE EVT_MOUSEWHEEL EVT_MOUSE_EVENTS);
 
6
# must load OpenGL *before* Wx::GLCanvas
 
7
use OpenGL qw(:glconstants :glfunctions :glufunctions);
 
8
use base qw(Wx::GLCanvas Class::Accessor);
 
9
use Math::Trig qw(asin);
 
10
use List::Util qw(reduce min max first);
 
11
use Slic3r::Geometry qw(X Y Z MIN MAX triangle_normal normalize deg2rad tan);
 
12
use Wx::GLCanvas qw(:all);
 
13
 
 
14
__PACKAGE__->mk_accessors( qw(quat dirty init mview_init
 
15
                              object_bounding_box object_shift
 
16
                              volumes initpos
 
17
                              sphi stheta
 
18
                              cutting_plane_z
 
19
                              ) );
 
20
 
 
21
use constant TRACKBALLSIZE => 0.8;
 
22
use constant TURNTABLE_MODE => 1;
 
23
use constant SELECTED_COLOR => [0,1,0,1];
 
24
use constant COLORS => [ [1,1,1], [1,0.5,0.5], [0.5,1,0.5], [0.5,0.5,1] ];
 
25
 
 
26
# make OpenGL::Array thread-safe
 
27
*OpenGL::Array::CLONE_SKIP = sub { 1 };
 
28
 
 
29
sub new {
 
30
    my ($class, $parent, $object) = @_;
 
31
    my $self = $class->SUPER::new($parent);
 
32
   
 
33
    $self->quat((0, 0, 0, 1));
 
34
    $self->sphi(45);
 
35
    $self->stheta(-45);
 
36
 
 
37
    $self->load_object($object);
 
38
    
 
39
    EVT_PAINT($self, sub {
 
40
        my $dc = Wx::PaintDC->new($self);
 
41
        $self->Render($dc);
 
42
    });
 
43
    EVT_SIZE($self, sub { $self->dirty(1) });
 
44
    EVT_IDLE($self, sub {
 
45
        return unless $self->dirty;
 
46
        return if !$self->IsShownOnScreen;
 
47
        $self->Resize( $self->GetSizeWH );
 
48
        $self->Refresh;
 
49
    });
 
50
    EVT_MOUSEWHEEL($self, sub {
 
51
        my ($self, $e) = @_;
 
52
        
 
53
        my $zoom = ($e->GetWheelRotation() / $e->GetWheelDelta() / 10);
 
54
        $zoom = $zoom > 0 ?  (1.0 + $zoom) : 1 / (1.0 - $zoom);
 
55
        my @pos3d = $self->mouse_to_3d($e->GetX(), $e->GetY());
 
56
        $self->ZoomTo($zoom, $pos3d[0], $pos3d[1]);
 
57
        
 
58
        $self->Refresh;
 
59
    });
 
60
    EVT_MOUSE_EVENTS($self, sub {
 
61
        my ($self, $e) = @_;
 
62
 
 
63
        if ($e->Dragging() && $e->LeftIsDown()) {
 
64
            $self->handle_rotation($e);
 
65
        } elsif ($e->Dragging() && $e->RightIsDown()) {
 
66
            $self->handle_translation($e);
 
67
        } elsif ($e->LeftUp() || $e->RightUp()) {
 
68
            $self->initpos(undef);
 
69
        } else {
 
70
            $e->Skip();
 
71
        }
 
72
    });
 
73
    
 
74
    return $self;
 
75
}
 
76
 
 
77
sub load_object {
 
78
    my ($self, $object) = @_;
 
79
    
 
80
    my $bb = $object->raw_mesh->bounding_box;
 
81
    my $center = $bb->center;
 
82
    $self->object_shift(Slic3r::Pointf3->new(-$center->x, -$center->y, -$bb->z_min));  #,,
 
83
    $bb->translate(@{ $self->object_shift });
 
84
    $self->object_bounding_box($bb);
 
85
    
 
86
    # group mesh(es) by material
 
87
    my @materials = ();
 
88
    $self->volumes([]);
 
89
    
 
90
    # sort volumes: non-modifiers first
 
91
    my @volumes = sort { ($a->modifier // 0) <=> ($b->modifier // 0) } @{$object->volumes};
 
92
    foreach my $volume (@volumes) {
 
93
        my $mesh = $volume->mesh->clone;
 
94
        $mesh->translate(@{ $self->object_shift });  
 
95
        
 
96
        my $material_id = $volume->material_id // '_';
 
97
        my $color_idx = first { $materials[$_] eq $material_id } 0..$#materials;
 
98
        if (!defined $color_idx) {
 
99
            push @materials, $material_id;
 
100
            $color_idx = $#materials;
 
101
        }
 
102
        
 
103
        my $color = [ @{COLORS->[ $color_idx % scalar(@{&COLORS}) ]} ];
 
104
        push @$color, $volume->modifier ? 0.5 : 1;
 
105
        push @{$self->volumes}, my $v = {
 
106
            color => $color,
 
107
        };
 
108
        
 
109
        {
 
110
            my $vertices = $mesh->vertices;
 
111
            my @verts = map @{ $vertices->[$_] }, map @$_, @{$mesh->facets};
 
112
            $v->{verts} = OpenGL::Array->new_list(GL_FLOAT, @verts);
 
113
        }
 
114
        
 
115
        {
 
116
            my @norms = map { @$_, @$_, @$_ } @{$mesh->normals};
 
117
            $v->{norms} = OpenGL::Array->new_list(GL_FLOAT, @norms);
 
118
        }
 
119
    }
 
120
}
 
121
 
 
122
sub SetCuttingPlane {
 
123
    my ($self, $z) = @_;
 
124
    $self->cutting_plane_z($z);
 
125
}
 
126
 
 
127
# Given an axis and angle, compute quaternion.
 
128
sub axis_to_quat {
 
129
    my ($ax, $phi) = @_;
 
130
    
 
131
    my $lena = sqrt(reduce { $a + $b } (map { $_ * $_ } @$ax));
 
132
    my @q = map { $_ * (1 / $lena) } @$ax;
 
133
    @q = map { $_ * sin($phi / 2.0) } @q;
 
134
    $q[$#q + 1] = cos($phi / 2.0);
 
135
    return @q;
 
136
}
 
137
 
 
138
# Project a point on the virtual trackball. 
 
139
# If it is inside the sphere, map it to the sphere, if it outside map it
 
140
# to a hyperbola.
 
141
sub project_to_sphere {
 
142
    my ($r, $x, $y) = @_;
 
143
    
 
144
    my $d = sqrt($x * $x + $y * $y);
 
145
    if ($d < $r * 0.70710678118654752440) {     # Inside sphere
 
146
        return sqrt($r * $r - $d * $d);
 
147
    } else {                                    # On hyperbola
 
148
        my $t = $r / 1.41421356237309504880;
 
149
        return $t * $t / $d;
 
150
    }
 
151
}
 
152
 
 
153
sub cross {
 
154
    my ($v1, $v2) = @_;
 
155
  
 
156
    return (@$v1[1] * @$v2[2] - @$v1[2] * @$v2[1],
 
157
            @$v1[2] * @$v2[0] - @$v1[0] * @$v2[2],
 
158
            @$v1[0] * @$v2[1] - @$v1[1] * @$v2[0]);
 
159
}
 
160
 
 
161
# Simulate a track-ball. Project the points onto the virtual trackball, 
 
162
# then figure out the axis of rotation, which is the cross product of 
 
163
# P1 P2 and O P1 (O is the center of the ball, 0,0,0) Note: This is a 
 
164
# deformed trackball-- is a trackball in the center, but is deformed 
 
165
# into a hyperbolic sheet of rotation away from the center. 
 
166
# It is assumed that the arguments to this routine are in the range 
 
167
# (-1.0 ... 1.0).
 
168
sub trackball {
 
169
    my ($p1x, $p1y, $p2x, $p2y) = @_;
 
170
    
 
171
    if ($p1x == $p2x && $p1y == $p2y) {
 
172
        # zero rotation
 
173
        return (0.0, 0.0, 0.0, 1.0);
 
174
    }
 
175
    
 
176
    # First, figure out z-coordinates for projection of P1 and P2 to
 
177
    # deformed sphere
 
178
    my @p1 = ($p1x, $p1y, project_to_sphere(TRACKBALLSIZE, $p1x, $p1y));
 
179
    my @p2 = ($p2x, $p2y, project_to_sphere(TRACKBALLSIZE, $p2x, $p2y));
 
180
    
 
181
    # axis of rotation (cross product of P1 and P2)
 
182
    my @a = cross(\@p2, \@p1);
 
183
 
 
184
    # Figure out how much to rotate around that axis.
 
185
    my @d = map { $_ * $_ } (map { $p1[$_] - $p2[$_] } 0 .. $#p1);
 
186
    my $t = sqrt(reduce { $a + $b } @d) / (2.0 * TRACKBALLSIZE);
 
187
    
 
188
    # Avoid problems with out-of-control values...
 
189
    $t = 1.0 if ($t > 1.0);
 
190
    $t = -1.0 if ($t < -1.0);
 
191
    my $phi = 2.0 * asin($t);
 
192
 
 
193
    return axis_to_quat(\@a, $phi);
 
194
}
 
195
 
 
196
# Build a rotation matrix, given a quaternion rotation.
 
197
sub quat_to_rotmatrix {
 
198
    my ($q) = @_;
 
199
  
 
200
    my @m = ();
 
201
  
 
202
    $m[0] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[2] * @$q[2]);
 
203
    $m[1] = 2.0 * (@$q[0] * @$q[1] - @$q[2] * @$q[3]);
 
204
    $m[2] = 2.0 * (@$q[2] * @$q[0] + @$q[1] * @$q[3]);
 
205
    $m[3] = 0.0;
 
206
 
 
207
    $m[4] = 2.0 * (@$q[0] * @$q[1] + @$q[2] * @$q[3]);
 
208
    $m[5] = 1.0 - 2.0 * (@$q[2] * @$q[2] + @$q[0] * @$q[0]);
 
209
    $m[6] = 2.0 * (@$q[1] * @$q[2] - @$q[0] * @$q[3]);
 
210
    $m[7] = 0.0;
 
211
 
 
212
    $m[8] = 2.0 * (@$q[2] * @$q[0] - @$q[1] * @$q[3]);
 
213
    $m[9] = 2.0 * (@$q[1] * @$q[2] + @$q[0] * @$q[3]);
 
214
    $m[10] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[0] * @$q[0]);
 
215
    $m[11] = 0.0;
 
216
 
 
217
    $m[12] = 0.0;
 
218
    $m[13] = 0.0;
 
219
    $m[14] = 0.0;
 
220
    $m[15] = 1.0;
 
221
  
 
222
    return @m;
 
223
}
 
224
 
 
225
sub mulquats {
 
226
    my ($q1, $rq) = @_;
 
227
  
 
228
    return (@$q1[3] * @$rq[0] + @$q1[0] * @$rq[3] + @$q1[1] * @$rq[2] - @$q1[2] * @$rq[1],
 
229
            @$q1[3] * @$rq[1] + @$q1[1] * @$rq[3] + @$q1[2] * @$rq[0] - @$q1[0] * @$rq[2],
 
230
            @$q1[3] * @$rq[2] + @$q1[2] * @$rq[3] + @$q1[0] * @$rq[1] - @$q1[1] * @$rq[0],
 
231
            @$q1[3] * @$rq[3] - @$q1[0] * @$rq[0] - @$q1[1] * @$rq[1] - @$q1[2] * @$rq[2])
 
232
}
 
233
 
 
234
sub handle_rotation {
 
235
    my ($self, $e) = @_;
 
236
 
 
237
    if (not defined $self->initpos) {
 
238
        $self->initpos($e->GetPosition());
 
239
    } else {
 
240
        my $orig = $self->initpos;
 
241
        my $new = $e->GetPosition();
 
242
        my $size = $self->GetClientSize();
 
243
        if (TURNTABLE_MODE) {
 
244
            $self->sphi($self->sphi + ($new->x - $orig->x)*TRACKBALLSIZE);
 
245
            $self->stheta($self->stheta + ($new->y - $orig->y)*TRACKBALLSIZE);        #-
 
246
        } else {
 
247
            my @quat = trackball($orig->x / ($size->width / 2) - 1,
 
248
                            1 - $orig->y / ($size->height / 2),       #/
 
249
                            $new->x / ($size->width / 2) - 1,
 
250
                            1 - $new->y / ($size->height / 2),        #/
 
251
                            );
 
252
            $self->quat(mulquats($self->quat, \@quat));
 
253
        }
 
254
        $self->initpos($new);
 
255
        $self->Refresh;
 
256
    }
 
257
}
 
258
 
 
259
sub handle_translation {
 
260
    my ($self, $e) = @_;
 
261
 
 
262
    if (not defined $self->initpos) {
 
263
        $self->initpos($e->GetPosition());
 
264
    } else {
 
265
        my $new = $e->GetPosition();
 
266
        my $orig = $self->initpos;
 
267
        my @orig3d = $self->mouse_to_3d($orig->x, $orig->y);             #)()
 
268
        my @new3d = $self->mouse_to_3d($new->x, $new->y);                #)()
 
269
        glTranslatef($new3d[0] - $orig3d[0], $new3d[1] - $orig3d[1], 0);
 
270
        $self->initpos($new);
 
271
        $self->Refresh;
 
272
    }
 
273
}
 
274
 
 
275
sub mouse_to_3d {
 
276
    my ($self, $x, $y) = @_;
 
277
 
 
278
    my @viewport    = glGetIntegerv_p(GL_VIEWPORT);             # 4 items
 
279
    my @mview       = glGetDoublev_p(GL_MODELVIEW_MATRIX);      # 16 items
 
280
    my @proj        = glGetDoublev_p(GL_PROJECTION_MATRIX);     # 16 items
 
281
 
 
282
    my @projected = gluUnProject_p($x, $viewport[3] - $y, 1.0, @mview, @proj, @viewport);
 
283
    return @projected;
 
284
}
 
285
 
 
286
sub ZoomTo {
 
287
    my ($self, $factor, $tox, $toy) =  @_;
 
288
    
 
289
    glTranslatef($tox, $toy, 0);
 
290
    glMatrixMode(GL_MODELVIEW);
 
291
    $self->Zoom($factor);
 
292
    glTranslatef(-$tox, -$toy, 0);
 
293
}
 
294
 
 
295
sub Zoom {
 
296
    my ($self, $factor) =  @_;
 
297
    glScalef($factor, $factor, 1);
 
298
}
 
299
 
 
300
sub GetContext {
 
301
    my ($self) = @_;
 
302
    
 
303
    if (Wx::wxVERSION >= 2.009) {
 
304
        return $self->{context} ||= Wx::GLContext->new($self);
 
305
    } else {
 
306
        return $self->SUPER::GetContext;
 
307
    }
 
308
}
 
309
 
 
310
sub SetCurrent {
 
311
    my ($self, $context) = @_;
 
312
    
 
313
    if (Wx::wxVERSION >= 2.009) {
 
314
        return $self->SUPER::SetCurrent($context);
 
315
    } else {
 
316
        return $self->SUPER::SetCurrent;
 
317
    }
 
318
}
 
319
 
 
320
sub ResetModelView {
 
321
    my ($self, $factor) = @_;
 
322
    
 
323
    glMatrixMode(GL_MODELVIEW);
 
324
    glLoadIdentity();
 
325
    my $win_size = $self->GetClientSize();
 
326
    my $ratio = $factor * min($win_size->width, $win_size->height) / max(@{ $self->object_bounding_box->size });
 
327
    glScalef($ratio, $ratio, 1);
 
328
}
 
329
 
 
330
sub Resize {
 
331
    my ($self, $x, $y) = @_;
 
332
 
 
333
    return unless $self->GetContext;
 
334
    $self->dirty(0);
 
335
 
 
336
    $self->SetCurrent($self->GetContext);
 
337
    glViewport(0, 0, $x, $y);
 
338
 
 
339
    glMatrixMode(GL_PROJECTION);
 
340
    glLoadIdentity();
 
341
    glOrtho(-$x/2, $x/2, -$y/2, $y/2, 0.5, 2 * max(@{ $self->object_bounding_box->size }));
 
342
 
 
343
    glMatrixMode(GL_MODELVIEW);
 
344
    unless ($self->mview_init) {
 
345
        $self->mview_init(1);
 
346
        $self->ResetModelView(0.9);
 
347
    }
 
348
}
 
349
 
 
350
sub InitGL {
 
351
    my $self = shift;
 
352
 
 
353
    return if $self->init;
 
354
    return unless $self->GetContext;
 
355
    $self->init(1);
 
356
    
 
357
    glEnable(GL_NORMALIZE);
 
358
    glEnable(GL_LIGHTING);
 
359
    glDepthFunc(GL_LESS);
 
360
    glEnable(GL_DEPTH_TEST);
 
361
    
 
362
    # Settings for our light.
 
363
    my @LightPos        = (0, 0, 2, 1.0);
 
364
    my @LightAmbient    = (0.1, 0.1, 0.1, 1.0);
 
365
    my @LightDiffuse    = (0.7, 0.5, 0.5, 1.0);
 
366
    my @LightSpecular   = (0.1, 0.1, 0.1, 0.1);
 
367
    
 
368
    # Enables Smooth Color Shading; try GL_FLAT for (lack of) fun.
 
369
    glShadeModel(GL_SMOOTH);
 
370
    
 
371
    # Set up a light, turn it on.
 
372
    glLightfv_p(GL_LIGHT1, GL_POSITION, @LightPos);
 
373
    glLightfv_p(GL_LIGHT1, GL_AMBIENT,  @LightAmbient);
 
374
    glLightfv_p(GL_LIGHT1, GL_DIFFUSE,  @LightDiffuse);
 
375
    glLightfv_p(GL_LIGHT1, GL_SPECULAR, @LightSpecular);
 
376
    glEnable(GL_LIGHT1);
 
377
      
 
378
    # A handy trick -- have surface material mirror the color.
 
379
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
 
380
    glEnable(GL_COLOR_MATERIAL);
 
381
}
 
382
 
 
383
sub Render {
 
384
    my ($self, $dc) = @_;
 
385
 
 
386
    return unless $self->GetContext;
 
387
    $self->SetCurrent($self->GetContext);
 
388
    $self->InitGL;
 
389
 
 
390
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
391
 
 
392
    glPushMatrix();
 
393
 
 
394
    my $object_size = $self->object_bounding_box->size;
 
395
    glTranslatef(0, 0, -max(@$object_size[0..1]));
 
396
    my @rotmat = quat_to_rotmatrix($self->quat);
 
397
    glMultMatrixd_p(@rotmat[0..15]);
 
398
    glRotatef($self->stheta, 1, 0, 0);
 
399
    glRotatef($self->sphi, 0, 0, 1);
 
400
    
 
401
    my $center = $self->object_bounding_box->center;
 
402
    glTranslatef(-$center->x, -$center->y, -$center->z);  #,,
 
403
 
 
404
    $self->draw_mesh;
 
405
    
 
406
    my $z0 = 0;
 
407
    # draw axes
 
408
    {
 
409
        my $axis_len = 2 * max(@{ $object_size });
 
410
        glLineWidth(2);
 
411
        glBegin(GL_LINES);
 
412
        # draw line for x axis
 
413
        glColor3f(1, 0, 0);
 
414
        glVertex3f(0, 0, $z0);
 
415
        glVertex3f($axis_len, 0, $z0);
 
416
        # draw line for y axis
 
417
        glColor3f(0, 1, 0);
 
418
        glVertex3f(0, 0, $z0);
 
419
        glVertex3f(0, $axis_len, $z0);
 
420
        # draw line for Z axis
 
421
        glColor3f(0, 0, 1);
 
422
        glVertex3f(0, 0, $z0);
 
423
        glVertex3f(0, 0, $z0+$axis_len);
 
424
        glEnd();
 
425
        
 
426
        # draw ground
 
427
        my $ground_z = $z0-0.02;
 
428
        glDisable(GL_CULL_FACE);
 
429
        glEnable(GL_BLEND);
 
430
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
431
        glBegin(GL_QUADS);
 
432
        glColor4f(1, 1, 1, 0.5);
 
433
        glVertex3f(-$axis_len, -$axis_len, $ground_z);
 
434
        glVertex3f($axis_len, -$axis_len, $ground_z);
 
435
        glVertex3f($axis_len, $axis_len, $ground_z);
 
436
        glVertex3f(-$axis_len, $axis_len, $ground_z);
 
437
        glEnd();
 
438
        glEnable(GL_CULL_FACE);
 
439
        glDisable(GL_BLEND);
 
440
        
 
441
        # draw grid
 
442
        glBegin(GL_LINES);
 
443
        glColor3f(1, 1, 1);
 
444
        for (my $x = -$axis_len; $x <= $axis_len; $x += 10) {
 
445
            glVertex3f($x, -$axis_len, $ground_z);
 
446
            glVertex3f($x, $axis_len, $ground_z);
 
447
        }
 
448
        for (my $y = -$axis_len; $y <= $axis_len; $y += 10) {
 
449
            glVertex3f(-$axis_len, $y, $ground_z);
 
450
            glVertex3f($axis_len, $y, $ground_z);
 
451
        }
 
452
        glEnd();
 
453
        
 
454
        # draw cutting plane
 
455
        if (defined $self->cutting_plane_z) {
 
456
            my $plane_z = $z0 + $self->cutting_plane_z;
 
457
            glDisable(GL_CULL_FACE);
 
458
            glEnable(GL_BLEND);
 
459
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
460
            glBegin(GL_QUADS);
 
461
            glColor4f(1, 0.8, 0.8, 0.5);
 
462
            glVertex3f(-$axis_len, -$axis_len, $plane_z);
 
463
            glVertex3f($axis_len, -$axis_len, $plane_z);
 
464
            glVertex3f($axis_len, $axis_len, $plane_z);
 
465
            glVertex3f(-$axis_len, $axis_len, $plane_z);
 
466
            glEnd();
 
467
            glEnable(GL_CULL_FACE);
 
468
            glDisable(GL_BLEND);
 
469
        }
 
470
    }
 
471
 
 
472
    glPopMatrix();
 
473
    glFlush();
 
474
 
 
475
    $self->SwapBuffers();
 
476
}
 
477
 
 
478
sub draw_mesh {
 
479
    my $self = shift;
 
480
    
 
481
    glEnable(GL_BLEND);
 
482
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 
483
    glEnable(GL_CULL_FACE);
 
484
    glEnableClientState(GL_VERTEX_ARRAY);
 
485
    glEnableClientState(GL_NORMAL_ARRAY);
 
486
    
 
487
    foreach my $volume (@{$self->volumes}) {
 
488
        glVertexPointer_p(3, $volume->{verts});
 
489
        
 
490
        glCullFace(GL_BACK);
 
491
        glNormalPointer_p($volume->{norms});
 
492
        if ($volume->{selected}) {
 
493
            glColor4f(@{ &SELECTED_COLOR });
 
494
        } else {
 
495
            glColor4f(@{ $volume->{color} });
 
496
        }
 
497
        glDrawArrays(GL_TRIANGLES, 0, $volume->{verts}->elements / 3);
 
498
    }
 
499
    
 
500
    glDisableClientState(GL_NORMAL_ARRAY);
 
501
    glDisableClientState(GL_VERTEX_ARRAY);
 
502
}
 
503
 
 
504
1;