3DScene.pm 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. # Implements pure perl packages
  2. #
  3. # Slic3r::GUI::3DScene::Base;
  4. # Slic3r::GUI::3DScene;
  5. #
  6. # Slic3r::GUI::Plater::3D derives from Slic3r::GUI::3DScene,
  7. # Slic3r::GUI::Plater::3DPreview, Slic3r::GUI::Plater::3DToolpaths,
  8. # Slic3r::GUI::Plater::ObjectCutDialog and Slic3r::GUI::Plater::ObjectPartsPanel
  9. # own $self->{canvas} of the Slic3r::GUI::3DScene type.
  10. #
  11. # Therefore the 3DScene supports renderng of STLs, extrusions and cutting planes,
  12. # and camera manipulation.
  13. package Slic3r::GUI::3DScene::Base;
  14. use strict;
  15. use warnings;
  16. use Wx qw(wxTheApp :timer :bitmap :icon :dialog);
  17. use Wx::Event qw(EVT_PAINT EVT_SIZE EVT_ERASE_BACKGROUND EVT_IDLE EVT_MOUSEWHEEL EVT_MOUSE_EVENTS EVT_CHAR EVT_TIMER);
  18. # must load OpenGL *before* Wx::GLCanvas
  19. use OpenGL qw(:glconstants :glfunctions :glufunctions :gluconstants);
  20. use base qw(Wx::GLCanvas Class::Accessor);
  21. use Math::Trig qw(asin tan);
  22. use List::Util qw(reduce min max first);
  23. use Slic3r::Geometry qw(X Y normalize scale unscale scaled_epsilon);
  24. use Slic3r::Geometry::Clipper qw(offset_ex intersection_pl JT_ROUND);
  25. use Wx::GLCanvas qw(:all);
  26. use Slic3r::Geometry qw(PI);
  27. # _dirty: boolean flag indicating, that the screen has to be redrawn on EVT_IDLE.
  28. # volumes: reference to vector of Slic3r::GUI::3DScene::Volume.
  29. # _camera_type: 'perspective' or 'ortho'
  30. __PACKAGE__->mk_accessors( qw(_quat _dirty init
  31. enable_picking
  32. enable_moving
  33. use_plain_shader
  34. on_viewport_changed
  35. on_hover
  36. on_select
  37. on_double_click
  38. on_right_click
  39. on_move
  40. on_model_update
  41. volumes
  42. _sphi _stheta
  43. cutting_plane_z
  44. cut_lines_vertices
  45. bed_shape
  46. bed_triangles
  47. bed_grid_lines
  48. bed_polygon
  49. background
  50. origin
  51. _mouse_pos
  52. _hover_volume_idx
  53. _drag_volume_idx
  54. _drag_start_pos
  55. _drag_volume_center_offset
  56. _drag_start_xy
  57. _dragged
  58. _layer_height_edited
  59. _camera_type
  60. _camera_target
  61. _camera_distance
  62. _zoom
  63. ) );
  64. use constant TRACKBALLSIZE => 0.8;
  65. use constant TURNTABLE_MODE => 1;
  66. use constant GROUND_Z => -0.02;
  67. # For mesh selection: Not selected - bright yellow.
  68. use constant DEFAULT_COLOR => [1,1,0];
  69. # For mesh selection: Selected - bright green.
  70. use constant SELECTED_COLOR => [0,1,0,1];
  71. # For mesh selection: Mouse hovers over the object, but object not selected yet - dark green.
  72. use constant HOVER_COLOR => [0.4,0.9,0,1];
  73. # phi / theta angles to orient the camera.
  74. use constant VIEW_DEFAULT => [45.0,45.0];
  75. use constant VIEW_LEFT => [90.0,90.0];
  76. use constant VIEW_RIGHT => [-90.0,90.0];
  77. use constant VIEW_TOP => [0.0,0.0];
  78. use constant VIEW_BOTTOM => [0.0,180.0];
  79. use constant VIEW_FRONT => [0.0,90.0];
  80. use constant VIEW_REAR => [180.0,90.0];
  81. use constant MANIPULATION_IDLE => 0;
  82. use constant MANIPULATION_DRAGGING => 1;
  83. use constant MANIPULATION_LAYER_HEIGHT => 2;
  84. use constant GIMBALL_LOCK_THETA_MAX => 170;
  85. use constant VARIABLE_LAYER_THICKNESS_BAR_WIDTH => 70;
  86. use constant VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT => 22;
  87. # make OpenGL::Array thread-safe
  88. {
  89. no warnings 'redefine';
  90. *OpenGL::Array::CLONE_SKIP = sub { 1 };
  91. }
  92. sub new {
  93. my ($class, $parent) = @_;
  94. # We can only enable multi sample anti aliasing wih wxWidgets 3.0.3 and with a hacked Wx::GLCanvas,
  95. # which exports some new WX_GL_XXX constants, namely WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES.
  96. my $can_multisample =
  97. ! wxTheApp->{app_config}->get('use_legacy_opengl') &&
  98. Wx::wxVERSION >= 3.000003 &&
  99. defined Wx::GLCanvas->can('WX_GL_SAMPLE_BUFFERS') &&
  100. defined Wx::GLCanvas->can('WX_GL_SAMPLES');
  101. my $attrib = [WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 24];
  102. if ($can_multisample) {
  103. # Request a window with multi sampled anti aliasing. This is a new feature in Wx 3.0.3 (backported from 3.1.0).
  104. # Use eval to avoid compilation, if the subs WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES are missing.
  105. eval 'push(@$attrib, (WX_GL_SAMPLE_BUFFERS, 1, WX_GL_SAMPLES, 4));';
  106. }
  107. # wxWidgets expect the attrib list to be ended by zero.
  108. push(@$attrib, 0);
  109. # we request a depth buffer explicitely because it looks like it's not created by
  110. # default on Linux, causing transparency issues
  111. my $self = $class->SUPER::new($parent, -1, Wx::wxDefaultPosition, Wx::wxDefaultSize, 0, "", $attrib);
  112. if (Wx::wxVERSION >= 3.000003) {
  113. # Wx 3.0.3 contains an ugly hack to support some advanced OpenGL attributes through the attribute list.
  114. # The attribute list is transferred between the wxGLCanvas and wxGLContext constructors using a single static array s_wglContextAttribs.
  115. # Immediatelly force creation of the OpenGL context to consume the static variable s_wglContextAttribs.
  116. $self->GetContext();
  117. }
  118. $self->{can_multisample} = $can_multisample;
  119. $self->background(1);
  120. $self->_quat((0, 0, 0, 1));
  121. $self->_stheta(45);
  122. $self->_sphi(45);
  123. $self->_zoom(1);
  124. $self->use_plain_shader(0);
  125. # Collection of GLVolume objects
  126. $self->volumes(Slic3r::GUI::_3DScene::GLVolume::Collection->new);
  127. # 3D point in model space
  128. $self->_camera_type('ortho');
  129. # $self->_camera_type('perspective');
  130. $self->_camera_target(Slic3r::Pointf3->new(0,0,0));
  131. $self->_camera_distance(0.);
  132. $self->layer_editing_enabled(0);
  133. $self->{layer_height_edit_band_width} = 2.;
  134. $self->{layer_height_edit_strength} = 0.005;
  135. $self->{layer_height_edit_last_object_id} = -1;
  136. $self->{layer_height_edit_last_z} = 0.;
  137. $self->{layer_height_edit_last_action} = 0;
  138. $self->reset_objects;
  139. EVT_PAINT($self, sub {
  140. my $dc = Wx::PaintDC->new($self);
  141. $self->Render($dc);
  142. });
  143. EVT_SIZE($self, sub { $self->_dirty(1) });
  144. EVT_IDLE($self, sub {
  145. return unless $self->_dirty;
  146. return if !$self->IsShownOnScreen;
  147. $self->Resize( $self->GetSizeWH );
  148. $self->Refresh;
  149. });
  150. EVT_MOUSEWHEEL($self, \&mouse_wheel_event);
  151. EVT_MOUSE_EVENTS($self, \&mouse_event);
  152. # EVT_KEY_DOWN($self, sub {
  153. EVT_CHAR($self, sub {
  154. my ($s, $event) = @_;
  155. if ($event->HasModifiers) {
  156. $event->Skip;
  157. } else {
  158. my $key = $event->GetKeyCode;
  159. if ($key == ord('0')) {
  160. $self->select_view('iso');
  161. } elsif ($key == ord('1')) {
  162. $self->select_view('top');
  163. } elsif ($key == ord('2')) {
  164. $self->select_view('bottom');
  165. } elsif ($key == ord('3')) {
  166. $self->select_view('front');
  167. } elsif ($key == ord('4')) {
  168. $self->select_view('rear');
  169. } elsif ($key == ord('5')) {
  170. $self->select_view('left');
  171. } elsif ($key == ord('6')) {
  172. $self->select_view('right');
  173. } else {
  174. $event->Skip;
  175. }
  176. }
  177. });
  178. $self->{layer_height_edit_timer_id} = &Wx::NewId();
  179. $self->{layer_height_edit_timer} = Wx::Timer->new($self, $self->{layer_height_edit_timer_id});
  180. EVT_TIMER($self, $self->{layer_height_edit_timer_id}, sub {
  181. my ($self, $event) = @_;
  182. return if $self->_layer_height_edited != 1;
  183. return if $self->{layer_height_edit_last_object_id} == -1;
  184. $self->_variable_layer_thickness_action(undef);
  185. });
  186. return $self;
  187. }
  188. sub Destroy {
  189. my ($self) = @_;
  190. $self->{layer_height_edit_timer}->Stop;
  191. $self->DestroyGL;
  192. return $self->SUPER::Destroy;
  193. }
  194. sub layer_editing_enabled {
  195. my ($self, $value) = @_;
  196. if (@_ == 2) {
  197. $self->{layer_editing_enabled} = $value;
  198. if ($value) {
  199. if (! $self->{layer_editing_initialized}) {
  200. # Enabling the layer editing for the first time. This triggers compilation of the necessary OpenGL shaders.
  201. # If compilation fails, a message box is shown with the error codes.
  202. $self->SetCurrent($self->GetContext);
  203. my $shader = new Slic3r::GUI::_3DScene::GLShader;
  204. my $error_message;
  205. if (! $shader->load($self->_fragment_shader_variable_layer_height, $self->_vertex_shader_variable_layer_height)) {
  206. # Compilation or linking of the shaders failed.
  207. $error_message = "Cannot compile an OpenGL Shader, therefore the Variable Layer Editing will be disabled.\n\n"
  208. . $shader->last_error;
  209. $shader = undef;
  210. } else {
  211. $self->{layer_height_edit_shader} = $shader;
  212. ($self->{layer_preview_z_texture_id}) = glGenTextures_p(1);
  213. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  214. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  215. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  216. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  217. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
  218. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  219. glBindTexture(GL_TEXTURE_2D, 0);
  220. }
  221. if (defined($error_message)) {
  222. # Don't enable the layer editing tool.
  223. $self->{layer_editing_enabled} = 0;
  224. # 2 means failed
  225. $self->{layer_editing_initialized} = 2;
  226. # Show the error message.
  227. Wx::MessageBox($error_message, "Slic3r Error", wxOK | wxICON_EXCLAMATION, $self);
  228. } else {
  229. $self->{layer_editing_initialized} = 1;
  230. }
  231. } elsif ($self->{layer_editing_initialized} == 2) {
  232. # Initilization failed before. Don't try to initialize and disable layer editing.
  233. $self->{layer_editing_enabled} = 0;
  234. }
  235. }
  236. }
  237. return $self->{layer_editing_enabled};
  238. }
  239. sub layer_editing_allowed {
  240. my ($self) = @_;
  241. # Allow layer editing if either the shaders were not initialized yet and we don't know
  242. # whether it will be possible to initialize them,
  243. # or if the initialization was done already and it failed.
  244. return ! (defined($self->{layer_editing_initialized}) && $self->{layer_editing_initialized} == 2);
  245. }
  246. sub _first_selected_object_id_for_variable_layer_height_editing {
  247. my ($self) = @_;
  248. for my $i (0..$#{$self->volumes}) {
  249. if ($self->volumes->[$i]->selected) {
  250. my $object_id = int($self->volumes->[$i]->select_group_id / 1000000);
  251. # Objects with object_id >= 1000 have a specific meaning, for example the wipe tower proxy.
  252. return ($object_id >= $self->{print}->object_count) ? -1 : $object_id
  253. if $object_id < 10000;
  254. }
  255. }
  256. return -1;
  257. }
  258. # Returns an array with (left, top, right, bottom) of the variable layer thickness bar on the screen.
  259. sub _variable_layer_thickness_bar_rect_screen {
  260. my ($self) = @_;
  261. my ($cw, $ch) = $self->GetSizeWH;
  262. return ($cw - VARIABLE_LAYER_THICKNESS_BAR_WIDTH, 0, $cw, $ch - VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT);
  263. }
  264. sub _variable_layer_thickness_bar_rect_viewport {
  265. my ($self) = @_;
  266. my ($cw, $ch) = $self->GetSizeWH;
  267. return ((0.5*$cw-VARIABLE_LAYER_THICKNESS_BAR_WIDTH)/$self->_zoom, (-0.5*$ch+VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT)/$self->_zoom, $cw/(2*$self->_zoom), $ch/(2*$self->_zoom));
  268. }
  269. # Returns an array with (left, top, right, bottom) of the variable layer thickness bar on the screen.
  270. sub _variable_layer_thickness_reset_rect_screen {
  271. my ($self) = @_;
  272. my ($cw, $ch) = $self->GetSizeWH;
  273. return ($cw - VARIABLE_LAYER_THICKNESS_BAR_WIDTH, $ch - VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT, $cw, $ch);
  274. }
  275. sub _variable_layer_thickness_reset_rect_viewport {
  276. my ($self) = @_;
  277. my ($cw, $ch) = $self->GetSizeWH;
  278. return ((0.5*$cw-VARIABLE_LAYER_THICKNESS_BAR_WIDTH)/$self->_zoom, -$ch/(2*$self->_zoom), $cw/(2*$self->_zoom), (-0.5*$ch+VARIABLE_LAYER_THICKNESS_RESET_BUTTON_HEIGHT)/$self->_zoom);
  279. }
  280. sub _variable_layer_thickness_bar_rect_mouse_inside {
  281. my ($self, $mouse_evt) = @_;
  282. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  283. return $mouse_evt->GetX >= $bar_left && $mouse_evt->GetX <= $bar_right && $mouse_evt->GetY >= $bar_top && $mouse_evt->GetY <= $bar_bottom;
  284. }
  285. sub _variable_layer_thickness_reset_rect_mouse_inside {
  286. my ($self, $mouse_evt) = @_;
  287. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_reset_rect_screen;
  288. return $mouse_evt->GetX >= $bar_left && $mouse_evt->GetX <= $bar_right && $mouse_evt->GetY >= $bar_top && $mouse_evt->GetY <= $bar_bottom;
  289. }
  290. sub _variable_layer_thickness_bar_mouse_cursor_z_relative {
  291. my ($self) = @_;
  292. my $mouse_pos = $self->ScreenToClientPoint(Wx::GetMousePosition());
  293. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  294. return ($mouse_pos->x >= $bar_left && $mouse_pos->x <= $bar_right && $mouse_pos->y >= $bar_top && $mouse_pos->y <= $bar_bottom) ?
  295. # Inside the bar.
  296. ($bar_bottom - $mouse_pos->y - 1.) / ($bar_bottom - $bar_top - 1) :
  297. # Outside the bar.
  298. -1000.;
  299. }
  300. sub _variable_layer_thickness_action {
  301. my ($self, $mouse_event, $do_modification) = @_;
  302. # A volume is selected. Test, whether hovering over a layer thickness bar.
  303. return if $self->{layer_height_edit_last_object_id} == -1;
  304. if (defined($mouse_event)) {
  305. my ($bar_left, $bar_top, $bar_right, $bar_bottom) = $self->_variable_layer_thickness_bar_rect_screen;
  306. $self->{layer_height_edit_last_z} = unscale($self->{print}->get_object($self->{layer_height_edit_last_object_id})->size->z)
  307. * ($bar_bottom - $mouse_event->GetY - 1.) / ($bar_bottom - $bar_top);
  308. $self->{layer_height_edit_last_action} = $mouse_event->ShiftDown ? ($mouse_event->RightIsDown ? 3 : 2) : ($mouse_event->RightIsDown ? 0 : 1);
  309. }
  310. # Mark the volume as modified, so Print will pick its layer height profile? Where to mark it?
  311. # Start a timer to refresh the print? schedule_background_process() ?
  312. # The PrintObject::adjust_layer_height_profile() call adjusts the profile of its associated ModelObject, it does not modify the profile of the PrintObject itself.
  313. $self->{print}->get_object($self->{layer_height_edit_last_object_id})->adjust_layer_height_profile(
  314. $self->{layer_height_edit_last_z},
  315. $self->{layer_height_edit_strength},
  316. $self->{layer_height_edit_band_width},
  317. $self->{layer_height_edit_last_action});
  318. $self->volumes->[$self->{layer_height_edit_last_object_id}]->generate_layer_height_texture(
  319. $self->{print}->get_object($self->{layer_height_edit_last_object_id}), 1);
  320. $self->Refresh;
  321. # Automatic action on mouse down with the same coordinate.
  322. $self->{layer_height_edit_timer}->Start(100, wxTIMER_CONTINUOUS);
  323. }
  324. sub mouse_event {
  325. my ($self, $e) = @_;
  326. my $pos = Slic3r::Pointf->new($e->GetPositionXY);
  327. my $object_idx_selected = $self->{layer_height_edit_last_object_id} = ($self->layer_editing_enabled && $self->{print}) ? $self->_first_selected_object_id_for_variable_layer_height_editing : -1;
  328. if ($e->Entering && &Wx::wxMSW) {
  329. # wxMSW needs focus in order to catch mouse wheel events
  330. $self->SetFocus;
  331. $self->_drag_start_xy(undef);
  332. } elsif ($e->LeftDClick) {
  333. if ($object_idx_selected != -1 && $self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  334. } elsif ($self->on_double_click) {
  335. $self->on_double_click->();
  336. }
  337. } elsif ($e->LeftDown || $e->RightDown) {
  338. # If user pressed left or right button we first check whether this happened
  339. # on a volume or not.
  340. my $volume_idx = $self->_hover_volume_idx // -1;
  341. $self->_layer_height_edited(0);
  342. if ($object_idx_selected != -1 && $self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  343. # A volume is selected and the mouse is hovering over a layer thickness bar.
  344. # Start editing the layer height.
  345. $self->_layer_height_edited(1);
  346. $self->_variable_layer_thickness_action($e);
  347. } elsif ($object_idx_selected != -1 && $self->_variable_layer_thickness_reset_rect_mouse_inside($e)) {
  348. $self->{print}->get_object($object_idx_selected)->reset_layer_height_profile;
  349. # Index 2 means no editing, just wait for mouse up event.
  350. $self->_layer_height_edited(2);
  351. $self->Refresh;
  352. $self->Update;
  353. } else {
  354. # Select volume in this 3D canvas.
  355. # Don't deselect a volume if layer editing is enabled. We want the object to stay selected
  356. # during the scene manipulation.
  357. if ($self->enable_picking && ($volume_idx != -1 || ! $self->layer_editing_enabled)) {
  358. $self->deselect_volumes;
  359. $self->select_volume($volume_idx);
  360. if ($volume_idx != -1) {
  361. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  362. my @volumes;
  363. if ($group_id != -1) {
  364. $self->select_volume($_)
  365. for grep $self->volumes->[$_]->select_group_id == $group_id,
  366. 0..$#{$self->volumes};
  367. }
  368. }
  369. $self->Refresh;
  370. $self->Update;
  371. }
  372. # propagate event through callback
  373. $self->on_select->($volume_idx)
  374. if $self->on_select;
  375. if ($volume_idx != -1) {
  376. if ($e->LeftDown && $self->enable_moving) {
  377. # The mouse_to_3d gets the Z coordinate from the Z buffer at the screen coordinate $pos->x,y,
  378. # an converts the screen space coordinate to unscaled object space.
  379. my $pos3d = $self->mouse_to_3d(@$pos);
  380. # Only accept the initial position, if it is inside the volume bounding box.
  381. my $volume_bbox = $self->volumes->[$volume_idx]->transformed_bounding_box;
  382. $volume_bbox->offset(1.);
  383. if ($volume_bbox->contains_point($pos3d)) {
  384. # The dragging operation is initiated.
  385. $self->_drag_volume_idx($volume_idx);
  386. $self->_drag_start_pos($pos3d);
  387. # Remember the shift to to the object center. The object center will later be used
  388. # to limit the object placement close to the bed.
  389. $self->_drag_volume_center_offset($pos3d->vector_to($volume_bbox->center));
  390. }
  391. } elsif ($e->RightDown) {
  392. # if right clicking on volume, propagate event through callback
  393. $self->on_right_click->($e->GetPosition)
  394. if $self->on_right_click;
  395. }
  396. }
  397. }
  398. } elsif ($e->Dragging && $e->LeftIsDown && ! $self->_layer_height_edited && defined($self->_drag_volume_idx)) {
  399. # Get new position at the same Z of the initial click point.
  400. my $cur_pos = Slic3r::Linef3->new(
  401. $self->mouse_to_3d($e->GetX, $e->GetY, 0),
  402. $self->mouse_to_3d($e->GetX, $e->GetY, 1))
  403. ->intersect_plane($self->_drag_start_pos->z);
  404. # Clip the new position, so the object center remains close to the bed.
  405. {
  406. $cur_pos->translate(@{$self->_drag_volume_center_offset});
  407. my $cur_pos2 = Slic3r::Point->new(scale($cur_pos->x), scale($cur_pos->y));
  408. if (! $self->bed_polygon->contains_point($cur_pos2)) {
  409. my $ip = $self->bed_polygon->point_projection($cur_pos2);
  410. $cur_pos->set_x(unscale($ip->x));
  411. $cur_pos->set_y(unscale($ip->y));
  412. }
  413. $cur_pos->translate(@{$self->_drag_volume_center_offset->negative});
  414. }
  415. # Calculate the translation vector.
  416. my $vector = $self->_drag_start_pos->vector_to($cur_pos);
  417. # Get the volume being dragged.
  418. my $volume = $self->volumes->[$self->_drag_volume_idx];
  419. # Get all volumes belonging to the same group, if any.
  420. my @volumes = ($volume->drag_group_id == -1) ?
  421. ($volume) :
  422. grep $_->drag_group_id == $volume->drag_group_id, @{$self->volumes};
  423. # Apply new temporary volume origin and ignore Z.
  424. $_->translate($vector->x, $vector->y, 0) for @volumes;
  425. $self->_drag_start_pos($cur_pos);
  426. $self->_dragged(1);
  427. $self->Refresh;
  428. $self->Update;
  429. } elsif ($e->Dragging) {
  430. if ($self->_layer_height_edited && $object_idx_selected != -1) {
  431. $self->_variable_layer_thickness_action($e) if ($self->_layer_height_edited == 1);
  432. } elsif ($e->LeftIsDown) {
  433. # if dragging over blank area with left button, rotate
  434. if (defined $self->_drag_start_pos) {
  435. my $orig = $self->_drag_start_pos;
  436. if (TURNTABLE_MODE) {
  437. # Turntable mode is enabled by default.
  438. $self->_sphi($self->_sphi + ($pos->x - $orig->x) * TRACKBALLSIZE);
  439. $self->_stheta($self->_stheta - ($pos->y - $orig->y) * TRACKBALLSIZE); #-
  440. $self->_stheta(GIMBALL_LOCK_THETA_MAX) if $self->_stheta > GIMBALL_LOCK_THETA_MAX;
  441. $self->_stheta(0) if $self->_stheta < 0;
  442. } else {
  443. my $size = $self->GetClientSize;
  444. my @quat = trackball(
  445. $orig->x / ($size->width / 2) - 1,
  446. 1 - $orig->y / ($size->height / 2), #/
  447. $pos->x / ($size->width / 2) - 1,
  448. 1 - $pos->y / ($size->height / 2), #/
  449. );
  450. $self->_quat(mulquats($self->_quat, \@quat));
  451. }
  452. $self->on_viewport_changed->() if $self->on_viewport_changed;
  453. $self->Refresh;
  454. $self->Update;
  455. }
  456. $self->_drag_start_pos($pos);
  457. } elsif ($e->MiddleIsDown || $e->RightIsDown) {
  458. # If dragging over blank area with right button, pan.
  459. if (defined $self->_drag_start_xy) {
  460. # get point in model space at Z = 0
  461. my $cur_pos = $self->mouse_to_3d($e->GetX, $e->GetY, 0);
  462. my $orig = $self->mouse_to_3d($self->_drag_start_xy->x, $self->_drag_start_xy->y, 0);
  463. $self->_camera_target->translate(@{$orig->vector_to($cur_pos)->negative});
  464. $self->on_viewport_changed->() if $self->on_viewport_changed;
  465. $self->Refresh;
  466. $self->Update;
  467. }
  468. $self->_drag_start_xy($pos);
  469. }
  470. } elsif ($e->LeftUp || $e->MiddleUp || $e->RightUp) {
  471. if ($self->_layer_height_edited) {
  472. $self->_layer_height_edited(undef);
  473. $self->{layer_height_edit_timer}->Stop;
  474. $self->on_model_update->()
  475. if ($object_idx_selected != -1 && $self->on_model_update);
  476. } elsif ($self->on_move && defined($self->_drag_volume_idx) && $self->_dragged) {
  477. # get all volumes belonging to the same group, if any
  478. my @volume_idxs;
  479. my $group_id = $self->volumes->[$self->_drag_volume_idx]->drag_group_id;
  480. if ($group_id == -1) {
  481. @volume_idxs = ($self->_drag_volume_idx);
  482. } else {
  483. @volume_idxs = grep $self->volumes->[$_]->drag_group_id == $group_id,
  484. 0..$#{$self->volumes};
  485. }
  486. $self->on_move->(@volume_idxs);
  487. }
  488. $self->_drag_volume_idx(undef);
  489. $self->_drag_start_pos(undef);
  490. $self->_drag_start_xy(undef);
  491. $self->_dragged(undef);
  492. } elsif ($e->Moving) {
  493. $self->_mouse_pos($pos);
  494. # Only refresh if picking is enabled, in that case the objects may get highlighted if the mouse cursor
  495. # hovers over.
  496. if ($self->enable_picking) {
  497. $self->Update;
  498. $self->Refresh;
  499. }
  500. } else {
  501. $e->Skip();
  502. }
  503. }
  504. sub mouse_wheel_event {
  505. my ($self, $e) = @_;
  506. if ($e->MiddleIsDown) {
  507. # Ignore the wheel events if the middle button is pressed.
  508. return;
  509. }
  510. if ($self->layer_editing_enabled && $self->{print}) {
  511. my $object_idx_selected = $self->_first_selected_object_id_for_variable_layer_height_editing;
  512. if ($object_idx_selected != -1) {
  513. # A volume is selected. Test, whether hovering over a layer thickness bar.
  514. if ($self->_variable_layer_thickness_bar_rect_mouse_inside($e)) {
  515. # Adjust the width of the selection.
  516. $self->{layer_height_edit_band_width} = max(min($self->{layer_height_edit_band_width} * (1 + 0.1 * $e->GetWheelRotation() / $e->GetWheelDelta()), 10.), 1.5);
  517. $self->Refresh;
  518. return;
  519. }
  520. }
  521. }
  522. # Calculate the zoom delta and apply it to the current zoom factor
  523. my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
  524. $zoom = max(min($zoom, 4), -4);
  525. $zoom /= 10;
  526. $zoom = $self->_zoom / (1-$zoom);
  527. # Don't allow to zoom too far outside the scene.
  528. my $zoom_min = $self->get_zoom_to_bounding_box_factor($self->max_bounding_box);
  529. $zoom_min *= 0.4 if defined $zoom_min;
  530. $zoom = $zoom_min if defined $zoom_min && $zoom < $zoom_min;
  531. $self->_zoom($zoom);
  532. # In order to zoom around the mouse point we need to translate
  533. # the camera target
  534. my $size = Slic3r::Pointf->new($self->GetSizeWH);
  535. my $pos = Slic3r::Pointf->new($e->GetX, $size->y - $e->GetY); #-
  536. $self->_camera_target->translate(
  537. # ($pos - $size/2) represents the vector from the viewport center
  538. # to the mouse point. By multiplying it by $zoom we get the new,
  539. # transformed, length of such vector.
  540. # Since we want that point to stay fixed, we move our camera target
  541. # in the opposite direction by the delta of the length of such vector
  542. # ($zoom - 1). We then scale everything by 1/$self->_zoom since
  543. # $self->_camera_target is expressed in terms of model units.
  544. -($pos->x - $size->x/2) * ($zoom) / $self->_zoom,
  545. -($pos->y - $size->y/2) * ($zoom) / $self->_zoom,
  546. 0,
  547. ) if 0;
  548. $self->on_viewport_changed->() if $self->on_viewport_changed;
  549. $self->Resize($self->GetSizeWH) if $self->IsShownOnScreen;
  550. $self->Refresh;
  551. }
  552. # Reset selection.
  553. sub reset_objects {
  554. my ($self) = @_;
  555. if ($self->GetContext) {
  556. $self->SetCurrent($self->GetContext);
  557. $self->volumes->release_geometry;
  558. }
  559. $self->volumes->erase;
  560. $self->_dirty(1);
  561. }
  562. # Setup camera to view all objects.
  563. sub set_viewport_from_scene {
  564. my ($self, $scene) = @_;
  565. $self->_sphi($scene->_sphi);
  566. $self->_stheta($scene->_stheta);
  567. $self->_camera_target($scene->_camera_target);
  568. $self->_zoom($scene->_zoom);
  569. $self->_quat($scene->_quat);
  570. $self->_dirty(1);
  571. }
  572. # Set the camera to a default orientation,
  573. # zoom to volumes.
  574. sub select_view {
  575. my ($self, $direction) = @_;
  576. my $dirvec;
  577. if (ref($direction)) {
  578. $dirvec = $direction;
  579. } else {
  580. if ($direction eq 'iso') {
  581. $dirvec = VIEW_DEFAULT;
  582. } elsif ($direction eq 'left') {
  583. $dirvec = VIEW_LEFT;
  584. } elsif ($direction eq 'right') {
  585. $dirvec = VIEW_RIGHT;
  586. } elsif ($direction eq 'top') {
  587. $dirvec = VIEW_TOP;
  588. } elsif ($direction eq 'bottom') {
  589. $dirvec = VIEW_BOTTOM;
  590. } elsif ($direction eq 'front') {
  591. $dirvec = VIEW_FRONT;
  592. } elsif ($direction eq 'rear') {
  593. $dirvec = VIEW_REAR;
  594. }
  595. }
  596. my $bb = $self->volumes_bounding_box;
  597. if (! $bb->empty) {
  598. $self->_sphi($dirvec->[0]);
  599. $self->_stheta($dirvec->[1]);
  600. # Avoid gimball lock.
  601. $self->_stheta(GIMBALL_LOCK_THETA_MAX) if $self->_stheta > GIMBALL_LOCK_THETA_MAX;
  602. $self->_stheta(0) if $self->_stheta < 0;
  603. # View everything.
  604. $self->zoom_to_bounding_box($bb);
  605. $self->on_viewport_changed->() if $self->on_viewport_changed;
  606. $self->Refresh;
  607. }
  608. }
  609. sub get_zoom_to_bounding_box_factor {
  610. my ($self, $bb) = @_;
  611. return undef if ($bb->empty);
  612. my $max_size = max(@{$bb->size}) * 2;
  613. return ($max_size == 0) ? undef : min($self->GetSizeWH) / $max_size;
  614. }
  615. sub zoom_to_bounding_box {
  616. my ($self, $bb) = @_;
  617. # Calculate the zoom factor needed to adjust viewport to bounding box.
  618. my $zoom = $self->get_zoom_to_bounding_box_factor($bb);
  619. if (defined $zoom) {
  620. $self->_zoom($zoom);
  621. # center view around bounding box center
  622. $self->_camera_target($bb->center);
  623. $self->on_viewport_changed->() if $self->on_viewport_changed;
  624. }
  625. }
  626. sub zoom_to_bed {
  627. my ($self) = @_;
  628. if ($self->bed_shape) {
  629. $self->zoom_to_bounding_box($self->bed_bounding_box);
  630. }
  631. }
  632. sub zoom_to_volume {
  633. my ($self, $volume_idx) = @_;
  634. my $volume = $self->volumes->[$volume_idx];
  635. my $bb = $volume->transformed_bounding_box;
  636. $self->zoom_to_bounding_box($bb);
  637. }
  638. sub zoom_to_volumes {
  639. my ($self) = @_;
  640. $self->zoom_to_bounding_box($self->volumes_bounding_box);
  641. }
  642. sub volumes_bounding_box {
  643. my ($self) = @_;
  644. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  645. $bb->merge($_->transformed_bounding_box) for @{$self->volumes};
  646. return $bb;
  647. }
  648. sub bed_bounding_box {
  649. my ($self) = @_;
  650. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  651. if ($self->bed_shape) {
  652. $bb->merge_point(Slic3r::Pointf3->new(@$_, 0)) for @{$self->bed_shape};
  653. }
  654. return $bb;
  655. }
  656. sub max_bounding_box {
  657. my ($self) = @_;
  658. my $bb = $self->bed_bounding_box;
  659. $bb->merge($self->volumes_bounding_box);
  660. return $bb;
  661. }
  662. # Used by ObjectCutDialog and ObjectPartsPanel to generate a rectangular ground plane
  663. # to support the scene objects.
  664. sub set_auto_bed_shape {
  665. my ($self, $bed_shape) = @_;
  666. # draw a default square bed around object center
  667. my $max_size = max(@{ $self->volumes_bounding_box->size });
  668. my $center = $self->volumes_bounding_box->center;
  669. $self->set_bed_shape([
  670. [ $center->x - $max_size, $center->y - $max_size ], #--
  671. [ $center->x + $max_size, $center->y - $max_size ], #--
  672. [ $center->x + $max_size, $center->y + $max_size ], #++
  673. [ $center->x - $max_size, $center->y + $max_size ], #++
  674. ]);
  675. # Set the origin for painting of the coordinate system axes.
  676. $self->origin(Slic3r::Pointf->new(@$center[X,Y]));
  677. }
  678. # Set the bed shape to a single closed 2D polygon (array of two element arrays),
  679. # triangulate the bed and store the triangles into $self->bed_triangles,
  680. # fills the $self->bed_grid_lines and sets $self->origin.
  681. # Sets $self->bed_polygon to limit the object placement.
  682. sub set_bed_shape {
  683. my ($self, $bed_shape) = @_;
  684. $self->bed_shape($bed_shape);
  685. # triangulate bed
  686. my $expolygon = Slic3r::ExPolygon->new([ map [map scale($_), @$_], @$bed_shape ]);
  687. my $bed_bb = $expolygon->bounding_box;
  688. {
  689. my @points = ();
  690. foreach my $triangle (@{ $expolygon->triangulate }) {
  691. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$triangle;
  692. }
  693. $self->bed_triangles(OpenGL::Array->new_list(GL_FLOAT, @points));
  694. }
  695. {
  696. my @polylines = ();
  697. for (my $x = $bed_bb->x_min; $x <= $bed_bb->x_max; $x += scale 10) {
  698. push @polylines, Slic3r::Polyline->new([$x,$bed_bb->y_min], [$x,$bed_bb->y_max]);
  699. }
  700. for (my $y = $bed_bb->y_min; $y <= $bed_bb->y_max; $y += scale 10) {
  701. push @polylines, Slic3r::Polyline->new([$bed_bb->x_min,$y], [$bed_bb->x_max,$y]);
  702. }
  703. # clip with a slightly grown expolygon because our lines lay on the contours and
  704. # may get erroneously clipped
  705. my @lines = map Slic3r::Line->new(@$_[0,-1]),
  706. @{intersection_pl(\@polylines, [ @{$expolygon->offset(+scaled_epsilon)} ])};
  707. # append bed contours
  708. push @lines, map @{$_->lines}, @$expolygon;
  709. my @points = ();
  710. foreach my $line (@lines) {
  711. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$line; #))
  712. }
  713. $self->bed_grid_lines(OpenGL::Array->new_list(GL_FLOAT, @points));
  714. }
  715. # Set the origin for painting of the coordinate system axes.
  716. $self->origin(Slic3r::Pointf->new(0,0));
  717. $self->bed_polygon(offset_ex([$expolygon->contour], $bed_bb->radius * 1.7, JT_ROUND, scale(0.5))->[0]->contour->clone);
  718. }
  719. sub deselect_volumes {
  720. my ($self) = @_;
  721. $_->set_selected(0) for @{$self->volumes};
  722. }
  723. sub select_volume {
  724. my ($self, $volume_idx) = @_;
  725. $self->volumes->[$volume_idx]->set_selected(1)
  726. if $volume_idx != -1;
  727. }
  728. sub SetCuttingPlane {
  729. my ($self, $z, $expolygons) = @_;
  730. $self->cutting_plane_z($z);
  731. # grow slices in order to display them better
  732. $expolygons = offset_ex([ map @$_, @$expolygons ], scale 0.1);
  733. my @verts = ();
  734. foreach my $line (map @{$_->lines}, map @$_, @$expolygons) {
  735. push @verts, (
  736. unscale($line->a->x), unscale($line->a->y), $z, #))
  737. unscale($line->b->x), unscale($line->b->y), $z, #))
  738. );
  739. }
  740. $self->cut_lines_vertices(OpenGL::Array->new_list(GL_FLOAT, @verts));
  741. }
  742. # Given an axis and angle, compute quaternion.
  743. sub axis_to_quat {
  744. my ($ax, $phi) = @_;
  745. my $lena = sqrt(reduce { $a + $b } (map { $_ * $_ } @$ax));
  746. my @q = map { $_ * (1 / $lena) } @$ax;
  747. @q = map { $_ * sin($phi / 2.0) } @q;
  748. $q[$#q + 1] = cos($phi / 2.0);
  749. return @q;
  750. }
  751. # Project a point on the virtual trackball.
  752. # If it is inside the sphere, map it to the sphere, if it outside map it
  753. # to a hyperbola.
  754. sub project_to_sphere {
  755. my ($r, $x, $y) = @_;
  756. my $d = sqrt($x * $x + $y * $y);
  757. if ($d < $r * 0.70710678118654752440) { # Inside sphere
  758. return sqrt($r * $r - $d * $d);
  759. } else { # On hyperbola
  760. my $t = $r / 1.41421356237309504880;
  761. return $t * $t / $d;
  762. }
  763. }
  764. sub cross {
  765. my ($v1, $v2) = @_;
  766. return (@$v1[1] * @$v2[2] - @$v1[2] * @$v2[1],
  767. @$v1[2] * @$v2[0] - @$v1[0] * @$v2[2],
  768. @$v1[0] * @$v2[1] - @$v1[1] * @$v2[0]);
  769. }
  770. # Simulate a track-ball. Project the points onto the virtual trackball,
  771. # then figure out the axis of rotation, which is the cross product of
  772. # P1 P2 and O P1 (O is the center of the ball, 0,0,0) Note: This is a
  773. # deformed trackball-- is a trackball in the center, but is deformed
  774. # into a hyperbolic sheet of rotation away from the center.
  775. # It is assumed that the arguments to this routine are in the range
  776. # (-1.0 ... 1.0).
  777. sub trackball {
  778. my ($p1x, $p1y, $p2x, $p2y) = @_;
  779. if ($p1x == $p2x && $p1y == $p2y) {
  780. # zero rotation
  781. return (0.0, 0.0, 0.0, 1.0);
  782. }
  783. # First, figure out z-coordinates for projection of P1 and P2 to
  784. # deformed sphere
  785. my @p1 = ($p1x, $p1y, project_to_sphere(TRACKBALLSIZE, $p1x, $p1y));
  786. my @p2 = ($p2x, $p2y, project_to_sphere(TRACKBALLSIZE, $p2x, $p2y));
  787. # axis of rotation (cross product of P1 and P2)
  788. my @a = cross(\@p2, \@p1);
  789. # Figure out how much to rotate around that axis.
  790. my @d = map { $_ * $_ } (map { $p1[$_] - $p2[$_] } 0 .. $#p1);
  791. my $t = sqrt(reduce { $a + $b } @d) / (2.0 * TRACKBALLSIZE);
  792. # Avoid problems with out-of-control values...
  793. $t = 1.0 if ($t > 1.0);
  794. $t = -1.0 if ($t < -1.0);
  795. my $phi = 2.0 * asin($t);
  796. return axis_to_quat(\@a, $phi);
  797. }
  798. # Build a rotation matrix, given a quaternion rotation.
  799. sub quat_to_rotmatrix {
  800. my ($q) = @_;
  801. my @m = ();
  802. $m[0] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[2] * @$q[2]);
  803. $m[1] = 2.0 * (@$q[0] * @$q[1] - @$q[2] * @$q[3]);
  804. $m[2] = 2.0 * (@$q[2] * @$q[0] + @$q[1] * @$q[3]);
  805. $m[3] = 0.0;
  806. $m[4] = 2.0 * (@$q[0] * @$q[1] + @$q[2] * @$q[3]);
  807. $m[5] = 1.0 - 2.0 * (@$q[2] * @$q[2] + @$q[0] * @$q[0]);
  808. $m[6] = 2.0 * (@$q[1] * @$q[2] - @$q[0] * @$q[3]);
  809. $m[7] = 0.0;
  810. $m[8] = 2.0 * (@$q[2] * @$q[0] - @$q[1] * @$q[3]);
  811. $m[9] = 2.0 * (@$q[1] * @$q[2] + @$q[0] * @$q[3]);
  812. $m[10] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[0] * @$q[0]);
  813. $m[11] = 0.0;
  814. $m[12] = 0.0;
  815. $m[13] = 0.0;
  816. $m[14] = 0.0;
  817. $m[15] = 1.0;
  818. return @m;
  819. }
  820. sub mulquats {
  821. my ($q1, $rq) = @_;
  822. return (@$q1[3] * @$rq[0] + @$q1[0] * @$rq[3] + @$q1[1] * @$rq[2] - @$q1[2] * @$rq[1],
  823. @$q1[3] * @$rq[1] + @$q1[1] * @$rq[3] + @$q1[2] * @$rq[0] - @$q1[0] * @$rq[2],
  824. @$q1[3] * @$rq[2] + @$q1[2] * @$rq[3] + @$q1[0] * @$rq[1] - @$q1[1] * @$rq[0],
  825. @$q1[3] * @$rq[3] - @$q1[0] * @$rq[0] - @$q1[1] * @$rq[1] - @$q1[2] * @$rq[2])
  826. }
  827. # Convert the screen space coordinate to an object space coordinate.
  828. # If the Z screen space coordinate is not provided, a depth buffer value is substituted.
  829. sub mouse_to_3d {
  830. my ($self, $x, $y, $z) = @_;
  831. my @viewport = glGetIntegerv_p(GL_VIEWPORT); # 4 items
  832. my @mview = glGetDoublev_p(GL_MODELVIEW_MATRIX); # 16 items
  833. my @proj = glGetDoublev_p(GL_PROJECTION_MATRIX); # 16 items
  834. $y = $viewport[3] - $y;
  835. $z //= glReadPixels_p($x, $y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT);
  836. my @projected = gluUnProject_p($x, $y, $z, @mview, @proj, @viewport);
  837. return Slic3r::Pointf3->new(@projected);
  838. }
  839. sub GetContext {
  840. my ($self) = @_;
  841. return $self->{context} ||= Wx::GLContext->new($self);
  842. }
  843. sub SetCurrent {
  844. my ($self, $context) = @_;
  845. return $self->SUPER::SetCurrent($context);
  846. }
  847. sub UseVBOs {
  848. my ($self) = @_;
  849. if (! defined ($self->{use_VBOs})) {
  850. my $use_legacy = wxTheApp->{app_config}->get('use_legacy_opengl');
  851. if ($use_legacy eq '1') {
  852. # Disable OpenGL 2.0 rendering.
  853. $self->{use_VBOs} = 0;
  854. # Don't enable the layer editing tool.
  855. $self->{layer_editing_enabled} = 0;
  856. # 2 means failed
  857. $self->{layer_editing_initialized} = 2;
  858. return 0;
  859. }
  860. # This is a special path for wxWidgets on GTK, where an OpenGL context is initialized
  861. # first when an OpenGL widget is shown for the first time. How ugly.
  862. return 0 if (! $self->init && $^O eq 'linux');
  863. # Don't use VBOs if anything fails.
  864. $self->{use_VBOs} = 0;
  865. if ($self->GetContext) {
  866. $self->SetCurrent($self->GetContext);
  867. Slic3r::GUI::_3DScene::_glew_init;
  868. my @gl_version = split(/\./, glGetString(GL_VERSION));
  869. $self->{use_VBOs} = int($gl_version[0]) >= 2;
  870. # print "UseVBOs $self OpenGL major: $gl_version[0], minor: $gl_version[1]. Use VBOs: ", $self->{use_VBOs}, "\n";
  871. }
  872. }
  873. return $self->{use_VBOs};
  874. }
  875. sub Resize {
  876. my ($self, $x, $y) = @_;
  877. return unless $self->GetContext;
  878. $self->_dirty(0);
  879. $self->SetCurrent($self->GetContext);
  880. glViewport(0, 0, $x, $y);
  881. $x /= $self->_zoom;
  882. $y /= $self->_zoom;
  883. glMatrixMode(GL_PROJECTION);
  884. glLoadIdentity();
  885. if ($self->_camera_type eq 'ortho') {
  886. #FIXME setting the size of the box 10x larger than necessary
  887. # is only a workaround for an incorrectly set camera.
  888. # This workaround harms Z-buffer accuracy!
  889. # my $depth = 1.05 * $self->max_bounding_box->radius();
  890. my $depth = 10.0 * $self->max_bounding_box->radius();
  891. glOrtho(
  892. -$x/2, $x/2, -$y/2, $y/2,
  893. -$depth, $depth,
  894. );
  895. } else {
  896. die "Invalid camera type: ", $self->_camera_type, "\n" if ($self->_camera_type ne 'perspective');
  897. my $bbox_r = $self->max_bounding_box->radius();
  898. my $fov = PI * 45. / 180.;
  899. my $fov_tan = tan(0.5 * $fov);
  900. my $cam_distance = 0.5 * $bbox_r / $fov_tan;
  901. $self->_camera_distance($cam_distance);
  902. my $nr = $cam_distance - $bbox_r * 1.1;
  903. my $fr = $cam_distance + $bbox_r * 1.1;
  904. $nr = 1 if ($nr < 1);
  905. $fr = $nr + 1 if ($fr < $nr + 1);
  906. my $h2 = $fov_tan * $nr;
  907. my $w2 = $h2 * $x / $y;
  908. glFrustum(-$w2, $w2, -$h2, $h2, $nr, $fr);
  909. }
  910. glMatrixMode(GL_MODELVIEW);
  911. }
  912. sub InitGL {
  913. my $self = shift;
  914. return if $self->init;
  915. return unless $self->GetContext;
  916. $self->init(1);
  917. # This is a special path for wxWidgets on GTK, where an OpenGL context is initialized
  918. # first when an OpenGL widget is shown for the first time. How ugly.
  919. # In that case the volumes are wainting to be moved to Vertex Buffer Objects
  920. # after the OpenGL context is being initialized.
  921. $self->volumes->finalize_geometry(1)
  922. if ($^O eq 'linux' && $self->UseVBOs);
  923. glClearColor(0, 0, 0, 1);
  924. glColor3f(1, 0, 0);
  925. glEnable(GL_DEPTH_TEST);
  926. glClearDepth(1.0);
  927. glDepthFunc(GL_LEQUAL);
  928. glEnable(GL_CULL_FACE);
  929. glEnable(GL_BLEND);
  930. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  931. # Set antialiasing/multisampling
  932. glDisable(GL_LINE_SMOOTH);
  933. glDisable(GL_POLYGON_SMOOTH);
  934. # See "GL_MULTISAMPLE and GL_ARRAY_BUFFER_ARB messages on failed launch"
  935. # https://github.com/alexrj/Slic3r/issues/4085
  936. eval {
  937. # Disable the multi sampling by default, so the picking by color will work correctly.
  938. glDisable(GL_MULTISAMPLE);
  939. };
  940. # Disable multi sampling if the eval failed.
  941. $self->{can_multisample} = 0 if $@;
  942. # ambient lighting
  943. glLightModelfv_p(GL_LIGHT_MODEL_AMBIENT, 0.3, 0.3, 0.3, 1);
  944. glEnable(GL_LIGHTING);
  945. glEnable(GL_LIGHT0);
  946. glEnable(GL_LIGHT1);
  947. # light from camera
  948. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  949. glLightfv_p(GL_LIGHT1, GL_SPECULAR, 0.3, 0.3, 0.3, 1);
  950. glLightfv_p(GL_LIGHT1, GL_DIFFUSE, 0.2, 0.2, 0.2, 1);
  951. # Enables Smooth Color Shading; try GL_FLAT for (lack of) fun.
  952. glShadeModel(GL_SMOOTH);
  953. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.5, 0.3, 0.3, 1);
  954. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_SPECULAR, 1, 1, 1, 1);
  955. # glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
  956. # glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0, 0, 0.9);
  957. # A handy trick -- have surface material mirror the color.
  958. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  959. glEnable(GL_COLOR_MATERIAL);
  960. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  961. if ($self->UseVBOs) {
  962. my $shader = new Slic3r::GUI::_3DScene::GLShader;
  963. if (! $shader->load($self->_fragment_shader_Gouraud, $self->_vertex_shader_Gouraud)) {
  964. # if (! $shader->load($self->_fragment_shader_Phong, $self->_vertex_shader_Phong)) {
  965. print "Compilaton of path shader failed: \n" . $shader->last_error . "\n";
  966. $shader = undef;
  967. } else {
  968. $self->{plain_shader} = $shader;
  969. }
  970. }
  971. }
  972. sub DestroyGL {
  973. my $self = shift;
  974. if ($self->GetContext) {
  975. $self->SetCurrent($self->GetContext);
  976. if ($self->{plain_shader}) {
  977. $self->{plain_shader}->release;
  978. delete $self->{plain_shader};
  979. }
  980. if ($self->{layer_height_edit_shader}) {
  981. $self->{layer_height_edit_shader}->release;
  982. delete $self->{layer_height_edit_shader};
  983. }
  984. $self->volumes->release_geometry;
  985. }
  986. }
  987. sub Render {
  988. my ($self, $dc) = @_;
  989. # prevent calling SetCurrent() when window is not shown yet
  990. return unless $self->IsShownOnScreen;
  991. return unless my $context = $self->GetContext;
  992. $self->SetCurrent($context);
  993. $self->InitGL;
  994. glClearColor(1, 1, 1, 1);
  995. glClearDepth(1);
  996. glDepthFunc(GL_LESS);
  997. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  998. glMatrixMode(GL_MODELVIEW);
  999. glLoadIdentity();
  1000. {
  1001. # Shift the perspective camera.
  1002. my $camera_pos = Slic3r::Pointf3->new(0,0,-$self->_camera_distance);
  1003. glTranslatef(@$camera_pos);
  1004. }
  1005. if (TURNTABLE_MODE) {
  1006. # Turntable mode is enabled by default.
  1007. glRotatef(-$self->_stheta, 1, 0, 0); # pitch
  1008. glRotatef($self->_sphi, 0, 0, 1); # yaw
  1009. } else {
  1010. my @rotmat = quat_to_rotmatrix($self->quat);
  1011. glMultMatrixd_p(@rotmat[0..15]);
  1012. }
  1013. glTranslatef(@{ $self->_camera_target->negative });
  1014. # light from above
  1015. glLightfv_p(GL_LIGHT0, GL_POSITION, -0.5, -0.5, 1, 0);
  1016. glLightfv_p(GL_LIGHT0, GL_SPECULAR, 0.2, 0.2, 0.2, 1);
  1017. glLightfv_p(GL_LIGHT0, GL_DIFFUSE, 0.5, 0.5, 0.5, 1);
  1018. # Head light
  1019. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  1020. if ($self->enable_picking) {
  1021. # Render the object for picking.
  1022. # FIXME This cannot possibly work in a multi-sampled context as the color gets mangled by the anti-aliasing.
  1023. # Better to use software ray-casting on a bounding-box hierarchy.
  1024. glPushAttrib(GL_ENABLE_BIT);
  1025. glDisable(GL_MULTISAMPLE) if ($self->{can_multisample});
  1026. glDisable(GL_LIGHTING);
  1027. glDisable(GL_BLEND);
  1028. $self->draw_volumes(1);
  1029. glFlush();
  1030. glFinish();
  1031. if (my $pos = $self->_mouse_pos) {
  1032. my $col = [ glReadPixels_p($pos->x, $self->GetSize->GetHeight - $pos->y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) ];
  1033. my $volume_idx = $col->[0] + $col->[1]*256 + $col->[2]*256*256;
  1034. $self->_hover_volume_idx(undef);
  1035. $_->set_hover(0) for @{$self->volumes};
  1036. if ($volume_idx <= $#{$self->volumes}) {
  1037. $self->_hover_volume_idx($volume_idx);
  1038. $self->volumes->[$volume_idx]->set_hover(1);
  1039. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  1040. if ($group_id != -1) {
  1041. $_->set_hover(1) for grep { $_->select_group_id == $group_id } @{$self->volumes};
  1042. }
  1043. $self->on_hover->($volume_idx) if $self->on_hover;
  1044. }
  1045. }
  1046. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1047. glFlush();
  1048. glFinish();
  1049. glPopAttrib();
  1050. }
  1051. # draw fixed background
  1052. if ($self->background) {
  1053. glDisable(GL_LIGHTING);
  1054. glPushMatrix();
  1055. glLoadIdentity();
  1056. glMatrixMode(GL_PROJECTION);
  1057. glPushMatrix();
  1058. glLoadIdentity();
  1059. # Draws a bluish bottom to top gradient over the complete screen.
  1060. glDisable(GL_DEPTH_TEST);
  1061. glBegin(GL_QUADS);
  1062. glColor3f(0.0,0.0,0.0);
  1063. glVertex3f(-1.0,-1.0, 1.0);
  1064. glVertex3f( 1.0,-1.0, 1.0);
  1065. glColor3f(10/255,98/255,144/255);
  1066. glVertex3f( 1.0, 1.0, 1.0);
  1067. glVertex3f(-1.0, 1.0, 1.0);
  1068. glEnd();
  1069. glPopMatrix();
  1070. glEnable(GL_DEPTH_TEST);
  1071. glMatrixMode(GL_MODELVIEW);
  1072. glPopMatrix();
  1073. glEnable(GL_LIGHTING);
  1074. }
  1075. # draw ground and axes
  1076. glDisable(GL_LIGHTING);
  1077. # draw ground
  1078. my $ground_z = GROUND_Z;
  1079. if ($self->bed_triangles) {
  1080. glDisable(GL_DEPTH_TEST);
  1081. glEnable(GL_BLEND);
  1082. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1083. glEnableClientState(GL_VERTEX_ARRAY);
  1084. glColor4f(0.8, 0.6, 0.5, 0.4);
  1085. glNormal3d(0,0,1);
  1086. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_triangles->ptr());
  1087. glDrawArrays(GL_TRIANGLES, 0, $self->bed_triangles->elements / 3);
  1088. glDisableClientState(GL_VERTEX_ARRAY);
  1089. # we need depth test for grid, otherwise it would disappear when looking
  1090. # the object from below
  1091. glEnable(GL_DEPTH_TEST);
  1092. # draw grid
  1093. glLineWidth(3);
  1094. glColor4f(0.2, 0.2, 0.2, 0.4);
  1095. glEnableClientState(GL_VERTEX_ARRAY);
  1096. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_grid_lines->ptr());
  1097. glDrawArrays(GL_LINES, 0, $self->bed_grid_lines->elements / 3);
  1098. glDisableClientState(GL_VERTEX_ARRAY);
  1099. glDisable(GL_BLEND);
  1100. }
  1101. my $volumes_bb = $self->volumes_bounding_box;
  1102. {
  1103. # draw axes
  1104. # disable depth testing so that axes are not covered by ground
  1105. glDisable(GL_DEPTH_TEST);
  1106. my $origin = $self->origin;
  1107. my $axis_len = max(
  1108. 0.3 * max(@{ $self->bed_bounding_box->size }),
  1109. 2 * max(@{ $volumes_bb->size }),
  1110. );
  1111. glLineWidth(2);
  1112. glBegin(GL_LINES);
  1113. # draw line for x axis
  1114. glColor3f(1, 0, 0);
  1115. glVertex3f(@$origin, $ground_z);
  1116. glVertex3f($origin->x + $axis_len, $origin->y, $ground_z); #,,
  1117. # draw line for y axis
  1118. glColor3f(0, 1, 0);
  1119. glVertex3f(@$origin, $ground_z);
  1120. glVertex3f($origin->x, $origin->y + $axis_len, $ground_z); #++
  1121. glEnd();
  1122. # draw line for Z axis
  1123. # (re-enable depth test so that axis is correctly shown when objects are behind it)
  1124. glEnable(GL_DEPTH_TEST);
  1125. glBegin(GL_LINES);
  1126. glColor3f(0, 0, 1);
  1127. glVertex3f(@$origin, $ground_z);
  1128. glVertex3f(@$origin, $ground_z+$axis_len);
  1129. glEnd();
  1130. }
  1131. glEnable(GL_LIGHTING);
  1132. # draw objects
  1133. if (! $self->use_plain_shader) {
  1134. $self->draw_volumes;
  1135. } elsif ($self->UseVBOs) {
  1136. $self->{plain_shader}->enable if $self->{plain_shader};
  1137. $self->volumes->render_VBOs;
  1138. $self->{plain_shader}->disable;
  1139. } else {
  1140. $self->volumes->render_legacy;
  1141. }
  1142. # draw cutting plane
  1143. if (defined $self->cutting_plane_z) {
  1144. my $plane_z = $self->cutting_plane_z;
  1145. my $bb = $volumes_bb;
  1146. glDisable(GL_CULL_FACE);
  1147. glDisable(GL_LIGHTING);
  1148. glEnable(GL_BLEND);
  1149. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1150. glBegin(GL_QUADS);
  1151. glColor4f(0.8, 0.8, 0.8, 0.5);
  1152. glVertex3f($bb->x_min-20, $bb->y_min-20, $plane_z);
  1153. glVertex3f($bb->x_max+20, $bb->y_min-20, $plane_z);
  1154. glVertex3f($bb->x_max+20, $bb->y_max+20, $plane_z);
  1155. glVertex3f($bb->x_min-20, $bb->y_max+20, $plane_z);
  1156. glEnd();
  1157. glEnable(GL_CULL_FACE);
  1158. glDisable(GL_BLEND);
  1159. }
  1160. $self->draw_active_object_annotations;
  1161. $self->SwapBuffers();
  1162. # Calling glFinish has a performance penalty, but it seems to fix some OpenGL driver hang-up with extremely large scenes.
  1163. # glFinish();
  1164. }
  1165. sub draw_volumes {
  1166. # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking.
  1167. my ($self, $fakecolor) = @_;
  1168. glEnable(GL_BLEND);
  1169. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1170. glEnableClientState(GL_VERTEX_ARRAY);
  1171. glEnableClientState(GL_NORMAL_ARRAY);
  1172. my $z_cursor_relative = $self->_variable_layer_thickness_bar_mouse_cursor_z_relative;
  1173. foreach my $volume_idx (0..$#{$self->volumes}) {
  1174. my $volume = $self->volumes->[$volume_idx];
  1175. my $shader_active = 0;
  1176. my $object_id = int($volume->select_group_id / 1000000);
  1177. if ($self->layer_editing_enabled && ! $fakecolor && $volume->selected && $self->{layer_height_edit_shader} &&
  1178. $volume->has_layer_height_texture && $object_id < $self->{print}->object_count) {
  1179. # Update the height texture if the ModelObject::layer_height_texture is invalid.
  1180. $volume->generate_layer_height_texture($self->{print}->get_object($object_id), 0);
  1181. $self->{layer_height_edit_shader}->enable;
  1182. $self->{layer_height_edit_shader}->set_uniform('z_to_texture_row', $volume->layer_height_texture_z_to_row_id);
  1183. $self->{layer_height_edit_shader}->set_uniform('z_texture_row_to_normalized', 1. / $volume->layer_height_texture_height);
  1184. $self->{layer_height_edit_shader}->set_uniform('z_cursor', $volume->bounding_box->z_max * $z_cursor_relative);
  1185. $self->{layer_height_edit_shader}->set_uniform('z_cursor_band_width', $self->{layer_height_edit_band_width});
  1186. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  1187. # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LEVEL, 0);
  1188. # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  1189. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1190. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1191. glTexImage2D_c(GL_TEXTURE_2D, 1, GL_RGBA8, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1192. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1193. # glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  1194. # glPixelStorei(GL_UNPACK_ROW_LENGTH, $self->{layer_preview_z_texture_width});
  1195. glTexSubImage2D_c(GL_TEXTURE_2D, 0, 0, 0, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1196. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level0);
  1197. glTexSubImage2D_c(GL_TEXTURE_2D, 1, 0, 0, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1198. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level1);
  1199. $shader_active = 1;
  1200. } elsif ($fakecolor) {
  1201. # Object picking mode. Render the object with a color encoding the object index.
  1202. my $r = ($volume_idx & 0x000000FF) >> 0;
  1203. my $g = ($volume_idx & 0x0000FF00) >> 8;
  1204. my $b = ($volume_idx & 0x00FF0000) >> 16;
  1205. glColor4f($r/255.0, $g/255.0, $b/255.0, 1);
  1206. } elsif ($volume->selected) {
  1207. glColor4f(@{ &SELECTED_COLOR });
  1208. } elsif ($volume->hover) {
  1209. glColor4f(@{ &HOVER_COLOR });
  1210. } else {
  1211. glColor4f(@{ $volume->color });
  1212. }
  1213. $volume->render;
  1214. if ($shader_active) {
  1215. glBindTexture(GL_TEXTURE_2D, 0);
  1216. $self->{layer_height_edit_shader}->disable;
  1217. }
  1218. }
  1219. glDisableClientState(GL_NORMAL_ARRAY);
  1220. glDisable(GL_BLEND);
  1221. if (defined $self->cutting_plane_z) {
  1222. glLineWidth(2);
  1223. glColor3f(0, 0, 0);
  1224. glVertexPointer_c(3, GL_FLOAT, 0, $self->cut_lines_vertices->ptr());
  1225. glDrawArrays(GL_LINES, 0, $self->cut_lines_vertices->elements / 3);
  1226. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  1227. }
  1228. glDisableClientState(GL_VERTEX_ARRAY);
  1229. }
  1230. sub _load_image_set_texture {
  1231. my ($self, $file_name) = @_;
  1232. # Load a PNG with an alpha channel.
  1233. my $img = Wx::Image->new;
  1234. $img->LoadFile(Slic3r::var($file_name), wxBITMAP_TYPE_PNG);
  1235. # Get RGB & alpha raw data from wxImage, interleave them into a Perl array.
  1236. my @rgb = unpack 'C*', $img->GetData();
  1237. my @alpha = $img->HasAlpha ? unpack 'C*', $img->GetAlpha() : (255) x (int(@rgb) / 3);
  1238. my $n_pixels = int(@alpha);
  1239. my @data = (0)x($n_pixels * 4);
  1240. for (my $i = 0; $i < $n_pixels; $i += 1) {
  1241. $data[$i*4 ] = $rgb[$i*3];
  1242. $data[$i*4+1] = $rgb[$i*3+1];
  1243. $data[$i*4+2] = $rgb[$i*3+2];
  1244. $data[$i*4+3] = $alpha[$i];
  1245. }
  1246. # Initialize a raw bitmap data.
  1247. my $params = {
  1248. loaded => 1,
  1249. valid => $n_pixels > 0,
  1250. width => $img->GetWidth,
  1251. height => $img->GetHeight,
  1252. data => OpenGL::Array->new_list(GL_UNSIGNED_BYTE, @data),
  1253. texture_id => glGenTextures_p(1)
  1254. };
  1255. # Create and initialize a texture with the raw data.
  1256. glBindTexture(GL_TEXTURE_2D, $params->{texture_id});
  1257. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1258. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1259. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
  1260. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $params->{width}, $params->{height}, 0, GL_RGBA, GL_UNSIGNED_BYTE, $params->{data}->ptr);
  1261. glBindTexture(GL_TEXTURE_2D, 0);
  1262. return $params;
  1263. }
  1264. sub _variable_layer_thickness_load_overlay_image {
  1265. my ($self) = @_;
  1266. $self->{layer_preview_annotation} = $self->_load_image_set_texture('variable_layer_height_tooltip.png')
  1267. if (! $self->{layer_preview_annotation}->{loaded});
  1268. return $self->{layer_preview_annotation}->{valid};
  1269. }
  1270. sub _variable_layer_thickness_load_reset_image {
  1271. my ($self) = @_;
  1272. $self->{layer_preview_reset_image} = $self->_load_image_set_texture('variable_layer_height_reset.png')
  1273. if (! $self->{layer_preview_reset_image}->{loaded});
  1274. return $self->{layer_preview_reset_image}->{valid};
  1275. }
  1276. # Paint the tooltip.
  1277. sub _render_image {
  1278. my ($self, $image, $l, $r, $b, $t) = @_;
  1279. glColor4f(1.,1.,1.,1.);
  1280. glDisable(GL_LIGHTING);
  1281. glEnable(GL_BLEND);
  1282. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1283. glEnable(GL_TEXTURE_2D);
  1284. glBindTexture(GL_TEXTURE_2D, $image->{texture_id});
  1285. glBegin(GL_QUADS);
  1286. glTexCoord2d(0.,1.); glVertex3f($l, $b, 0);
  1287. glTexCoord2d(1.,1.); glVertex3f($r, $b, 0);
  1288. glTexCoord2d(1.,0.); glVertex3f($r, $t, 0);
  1289. glTexCoord2d(0.,0.); glVertex3f($l, $t, 0);
  1290. glEnd();
  1291. glBindTexture(GL_TEXTURE_2D, 0);
  1292. glDisable(GL_TEXTURE_2D);
  1293. glDisable(GL_BLEND);
  1294. glEnable(GL_LIGHTING);
  1295. }
  1296. sub draw_active_object_annotations {
  1297. # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking.
  1298. my ($self) = @_;
  1299. return if (! $self->{layer_height_edit_shader} || ! $self->layer_editing_enabled);
  1300. # Find the selected volume, over which the layer editing is active.
  1301. my $volume;
  1302. foreach my $volume_idx (0..$#{$self->volumes}) {
  1303. my $v = $self->volumes->[$volume_idx];
  1304. if ($v->selected && $v->has_layer_height_texture) {
  1305. $volume = $v;
  1306. last;
  1307. }
  1308. }
  1309. return if (! $volume);
  1310. # If the active object was not allocated at the Print, go away. This should only be a momentary case between an object addition / deletion
  1311. # and an update by Platter::async_apply_config.
  1312. my $object_idx = int($volume->select_group_id / 1000000);
  1313. return if $object_idx >= $self->{print}->object_count;
  1314. # The viewport and camera are set to complete view and glOrtho(-$x/2, $x/2, -$y/2, $y/2, -$depth, $depth),
  1315. # where x, y is the window size divided by $self->_zoom.
  1316. my ($bar_left, $bar_bottom, $bar_right, $bar_top) = $self->_variable_layer_thickness_bar_rect_viewport;
  1317. my ($reset_left, $reset_bottom, $reset_right, $reset_top) = $self->_variable_layer_thickness_reset_rect_viewport;
  1318. my $z_cursor_relative = $self->_variable_layer_thickness_bar_mouse_cursor_z_relative;
  1319. $self->{layer_height_edit_shader}->enable;
  1320. $self->{layer_height_edit_shader}->set_uniform('z_to_texture_row', $volume->layer_height_texture_z_to_row_id);
  1321. $self->{layer_height_edit_shader}->set_uniform('z_texture_row_to_normalized', 1. / $volume->layer_height_texture_height);
  1322. $self->{layer_height_edit_shader}->set_uniform('z_cursor', $volume->bounding_box->z_max * $z_cursor_relative);
  1323. $self->{layer_height_edit_shader}->set_uniform('z_cursor_band_width', $self->{layer_height_edit_band_width});
  1324. glBindTexture(GL_TEXTURE_2D, $self->{layer_preview_z_texture_id});
  1325. glTexImage2D_c(GL_TEXTURE_2D, 0, GL_RGBA8, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1326. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1327. glTexImage2D_c(GL_TEXTURE_2D, 1, GL_RGBA8, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1328. 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  1329. glTexSubImage2D_c(GL_TEXTURE_2D, 0, 0, 0, $volume->layer_height_texture_width, $volume->layer_height_texture_height,
  1330. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level0);
  1331. glTexSubImage2D_c(GL_TEXTURE_2D, 1, 0, 0, $volume->layer_height_texture_width / 2, $volume->layer_height_texture_height / 2,
  1332. GL_RGBA, GL_UNSIGNED_BYTE, $volume->layer_height_texture_data_ptr_level1);
  1333. # Render the color bar.
  1334. glDisable(GL_DEPTH_TEST);
  1335. # The viewport and camera are set to complete view and glOrtho(-$x/2, $x/2, -$y/2, $y/2, -$depth, $depth),
  1336. # where x, y is the window size divided by $self->_zoom.
  1337. glPushMatrix();
  1338. glLoadIdentity();
  1339. # Paint the overlay.
  1340. glBegin(GL_QUADS);
  1341. glVertex3f($bar_left, $bar_bottom, 0);
  1342. glVertex3f($bar_right, $bar_bottom, 0);
  1343. glVertex3f($bar_right, $bar_top, $volume->bounding_box->z_max);
  1344. glVertex3f($bar_left, $bar_top, $volume->bounding_box->z_max);
  1345. glEnd();
  1346. glBindTexture(GL_TEXTURE_2D, 0);
  1347. $self->{layer_height_edit_shader}->disable;
  1348. # Paint the tooltip.
  1349. if ($self->_variable_layer_thickness_load_overlay_image) {
  1350. my $gap = 10/$self->_zoom;
  1351. my ($l, $r, $b, $t) = ($bar_left - $self->{layer_preview_annotation}->{width}/$self->_zoom - $gap, $bar_left - $gap, $reset_bottom + $self->{layer_preview_annotation}->{height}/$self->_zoom + $gap, $reset_bottom + $gap);
  1352. $self->_render_image($self->{layer_preview_annotation}, $l, $r, $t, $b);
  1353. }
  1354. # Paint the reset button.
  1355. if ($self->_variable_layer_thickness_load_reset_image) {
  1356. $self->_render_image($self->{layer_preview_reset_image}, $reset_left, $reset_right, $reset_bottom, $reset_top);
  1357. }
  1358. # Paint the graph.
  1359. #FIXME show some kind of legend.
  1360. my $print_object = $self->{print}->get_object($object_idx);
  1361. my $max_z = unscale($print_object->size->z);
  1362. my $profile = $print_object->model_object->layer_height_profile;
  1363. my $layer_height = $print_object->config->get('layer_height');
  1364. my $layer_height_max = 10000000000.;
  1365. {
  1366. # Get a maximum layer height value.
  1367. #FIXME This is a duplicate code of Slicing.cpp.
  1368. my $nozzle_diameters = $print_object->print->config->get('nozzle_diameter');
  1369. my $layer_heights_min = $print_object->print->config->get('min_layer_height');
  1370. my $layer_heights_max = $print_object->print->config->get('max_layer_height');
  1371. for (my $i = 0; $i < scalar(@{$nozzle_diameters}); $i += 1) {
  1372. my $lh_min = ($layer_heights_min->[$i] == 0.) ? 0.07 : max(0.01, $layer_heights_min->[$i]);
  1373. my $lh_max = ($layer_heights_max->[$i] == 0.) ? (0.75 * $nozzle_diameters->[$i]) : $layer_heights_max->[$i];
  1374. $layer_height_max = min($layer_height_max, max($lh_min, $lh_max));
  1375. }
  1376. }
  1377. # Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region.
  1378. $layer_height_max *= 1.12;
  1379. # Baseline
  1380. glColor3f(0., 0., 0.);
  1381. glBegin(GL_LINE_STRIP);
  1382. glVertex2f($bar_left + $layer_height * ($bar_right - $bar_left) / $layer_height_max, $bar_bottom);
  1383. glVertex2f($bar_left + $layer_height * ($bar_right - $bar_left) / $layer_height_max, $bar_top);
  1384. glEnd();
  1385. # Curve
  1386. glColor3f(0., 0., 1.);
  1387. glBegin(GL_LINE_STRIP);
  1388. for (my $i = 0; $i < int(@{$profile}); $i += 2) {
  1389. my $z = $profile->[$i];
  1390. my $h = $profile->[$i+1];
  1391. glVertex3f($bar_left + $h * ($bar_right - $bar_left) / $layer_height_max, $bar_bottom + $z * ($bar_top - $bar_bottom) / $max_z, $z);
  1392. }
  1393. glEnd();
  1394. # Revert the matrices.
  1395. glPopMatrix();
  1396. glEnable(GL_DEPTH_TEST);
  1397. }
  1398. sub opengl_info
  1399. {
  1400. my ($self, %params) = @_;
  1401. my %tag = Slic3r::tags($params{format});
  1402. my $gl_version = glGetString(GL_VERSION);
  1403. my $gl_vendor = glGetString(GL_VENDOR);
  1404. my $gl_renderer = glGetString(GL_RENDERER);
  1405. my $glsl_version = glGetString(GL_SHADING_LANGUAGE_VERSION);
  1406. my $out = '';
  1407. $out .= "$tag{h2start}OpenGL installation$tag{h2end}$tag{eol}";
  1408. $out .= " $tag{bstart}Using POGL$tag{bend} v$OpenGL::BUILD_VERSION$tag{eol}";
  1409. $out .= " $tag{bstart}GL version: $tag{bend}${gl_version}$tag{eol}";
  1410. $out .= " $tag{bstart}vendor: $tag{bend}${gl_vendor}$tag{eol}";
  1411. $out .= " $tag{bstart}renderer: $tag{bend}${gl_renderer}$tag{eol}";
  1412. $out .= " $tag{bstart}GLSL version: $tag{bend}${glsl_version}$tag{eol}";
  1413. # Check for other OpenGL extensions
  1414. $out .= "$tag{h2start}Installed extensions (* implemented in the module):$tag{h2end}$tag{eol}";
  1415. my $extensions = glGetString(GL_EXTENSIONS);
  1416. my @extensions = split(' ',$extensions);
  1417. foreach my $ext (sort @extensions) {
  1418. my $stat = glpCheckExtension($ext);
  1419. $out .= sprintf("%s ${ext}$tag{eol}", $stat?' ':'*');
  1420. $out .= sprintf(" ${stat}$tag{eol}") if ($stat && $stat !~ m|^$ext |);
  1421. }
  1422. return $out;
  1423. }
  1424. sub _report_opengl_state
  1425. {
  1426. my ($self, $comment) = @_;
  1427. my $err = glGetError();
  1428. return 0 if ($err == 0);
  1429. # gluErrorString() hangs. Don't use it.
  1430. # my $errorstr = gluErrorString();
  1431. my $errorstr = '';
  1432. if ($err == 0x0500) {
  1433. $errorstr = 'GL_INVALID_ENUM';
  1434. } elsif ($err == GL_INVALID_VALUE) {
  1435. $errorstr = 'GL_INVALID_VALUE';
  1436. } elsif ($err == GL_INVALID_OPERATION) {
  1437. $errorstr = 'GL_INVALID_OPERATION';
  1438. } elsif ($err == GL_STACK_OVERFLOW) {
  1439. $errorstr = 'GL_STACK_OVERFLOW';
  1440. } elsif ($err == GL_OUT_OF_MEMORY) {
  1441. $errorstr = 'GL_OUT_OF_MEMORY';
  1442. } else {
  1443. $errorstr = 'unknown';
  1444. }
  1445. if (defined($comment)) {
  1446. printf("OpenGL error at %s, nr %d (0x%x): %s\n", $comment, $err, $err, $errorstr);
  1447. } else {
  1448. printf("OpenGL error nr %d (0x%x): %s\n", $err, $err, $errorstr);
  1449. }
  1450. }
  1451. sub _vertex_shader_Gouraud {
  1452. return <<'VERTEX';
  1453. #version 110
  1454. #define INTENSITY_CORRECTION 0.7
  1455. #define LIGHT_TOP_DIR -0.6/1.31, 0.6/1.31, 1./1.31
  1456. #define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
  1457. #define LIGHT_TOP_SPECULAR (0.5 * INTENSITY_CORRECTION)
  1458. #define LIGHT_TOP_SHININESS 50.
  1459. #define LIGHT_FRONT_DIR 1./1.43, 0.2/1.43, 1./1.43
  1460. #define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
  1461. #define LIGHT_FRONT_SPECULAR (0.0 * INTENSITY_CORRECTION)
  1462. #define LIGHT_FRONT_SHININESS 50.
  1463. #define INTENSITY_AMBIENT 0.3
  1464. varying float intensity_specular;
  1465. varying float intensity_tainted;
  1466. void main()
  1467. {
  1468. vec3 eye, normal, lightDir, viewVector, halfVector;
  1469. float NdotL, NdotHV;
  1470. eye = vec3(0., 0., 1.);
  1471. // First transform the normal into eye space and normalize the result.
  1472. normal = normalize(gl_NormalMatrix * gl_Normal);
  1473. // Now normalize the light's direction. Note that according to the OpenGL specification, the light is stored in eye space.
  1474. // Also since we're talking about a directional light, the position field is actually direction.
  1475. lightDir = vec3(LIGHT_TOP_DIR);
  1476. halfVector = normalize(lightDir + eye);
  1477. // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
  1478. // Since these two are normalized the cosine is the dot product. We also need to clamp the result to the [0,1] range.
  1479. NdotL = max(dot(normal, lightDir), 0.0);
  1480. intensity_tainted = INTENSITY_AMBIENT + NdotL * LIGHT_TOP_DIFFUSE;
  1481. intensity_specular = 0.;
  1482. if (NdotL > 0.0)
  1483. intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_TOP_SHININESS);
  1484. // Perform the same lighting calculation for the 2nd light source.
  1485. lightDir = vec3(LIGHT_FRONT_DIR);
  1486. // halfVector = normalize(lightDir + eye);
  1487. NdotL = max(dot(normal, lightDir), 0.0);
  1488. intensity_tainted += NdotL * LIGHT_FRONT_DIFFUSE;
  1489. // compute the specular term if NdotL is larger than zero
  1490. // if (NdotL > 0.0)
  1491. // intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_FRONT_SHININESS);
  1492. gl_Position = ftransform();
  1493. }
  1494. VERTEX
  1495. }
  1496. sub _fragment_shader_Gouraud {
  1497. return <<'FRAGMENT';
  1498. #version 110
  1499. varying float intensity_specular;
  1500. varying float intensity_tainted;
  1501. uniform vec4 uniform_color;
  1502. void main()
  1503. {
  1504. gl_FragColor =
  1505. vec4(intensity_specular, intensity_specular, intensity_specular, 0.) + uniform_color * intensity_tainted;
  1506. gl_FragColor.a = uniform_color.a;
  1507. }
  1508. FRAGMENT
  1509. }
  1510. sub _vertex_shader_Phong {
  1511. return <<'VERTEX';
  1512. #version 110
  1513. varying vec3 normal;
  1514. varying vec3 eye;
  1515. void main(void)
  1516. {
  1517. eye = normalize(vec3(gl_ModelViewMatrix * gl_Vertex));
  1518. normal = normalize(gl_NormalMatrix * gl_Normal);
  1519. gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
  1520. }
  1521. VERTEX
  1522. }
  1523. sub _fragment_shader_Phong {
  1524. return <<'FRAGMENT';
  1525. #version 110
  1526. #define INTENSITY_CORRECTION 0.7
  1527. #define LIGHT_TOP_DIR -0.6/1.31, 0.6/1.31, 1./1.31
  1528. #define LIGHT_TOP_DIFFUSE (0.8 * INTENSITY_CORRECTION)
  1529. #define LIGHT_TOP_SPECULAR (0.5 * INTENSITY_CORRECTION)
  1530. //#define LIGHT_TOP_SHININESS 50.
  1531. #define LIGHT_TOP_SHININESS 10.
  1532. #define LIGHT_FRONT_DIR 1./1.43, 0.2/1.43, 1./1.43
  1533. #define LIGHT_FRONT_DIFFUSE (0.3 * INTENSITY_CORRECTION)
  1534. #define LIGHT_FRONT_SPECULAR (0.0 * INTENSITY_CORRECTION)
  1535. #define LIGHT_FRONT_SHININESS 50.
  1536. #define INTENSITY_AMBIENT 0.0
  1537. varying vec3 normal;
  1538. varying vec3 eye;
  1539. uniform vec4 uniform_color;
  1540. void main() {
  1541. float intensity_specular = 0.;
  1542. float intensity_tainted = 0.;
  1543. float intensity = max(dot(normal,vec3(LIGHT_TOP_DIR)), 0.0);
  1544. // if the vertex is lit compute the specular color
  1545. if (intensity > 0.0) {
  1546. intensity_tainted = LIGHT_TOP_DIFFUSE * intensity;
  1547. // compute the half vector
  1548. vec3 h = normalize(vec3(LIGHT_TOP_DIR) + eye);
  1549. // compute the specular term into spec
  1550. intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(h, normal), 0.0), LIGHT_TOP_SHININESS);
  1551. }
  1552. intensity = max(dot(normal,vec3(LIGHT_FRONT_DIR)), 0.0);
  1553. // if the vertex is lit compute the specular color
  1554. if (intensity > 0.0) {
  1555. intensity_tainted += LIGHT_FRONT_DIFFUSE * intensity;
  1556. // compute the half vector
  1557. // vec3 h = normalize(vec3(LIGHT_FRONT_DIR) + eye);
  1558. // compute the specular term into spec
  1559. // intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(h,normal), 0.0), LIGHT_FRONT_SHININESS);
  1560. }
  1561. gl_FragColor = max(
  1562. vec4(intensity_specular, intensity_specular, intensity_specular, 0.) + uniform_color * intensity_tainted,
  1563. INTENSITY_AMBIENT * uniform_color);
  1564. gl_FragColor.a = uniform_color.a;
  1565. }
  1566. FRAGMENT
  1567. }
  1568. sub _vertex_shader_variable_layer_height {
  1569. return <<'VERTEX';
  1570. #version 110
  1571. #define LIGHT_TOP_DIR 0., 1., 0.
  1572. #define LIGHT_TOP_DIFFUSE 0.2
  1573. #define LIGHT_TOP_SPECULAR 0.3
  1574. #define LIGHT_TOP_SHININESS 50.
  1575. #define LIGHT_FRONT_DIR 0., 0., 1.
  1576. #define LIGHT_FRONT_DIFFUSE 0.5
  1577. #define LIGHT_FRONT_SPECULAR 0.3
  1578. #define LIGHT_FRONT_SHININESS 50.
  1579. #define INTENSITY_AMBIENT 0.1
  1580. uniform float z_to_texture_row;
  1581. varying float intensity_specular;
  1582. varying float intensity_tainted;
  1583. varying float object_z;
  1584. void main()
  1585. {
  1586. vec3 eye, normal, lightDir, viewVector, halfVector;
  1587. float NdotL, NdotHV;
  1588. // eye = gl_ModelViewMatrixInverse[3].xyz;
  1589. eye = vec3(0., 0., 1.);
  1590. // First transform the normal into eye space and normalize the result.
  1591. normal = normalize(gl_NormalMatrix * gl_Normal);
  1592. // Now normalize the light's direction. Note that according to the OpenGL specification, the light is stored in eye space.
  1593. // Also since we're talking about a directional light, the position field is actually direction.
  1594. lightDir = vec3(LIGHT_TOP_DIR);
  1595. halfVector = normalize(lightDir + eye);
  1596. // Compute the cos of the angle between the normal and lights direction. The light is directional so the direction is constant for every vertex.
  1597. // Since these two are normalized the cosine is the dot product. We also need to clamp the result to the [0,1] range.
  1598. NdotL = max(dot(normal, lightDir), 0.0);
  1599. intensity_tainted = INTENSITY_AMBIENT + NdotL * LIGHT_TOP_DIFFUSE;
  1600. intensity_specular = 0.;
  1601. // if (NdotL > 0.0)
  1602. // intensity_specular = LIGHT_TOP_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_TOP_SHININESS);
  1603. // Perform the same lighting calculation for the 2nd light source.
  1604. lightDir = vec3(LIGHT_FRONT_DIR);
  1605. halfVector = normalize(lightDir + eye);
  1606. NdotL = max(dot(normal, lightDir), 0.0);
  1607. intensity_tainted += NdotL * LIGHT_FRONT_DIFFUSE;
  1608. // compute the specular term if NdotL is larger than zero
  1609. if (NdotL > 0.0)
  1610. intensity_specular += LIGHT_FRONT_SPECULAR * pow(max(dot(normal, halfVector), 0.0), LIGHT_FRONT_SHININESS);
  1611. // Scaled to widths of the Z texture.
  1612. object_z = gl_Vertex.z / gl_Vertex.w;
  1613. gl_Position = ftransform();
  1614. }
  1615. VERTEX
  1616. }
  1617. sub _fragment_shader_variable_layer_height {
  1618. return <<'FRAGMENT';
  1619. #version 110
  1620. #define M_PI 3.1415926535897932384626433832795
  1621. // 2D texture (1D texture split by the rows) of color along the object Z axis.
  1622. uniform sampler2D z_texture;
  1623. // Scaling from the Z texture rows coordinate to the normalized texture row coordinate.
  1624. uniform float z_to_texture_row;
  1625. uniform float z_texture_row_to_normalized;
  1626. varying float intensity_specular;
  1627. varying float intensity_tainted;
  1628. varying float object_z;
  1629. uniform float z_cursor;
  1630. uniform float z_cursor_band_width;
  1631. void main()
  1632. {
  1633. float object_z_row = z_to_texture_row * object_z;
  1634. // Index of the row in the texture.
  1635. float z_texture_row = floor(object_z_row);
  1636. // Normalized coordinate from 0. to 1.
  1637. float z_texture_col = object_z_row - z_texture_row;
  1638. float z_blend = 0.25 * cos(min(M_PI, abs(M_PI * (object_z - z_cursor) * 1.8 / z_cursor_band_width))) + 0.25;
  1639. // Calculate level of detail from the object Z coordinate.
  1640. // This makes the slowly sloping surfaces to be show with high detail (with stripes),
  1641. // and the vertical surfaces to be shown with low detail (no stripes)
  1642. float z_in_cells = object_z_row * 190.;
  1643. // Gradient of Z projected on the screen.
  1644. float dx_vtc = dFdx(z_in_cells);
  1645. float dy_vtc = dFdy(z_in_cells);
  1646. float lod = clamp(0.5 * log2(max(dx_vtc*dx_vtc, dy_vtc*dy_vtc)), 0., 1.);
  1647. // Sample the Z texture. Texture coordinates are normalized to <0, 1>.
  1648. vec4 color =
  1649. (1. - lod) * texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.) +
  1650. lod * texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.);
  1651. // Mix the final color.
  1652. gl_FragColor =
  1653. vec4(intensity_specular, intensity_specular, intensity_specular, 1.) +
  1654. (1. - z_blend) * intensity_tainted * color +
  1655. z_blend * vec4(1., 1., 0., 0.);
  1656. // and reset the transparency.
  1657. gl_FragColor.a = 1.;
  1658. }
  1659. FRAGMENT
  1660. }
  1661. # The 3D canvas to display objects and tool paths.
  1662. package Slic3r::GUI::3DScene;
  1663. use base qw(Slic3r::GUI::3DScene::Base);
  1664. use OpenGL qw(:glconstants :gluconstants :glufunctions);
  1665. use List::Util qw(first min max);
  1666. use Slic3r::Geometry qw(scale unscale epsilon);
  1667. use Slic3r::Print::State ':steps';
  1668. __PACKAGE__->mk_accessors(qw(
  1669. color_by
  1670. select_by
  1671. drag_by
  1672. ));
  1673. sub new {
  1674. my $class = shift;
  1675. my $self = $class->SUPER::new(@_);
  1676. $self->color_by('volume'); # object | volume
  1677. $self->select_by('object'); # object | volume | instance
  1678. $self->drag_by('instance'); # object | instance
  1679. return $self;
  1680. }
  1681. sub load_object {
  1682. my ($self, $model, $print, $obj_idx, $instance_idxs) = @_;
  1683. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1684. my $model_object;
  1685. if ($model->isa('Slic3r::Model::Object')) {
  1686. $model_object = $model;
  1687. $model = $model_object->model;
  1688. $obj_idx = 0;
  1689. } else {
  1690. $model_object = $model->get_object($obj_idx);
  1691. }
  1692. $instance_idxs ||= [0..$#{$model_object->instances}];
  1693. my $volume_indices = $self->volumes->load_object(
  1694. $model_object, $obj_idx, $instance_idxs, $self->color_by, $self->select_by, $self->drag_by,
  1695. $self->UseVBOs);
  1696. return @{$volume_indices};
  1697. }
  1698. # Create 3D thick extrusion lines for a skirt and brim.
  1699. # Adds a new Slic3r::GUI::3DScene::Volume to $self->volumes.
  1700. sub load_print_toolpaths {
  1701. my ($self, $print, $colors) = @_;
  1702. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1703. Slic3r::GUI::_3DScene::_load_print_toolpaths($print, $self->volumes, $colors, $self->UseVBOs)
  1704. if ($print->step_done(STEP_SKIRT) && $print->step_done(STEP_BRIM));
  1705. }
  1706. # Create 3D thick extrusion lines for object forming extrusions.
  1707. # Adds a new Slic3r::GUI::3DScene::Volume to $self->volumes,
  1708. # one for perimeters, one for infill and one for supports.
  1709. sub load_print_object_toolpaths {
  1710. my ($self, $object, $colors) = @_;
  1711. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1712. Slic3r::GUI::_3DScene::_load_print_object_toolpaths($object, $self->volumes, $colors, $self->UseVBOs);
  1713. }
  1714. # Create 3D thick extrusion lines for wipe tower extrusions.
  1715. sub load_wipe_tower_toolpaths {
  1716. my ($self, $print, $colors) = @_;
  1717. $self->SetCurrent($self->GetContext) if $self->UseVBOs;
  1718. Slic3r::GUI::_3DScene::_load_wipe_tower_toolpaths($print, $self->volumes, $colors, $self->UseVBOs)
  1719. if ($print->step_done(STEP_WIPE_TOWER));
  1720. }
  1721. sub set_toolpaths_range {
  1722. my ($self, $min_z, $max_z) = @_;
  1723. $self->volumes->set_range($min_z, $max_z);
  1724. }
  1725. 1;