3DScene.pm 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. package Slic3r::GUI::3DScene::Base;
  2. use strict;
  3. use warnings;
  4. use Wx::Event qw(EVT_PAINT EVT_SIZE EVT_ERASE_BACKGROUND EVT_IDLE EVT_MOUSEWHEEL EVT_MOUSE_EVENTS);
  5. # must load OpenGL *before* Wx::GLCanvas
  6. use OpenGL qw(:glconstants :glfunctions :glufunctions :gluconstants);
  7. use base qw(Wx::GLCanvas Class::Accessor);
  8. use Math::Trig qw(asin);
  9. use List::Util qw(reduce min max first);
  10. use Slic3r::Geometry qw(X Y Z MIN MAX triangle_normal normalize deg2rad tan scale unscale scaled_epsilon);
  11. use Slic3r::Geometry::Clipper qw(offset_ex intersection_pl);
  12. use Wx::GLCanvas qw(:all);
  13. __PACKAGE__->mk_accessors( qw(_quat _dirty init
  14. enable_picking
  15. enable_face_select
  16. enable_moving
  17. on_viewport_changed
  18. on_hover
  19. on_select
  20. on_double_click
  21. on_right_click
  22. on_move
  23. volumes
  24. _sphi _stheta
  25. cutting_plane_axis
  26. cutting_plane_z
  27. cut_lines_vertices
  28. bed_shape
  29. bed_triangles
  30. bed_grid_lines
  31. background
  32. origin
  33. _mouse_pos
  34. _hover_volume_idx
  35. _drag_volume_idx
  36. _drag_start_pos
  37. _drag_start_xy
  38. _dragged
  39. _camera_target
  40. _zoom
  41. ) );
  42. use constant TRACKBALLSIZE => 0.8;
  43. use constant TURNTABLE_MODE => 1;
  44. use constant GROUND_Z => -0.02;
  45. use constant PI => 3.1415927;
  46. # Constant to determine if Vertex Buffer objects are used to draw
  47. # bed grid and the cut plane for object separation.
  48. use constant HAS_VBO => eval { glGenBuffersARB_p(0); GL_ARRAY_BUFFER_ARB; 1 };
  49. # phi / theta angles to orient the camera.
  50. use constant VIEW_TOP => [0.0,0.0];
  51. use constant VIEW_BOTTOM => [0.0,180.0];
  52. use constant VIEW_LEFT => [90.0,90.0];
  53. use constant VIEW_RIGHT => [-90.0,90.0];
  54. use constant VIEW_FRONT => [0.0,90.0];
  55. use constant VIEW_BACK => [180.0,90.0];
  56. use constant VIEW_DIAGONAL => [45.0,45.0];
  57. # Color Scheme
  58. use Slic3r::GUI::ColorScheme;
  59. use constant GIMBAL_LOCK_THETA_MAX => 170;
  60. # make OpenGL::Array thread-safe
  61. {
  62. no warnings 'redefine';
  63. *OpenGL::Array::CLONE_SKIP = sub { 1 };
  64. }
  65. sub new {
  66. my ($class, $parent) = @_;
  67. if ( ( defined $Slic3r::GUI::Settings->{_}{colorscheme} ) && ( Slic3r::GUI::ColorScheme->can($Slic3r::GUI::Settings->{_}{colorscheme}) ) ) {
  68. my $myGetSchemeName = \&{"Slic3r::GUI::ColorScheme::$Slic3r::GUI::Settings->{_}{colorscheme}"};
  69. $myGetSchemeName->();
  70. } else {
  71. Slic3r::GUI::ColorScheme->getDefault();
  72. }
  73. # We can only enable multi sample anti aliasing with wxWidgets 3.0.3 and with a hacked Wx::GLCanvas,
  74. # which exports some new WX_GL_XXX constants, namely WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES.
  75. my $can_multisample =
  76. Wx::wxVERSION >= 3.000003 &&
  77. defined Wx::GLCanvas->can('WX_GL_SAMPLE_BUFFERS') &&
  78. defined Wx::GLCanvas->can('WX_GL_SAMPLES');
  79. my $attrib = [WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 24];
  80. if ($can_multisample) {
  81. # Request a window with multi sampled anti aliasing. This is a new feature in Wx 3.0.3 (backported from 3.1.0).
  82. # Use eval to avoid compilation, if the subs WX_GL_SAMPLE_BUFFERS and WX_GL_SAMPLES are missing.
  83. eval 'push(@$attrib, (WX_GL_SAMPLE_BUFFERS, 1, WX_GL_SAMPLES, 4));';
  84. }
  85. # wxWidgets expect the attrib list to be ended by zero.
  86. push(@$attrib, 0);
  87. # we request a depth buffer explicitely because it looks like it's not created by
  88. # default on Linux, causing transparency issues
  89. my $self = $class->SUPER::new($parent, -1, Wx::wxDefaultPosition, Wx::wxDefaultSize, 0, "", $attrib);
  90. if (Wx::wxVERSION >= 3.000003) {
  91. # Wx 3.0.3 contains an ugly hack to support some advanced OpenGL attributes through the attribute list.
  92. # The attribute list is transferred between the wxGLCanvas and wxGLContext constructors using a single static array s_wglContextAttribs.
  93. # Immediatelly force creation of the OpenGL context to consume the static variable s_wglContextAttribs.
  94. $self->GetContext();
  95. }
  96. $self->{can_multisample} = $can_multisample;
  97. $self->background(1);
  98. $self->_quat((0, 0, 0, 1));
  99. $self->_stheta(45);
  100. $self->_sphi(45);
  101. $self->_zoom(1);
  102. # 3D point in model space
  103. $self->_camera_target(Slic3r::Pointf3->new(0,0,0));
  104. $self->reset_objects;
  105. EVT_PAINT($self, sub {
  106. my $dc = Wx::PaintDC->new($self);
  107. $self->Render($dc);
  108. });
  109. EVT_SIZE($self, sub { $self->_dirty(1) });
  110. EVT_IDLE($self, sub {
  111. return unless $self->_dirty;
  112. return if !$self->IsShownOnScreen;
  113. $self->Resize( $self->GetSizeWH );
  114. $self->Refresh;
  115. });
  116. EVT_MOUSEWHEEL($self, sub {
  117. my ($self, $e) = @_;
  118. # Calculate the zoom delta and apply it to the current zoom factor
  119. my $zoom = $e->GetWheelRotation() / $e->GetWheelDelta();
  120. if ($Slic3r::GUI::Settings->{_}{invert_zoom}) {
  121. $zoom *= -1;
  122. }
  123. $zoom = max(min($zoom, 4), -4);
  124. $zoom /= 10;
  125. $self->_zoom($self->_zoom / (1-$zoom));
  126. # In order to zoom around the mouse point we need to translate
  127. # the camera target
  128. my $size = Slic3r::Pointf->new($self->GetSizeWH);
  129. my $pos = Slic3r::Pointf->new($e->GetX, $size->y - $e->GetY); #-
  130. $self->_camera_target->translate(
  131. # ($pos - $size/2) represents the vector from the viewport center
  132. # to the mouse point. By multiplying it by $zoom we get the new,
  133. # transformed, length of such vector.
  134. # Since we want that point to stay fixed, we move our camera target
  135. # in the opposite direction by the delta of the length of such vector
  136. # ($zoom - 1). We then scale everything by 1/$self->_zoom since
  137. # $self->_camera_target is expressed in terms of model units.
  138. -($pos->x - $size->x/2) * ($zoom) / $self->_zoom,
  139. -($pos->y - $size->y/2) * ($zoom) / $self->_zoom,
  140. 0,
  141. ) if 0;
  142. $self->on_viewport_changed->() if $self->on_viewport_changed;
  143. $self->_dirty(1);
  144. $self->Refresh;
  145. });
  146. EVT_MOUSE_EVENTS($self, \&mouse_event);
  147. return $self;
  148. }
  149. sub mouse_event {
  150. my ($self, $e) = @_;
  151. my $pos = Slic3r::Pointf->new($e->GetPositionXY);
  152. if ($e->Entering && &Wx::wxMSW) {
  153. # wxMSW needs focus in order to catch mouse wheel events
  154. $self->SetFocus;
  155. } elsif ($e->LeftDClick) {
  156. $self->on_double_click->()
  157. if $self->on_double_click;
  158. } elsif ($e->MiddleDClick) {
  159. if (@{$self->volumes}) {
  160. $self->zoom_to_volumes;
  161. } else {
  162. $self->zoom_to_bed;
  163. }
  164. $self->_dirty(1);
  165. $self->Refresh;
  166. } elsif (($e->LeftDown || $e->RightDown) && not $e->ShiftDown) {
  167. # If user pressed left or right button we first check whether this happened
  168. # on a volume or not.
  169. my $volume_idx = $self->_hover_volume_idx // -1;
  170. # select volume in this 3D canvas
  171. if ($self->enable_picking) {
  172. $self->deselect_volumes;
  173. $self->select_volume($volume_idx);
  174. if ($volume_idx != -1) {
  175. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  176. my @volumes;
  177. if ($group_id != -1) {
  178. $self->select_volume($_)
  179. for grep $self->volumes->[$_]->select_group_id == $group_id,
  180. 0..$#{$self->volumes};
  181. }
  182. }
  183. $self->Refresh;
  184. }
  185. # propagate event through callback
  186. $self->on_select->($volume_idx)
  187. if $self->on_select;
  188. if ($volume_idx != -1) {
  189. if ($e->LeftDown && $self->enable_moving) {
  190. $self->_drag_volume_idx($volume_idx);
  191. $self->_drag_start_pos($self->mouse_to_3d(@$pos));
  192. } elsif ($e->RightDown) {
  193. # if right clicking on volume, propagate event through callback
  194. $self->on_right_click->($e->GetPosition)
  195. if $self->on_right_click;
  196. }
  197. }
  198. } elsif ($e->Dragging && $e->LeftIsDown && defined($self->_drag_volume_idx)) {
  199. # get new position at the same Z of the initial click point
  200. my $mouse_ray = $self->mouse_ray($e->GetX, $e->GetY);
  201. my $cur_pos = $mouse_ray->intersect_plane($self->_drag_start_pos->z);
  202. # calculate the translation vector
  203. my $vector = $self->_drag_start_pos->vector_to($cur_pos);
  204. # get volume being dragged
  205. my $volume = $self->volumes->[$self->_drag_volume_idx];
  206. # get all volumes belonging to the same group, if any
  207. my @volumes;
  208. if ($volume->drag_group_id == -1) {
  209. @volumes = ($volume);
  210. } else {
  211. @volumes = grep $_->drag_group_id == $volume->drag_group_id, @{$self->volumes};
  212. }
  213. # apply new temporary volume origin and ignore Z
  214. $_->origin->translate($vector->x, $vector->y, 0) for @volumes; #,,
  215. $self->_drag_start_pos($cur_pos);
  216. $self->_dragged(1);
  217. $self->Refresh;
  218. } elsif ($e->Dragging) {
  219. if ($e->AltDown) {
  220. # Move the camera center on the Z axis based on mouse Y axis movement
  221. if (defined $self->_drag_start_pos) {
  222. my $orig = $self->_drag_start_pos;
  223. $self->_camera_target->translate(0, 0, $pos->y - $orig->y);
  224. $self->on_viewport_changed->() if $self->on_viewport_changed;
  225. $self->Refresh;
  226. }
  227. $self->_drag_start_pos($pos);
  228. } elsif ($e->LeftIsDown) {
  229. # if dragging over blank area with left button, rotate
  230. if (defined $self->_drag_start_pos) {
  231. my $orig = $self->_drag_start_pos;
  232. if (TURNTABLE_MODE) {
  233. $self->_sphi($self->_sphi + ($pos->x - $orig->x) * TRACKBALLSIZE);
  234. $self->_stheta($self->_stheta - ($pos->y - $orig->y) * TRACKBALLSIZE); #-
  235. $self->_stheta(GIMBAL_LOCK_THETA_MAX) if $self->_stheta > GIMBAL_LOCK_THETA_MAX;
  236. $self->_stheta(0) if $self->_stheta < 0;
  237. } else {
  238. my $size = $self->GetClientSize;
  239. my @quat = trackball(
  240. $orig->x / ($size->width / 2) - 1,
  241. 1 - $orig->y / ($size->height / 2), #/
  242. $pos->x / ($size->width / 2) - 1,
  243. 1 - $pos->y / ($size->height / 2), #/
  244. );
  245. $self->_quat(mulquats($self->_quat, \@quat));
  246. }
  247. $self->on_viewport_changed->() if $self->on_viewport_changed;
  248. $self->Refresh;
  249. }
  250. $self->_drag_start_pos($pos);
  251. } elsif ($e->MiddleIsDown || $e->RightIsDown) {
  252. # if dragging over blank area with right button, translate
  253. if (defined $self->_drag_start_xy) {
  254. # get point in model space at Z = 0
  255. my $cur_pos = $self->mouse_ray($e->GetX, $e->GetY)->intersect_plane(0);
  256. my $orig = $self->mouse_ray(@{$self->_drag_start_xy})->intersect_plane(0);
  257. $self->_camera_target->translate(
  258. @{$orig->vector_to($cur_pos)->negative},
  259. );
  260. $self->on_viewport_changed->() if $self->on_viewport_changed;
  261. $self->Refresh;
  262. }
  263. $self->_drag_start_xy($pos);
  264. }
  265. } elsif ($e->LeftUp || $e->MiddleUp || $e->RightUp) {
  266. if ($self->on_move && defined($self->_drag_volume_idx) && $self->_dragged) {
  267. # get all volumes belonging to the same group, if any
  268. my @volume_idxs;
  269. my $group_id = $self->volumes->[$self->_drag_volume_idx]->drag_group_id;
  270. if ($group_id == -1) {
  271. @volume_idxs = ($self->_drag_volume_idx);
  272. } else {
  273. @volume_idxs = grep $self->volumes->[$_]->drag_group_id == $group_id,
  274. 0..$#{$self->volumes};
  275. }
  276. $self->on_move->(@volume_idxs);
  277. }
  278. $self->_drag_volume_idx(undef);
  279. $self->_drag_start_pos(undef);
  280. $self->_drag_start_xy(undef);
  281. $self->_dragged(undef);
  282. } elsif ($e->Moving) {
  283. $self->_mouse_pos($pos);
  284. $self->Refresh if $self->enable_picking;
  285. } else {
  286. $e->Skip();
  287. }
  288. }
  289. sub reset_objects {
  290. my ($self) = @_;
  291. $self->volumes([]);
  292. $self->_dirty(1);
  293. }
  294. sub set_viewport_from_scene {
  295. my ($self, $scene) = @_;
  296. $self->_sphi($scene->_sphi);
  297. $self->_stheta($scene->_stheta);
  298. $self->_camera_target($scene->_camera_target);
  299. $self->_zoom($scene->_zoom);
  300. $self->_quat($scene->_quat);
  301. $self->_dirty(1);
  302. }
  303. sub zoom{
  304. my ($self, $direction) = @_;
  305. if( $direction eq 'in'){
  306. $self->_zoom($self->_zoom / (1-0.3));
  307. }
  308. elsif($direction eq 'out'){
  309. $self->_zoom($self->_zoom / (1+0.3));
  310. }
  311. $self->on_viewport_changed->() if $self->on_viewport_changed;
  312. $self->_dirty(1);
  313. $self->Refresh;
  314. }
  315. # Set the camera to a default orientation,
  316. # zoom to volumes.
  317. sub select_view {
  318. my ($self, $direction) = @_;
  319. my $dirvec;
  320. if (ref($direction)) {
  321. $dirvec = $direction;
  322. } else {
  323. if ($direction eq 'top') {
  324. $dirvec = VIEW_TOP;
  325. } elsif ($direction eq 'bottom') {
  326. $dirvec = VIEW_BOTTOM;
  327. } elsif ($direction eq 'left') {
  328. $dirvec = VIEW_LEFT;
  329. } elsif ($direction eq 'right') {
  330. $dirvec = VIEW_RIGHT;
  331. } elsif ($direction eq 'front') {
  332. $dirvec = VIEW_FRONT;
  333. } elsif ($direction eq 'back') {
  334. $dirvec = VIEW_BACK;
  335. } elsif ($direction eq 'diagonal') {
  336. $dirvec = VIEW_DIAGONAL;
  337. }
  338. }
  339. $self->_sphi($dirvec->[0]);
  340. $self->_stheta($dirvec->[1]);
  341. # Avoid gimbal lock.
  342. $self->_stheta(GIMBAL_LOCK_THETA_MAX) if $self->_stheta > GIMBAL_LOCK_THETA_MAX;
  343. $self->_stheta(0) if $self->_stheta < 0;
  344. # View everything.
  345. $self->volumes_bounding_box->defined
  346. ? $self->zoom_to_volumes
  347. : $self->zoom_to_bed;
  348. $self->on_viewport_changed->() if $self->on_viewport_changed;
  349. $self->_dirty(1);
  350. $self->Refresh;
  351. }
  352. sub zoom_to_bounding_box {
  353. my ($self, $bb) = @_;
  354. # calculate the zoom factor needed to adjust viewport to
  355. # bounding box
  356. my $max_size = max(@{$bb->size}) * 1.05;
  357. my $min_viewport_size = min($self->GetSizeWH);
  358. if ($max_size != 0) {
  359. # only re-zoom if we have a valid bounding box, avoid a divide by 0 error.
  360. $self->_zoom($min_viewport_size / $max_size);
  361. # center view around bounding box center
  362. $self->_camera_target($bb->center);
  363. $self->on_viewport_changed->() if $self->on_viewport_changed;
  364. }
  365. }
  366. sub zoom_to_bed {
  367. my ($self) = @_;
  368. if ($self->bed_shape) {
  369. $self->zoom_to_bounding_box($self->bed_bounding_box);
  370. }
  371. }
  372. sub zoom_to_volume {
  373. my ($self, $volume_idx) = @_;
  374. my $volume = $self->volumes->[$volume_idx];
  375. my $bb = $volume->transformed_bounding_box;
  376. $self->zoom_to_bounding_box($bb);
  377. }
  378. sub zoom_to_volumes {
  379. my ($self) = @_;
  380. $self->zoom_to_bounding_box($self->volumes_bounding_box);
  381. }
  382. sub volumes_bounding_box {
  383. my ($self) = @_;
  384. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  385. $bb->merge($_->transformed_bounding_box) for @{$self->volumes};
  386. return $bb;
  387. }
  388. sub bed_bounding_box {
  389. my ($self) = @_;
  390. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  391. if ($self->bed_shape) {
  392. $bb->merge_point(Slic3r::Pointf3->new(@$_, 0)) for @{$self->bed_shape};
  393. }
  394. return $bb;
  395. }
  396. sub max_bounding_box {
  397. my ($self) = @_;
  398. my $bb = $self->bed_bounding_box;
  399. $bb->merge($self->volumes_bounding_box);
  400. return $bb;
  401. }
  402. sub set_auto_bed_shape {
  403. my ($self, $bed_shape) = @_;
  404. # draw a default square bed around object center
  405. my $max_size = max(@{ $self->volumes_bounding_box->size });
  406. my $center = $self->volumes_bounding_box->center;
  407. $self->set_bed_shape([
  408. [ $center->x - $max_size, $center->y - $max_size ], #--
  409. [ $center->x + $max_size, $center->y - $max_size ], #--
  410. [ $center->x + $max_size, $center->y + $max_size ], #++
  411. [ $center->x - $max_size, $center->y + $max_size ], #++
  412. ]);
  413. $self->origin(Slic3r::Pointf->new(@$center[X,Y]));
  414. }
  415. sub set_bed_shape {
  416. my ($self, $bed_shape) = @_;
  417. $self->bed_shape($bed_shape);
  418. # triangulate bed
  419. my $expolygon = Slic3r::ExPolygon->new([ map [map scale($_), @$_], @$bed_shape ]);
  420. my $bed_bb = $expolygon->bounding_box;
  421. {
  422. my @points = ();
  423. foreach my $triangle (@{ $expolygon->triangulate }) {
  424. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$triangle; #))
  425. }
  426. $self->bed_triangles(OpenGL::Array->new_list(GL_FLOAT, @points));
  427. }
  428. {
  429. my @polylines = ();
  430. for (my $x = $bed_bb->x_min; $x <= $bed_bb->x_max; $x += scale 10) {
  431. push @polylines, Slic3r::Polyline->new([$x,$bed_bb->y_min], [$x,$bed_bb->y_max]);
  432. }
  433. for (my $y = $bed_bb->y_min; $y <= $bed_bb->y_max; $y += scale 10) {
  434. push @polylines, Slic3r::Polyline->new([$bed_bb->x_min,$y], [$bed_bb->x_max,$y]);
  435. }
  436. # clip with a slightly grown expolygon because our lines lay on the contours and
  437. # may get erroneously clipped
  438. my @lines = map Slic3r::Line->new(@$_[0,-1]),
  439. @{intersection_pl(\@polylines, [ @{$expolygon->offset(+scaled_epsilon)} ])};
  440. # append bed contours
  441. push @lines, map @{$_->lines}, @$expolygon;
  442. my @points = ();
  443. foreach my $line (@lines) {
  444. push @points, map {+ unscale($_->x), unscale($_->y), GROUND_Z } @$line; #))
  445. }
  446. $self->bed_grid_lines(OpenGL::Array->new_list(GL_FLOAT, @points));
  447. }
  448. $self->origin(Slic3r::Pointf->new(0,0));
  449. }
  450. sub deselect_volumes {
  451. my ($self) = @_;
  452. $_->selected(0) for @{$self->volumes};
  453. $_->selected_face(-1) for @{$self->volumes};
  454. }
  455. sub select_volume {
  456. my ($self, $volume_idx) = @_;
  457. if ($volume_idx != -1) {
  458. $self->volumes->[$volume_idx]->selected(1);
  459. $self->volumes->[$volume_idx]->selected_face($self->volumes->[$volume_idx]->hover_face);
  460. }
  461. }
  462. sub SetCuttingPlane {
  463. my ($self, $axis, $z, $expolygons) = @_;
  464. $self->cutting_plane_axis($axis);
  465. $self->cutting_plane_z($z);
  466. # grow slices in order to display them better
  467. $expolygons = offset_ex([ map @$_, @$expolygons ], scale 0.1);
  468. my $bb = $self->volumes_bounding_box;
  469. my @verts = ();
  470. foreach my $line (map @{$_->lines}, map @$_, @$expolygons) {
  471. if ($axis == X) {
  472. push @verts, (
  473. $bb->x_min + $z, unscale($line->a->x), unscale($line->a->y), #))
  474. $bb->x_min + $z, unscale($line->b->x), unscale($line->b->y), #))
  475. );
  476. } elsif ($axis == Y) {
  477. push @verts, (
  478. unscale($line->a->y), $bb->y_min + $z, unscale($line->a->x), #))
  479. unscale($line->b->y), $bb->y_min + $z, unscale($line->b->x), #))
  480. );
  481. } else {
  482. push @verts, (
  483. unscale($line->a->x), unscale($line->a->y), $z, #))
  484. unscale($line->b->x), unscale($line->b->y), $z, #))
  485. );
  486. }
  487. }
  488. $self->cut_lines_vertices(OpenGL::Array->new_list(GL_FLOAT, @verts));
  489. }
  490. # Given an axis and angle, compute quaternion.
  491. sub axis_to_quat {
  492. my ($ax, $phi) = @_;
  493. my $lena = sqrt(reduce { $a + $b } (map { $_ * $_ } @$ax));
  494. my @q = map { $_ * (1 / $lena) } @$ax;
  495. @q = map { $_ * sin($phi / 2.0) } @q;
  496. $q[$#q + 1] = cos($phi / 2.0);
  497. return @q;
  498. }
  499. # Project a point on the virtual trackball.
  500. # If it is inside the sphere, map it to the sphere, if it outside map it
  501. # to a hyperbola.
  502. sub project_to_sphere {
  503. my ($r, $x, $y) = @_;
  504. my $d = sqrt($x * $x + $y * $y);
  505. if ($d < $r * 0.70710678118654752440) { # Inside sphere
  506. return sqrt($r * $r - $d * $d);
  507. } else { # On hyperbola
  508. my $t = $r / 1.41421356237309504880;
  509. return $t * $t / $d;
  510. }
  511. }
  512. sub cross {
  513. my ($v1, $v2) = @_;
  514. return (@$v1[1] * @$v2[2] - @$v1[2] * @$v2[1],
  515. @$v1[2] * @$v2[0] - @$v1[0] * @$v2[2],
  516. @$v1[0] * @$v2[1] - @$v1[1] * @$v2[0]);
  517. }
  518. # Simulate a track-ball. Project the points onto the virtual trackball,
  519. # then figure out the axis of rotation, which is the cross product of
  520. # P1 P2 and O P1 (O is the center of the ball, 0,0,0) Note: This is a
  521. # deformed trackball-- is a trackball in the center, but is deformed
  522. # into a hyperbolic sheet of rotation away from the center.
  523. # It is assumed that the arguments to this routine are in the range
  524. # (-1.0 ... 1.0).
  525. sub trackball {
  526. my ($p1x, $p1y, $p2x, $p2y) = @_;
  527. if ($p1x == $p2x && $p1y == $p2y) {
  528. # zero rotation
  529. return (0.0, 0.0, 0.0, 1.0);
  530. }
  531. # First, figure out z-coordinates for projection of P1 and P2 to
  532. # deformed sphere
  533. my @p1 = ($p1x, $p1y, project_to_sphere(TRACKBALLSIZE, $p1x, $p1y));
  534. my @p2 = ($p2x, $p2y, project_to_sphere(TRACKBALLSIZE, $p2x, $p2y));
  535. # axis of rotation (cross product of P1 and P2)
  536. my @a = cross(\@p2, \@p1);
  537. # Figure out how much to rotate around that axis.
  538. my @d = map { $_ * $_ } (map { $p1[$_] - $p2[$_] } 0 .. $#p1);
  539. my $t = sqrt(reduce { $a + $b } @d) / (2.0 * TRACKBALLSIZE);
  540. # Avoid problems with out-of-control values...
  541. $t = 1.0 if ($t > 1.0);
  542. $t = -1.0 if ($t < -1.0);
  543. my $phi = 2.0 * asin($t);
  544. return axis_to_quat(\@a, $phi);
  545. }
  546. # Build a rotation matrix, given a quaternion rotation.
  547. sub quat_to_rotmatrix {
  548. my ($q) = @_;
  549. my @m = ();
  550. $m[0] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[2] * @$q[2]);
  551. $m[1] = 2.0 * (@$q[0] * @$q[1] - @$q[2] * @$q[3]);
  552. $m[2] = 2.0 * (@$q[2] * @$q[0] + @$q[1] * @$q[3]);
  553. $m[3] = 0.0;
  554. $m[4] = 2.0 * (@$q[0] * @$q[1] + @$q[2] * @$q[3]);
  555. $m[5] = 1.0 - 2.0 * (@$q[2] * @$q[2] + @$q[0] * @$q[0]);
  556. $m[6] = 2.0 * (@$q[1] * @$q[2] - @$q[0] * @$q[3]);
  557. $m[7] = 0.0;
  558. $m[8] = 2.0 * (@$q[2] * @$q[0] - @$q[1] * @$q[3]);
  559. $m[9] = 2.0 * (@$q[1] * @$q[2] + @$q[0] * @$q[3]);
  560. $m[10] = 1.0 - 2.0 * (@$q[1] * @$q[1] + @$q[0] * @$q[0]);
  561. $m[11] = 0.0;
  562. $m[12] = 0.0;
  563. $m[13] = 0.0;
  564. $m[14] = 0.0;
  565. $m[15] = 1.0;
  566. return @m;
  567. }
  568. sub mulquats {
  569. my ($q1, $rq) = @_;
  570. return (@$q1[3] * @$rq[0] + @$q1[0] * @$rq[3] + @$q1[1] * @$rq[2] - @$q1[2] * @$rq[1],
  571. @$q1[3] * @$rq[1] + @$q1[1] * @$rq[3] + @$q1[2] * @$rq[0] - @$q1[0] * @$rq[2],
  572. @$q1[3] * @$rq[2] + @$q1[2] * @$rq[3] + @$q1[0] * @$rq[1] - @$q1[1] * @$rq[0],
  573. @$q1[3] * @$rq[3] - @$q1[0] * @$rq[0] - @$q1[1] * @$rq[1] - @$q1[2] * @$rq[2])
  574. }
  575. sub mouse_to_3d {
  576. my ($self, $x, $y, $z) = @_;
  577. my @viewport = glGetIntegerv_p(GL_VIEWPORT); # 4 items
  578. my @mview = glGetDoublev_p(GL_MODELVIEW_MATRIX); # 16 items
  579. my @proj = glGetDoublev_p(GL_PROJECTION_MATRIX); # 16 items
  580. $y = $viewport[3] - $y;
  581. $z //= glReadPixels_p($x, $y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT);
  582. my @projected = gluUnProject_p($x, $y, $z, @mview, @proj, @viewport);
  583. return Slic3r::Pointf3->new(@projected);
  584. }
  585. sub mouse_ray {
  586. my ($self, $x, $y) = @_;
  587. return Slic3r::Linef3->new(
  588. $self->mouse_to_3d($x, $y, 0),
  589. $self->mouse_to_3d($x, $y, 1),
  590. );
  591. }
  592. sub GetContext {
  593. my ($self) = @_;
  594. if (Wx::wxVERSION >= 2.009) {
  595. return $self->{context} ||= Wx::GLContext->new($self);
  596. } else {
  597. return $self->SUPER::GetContext;
  598. }
  599. }
  600. sub SetCurrent {
  601. my ($self, $context) = @_;
  602. if (Wx::wxVERSION >= 2.009) {
  603. return $self->SUPER::SetCurrent($context);
  604. } else {
  605. return $self->SUPER::SetCurrent;
  606. }
  607. }
  608. sub Resize {
  609. my ($self, $x, $y) = @_;
  610. return unless $self->GetContext;
  611. $self->_dirty(0);
  612. $self->SetCurrent($self->GetContext);
  613. glViewport(0, 0, $x, $y);
  614. $x /= $self->_zoom;
  615. $y /= $self->_zoom;
  616. glMatrixMode(GL_PROJECTION);
  617. glLoadIdentity();
  618. my $depth = 10 * max(@{ $self->max_bounding_box->size });
  619. glOrtho(
  620. -$x/2, $x/2, -$y/2, $y/2,
  621. -$depth, 2*$depth,
  622. );
  623. glMatrixMode(GL_MODELVIEW);
  624. }
  625. sub InitGL {
  626. my $self = shift;
  627. return if $self->init;
  628. return unless $self->GetContext;
  629. $self->init(1);
  630. glClearColor(0, 0, 0, 1);
  631. glColor3f(1, 0, 0);
  632. glEnable(GL_DEPTH_TEST);
  633. glClearDepth(1.0);
  634. glDepthFunc(GL_LEQUAL);
  635. glEnable(GL_CULL_FACE);
  636. glEnable(GL_BLEND);
  637. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  638. # Set antialiasing/multisampling
  639. glDisable(GL_LINE_SMOOTH);
  640. glDisable(GL_POLYGON_SMOOTH);
  641. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  642. # ambient lighting
  643. glLightModelfv_p(GL_LIGHT_MODEL_AMBIENT, 0.1, 0.1, 0.1, 1);
  644. glEnable(GL_LIGHTING);
  645. glEnable(GL_LIGHT0);
  646. glEnable(GL_LIGHT1);
  647. # light from camera
  648. glLightfv_p(GL_LIGHT1, GL_POSITION, 1, 0, 1, 0);
  649. glLightfv_p(GL_LIGHT1, GL_SPECULAR, 0.8, 0.8, 0.8, 1);
  650. glLightfv_p(GL_LIGHT1, GL_DIFFUSE, 0.4, 0.4, 0.4, 1);
  651. # Enables Smooth Color Shading; try GL_FLAT for (lack of) fun. Default: GL_SMOOTH
  652. glShadeModel(GL_SMOOTH);
  653. glMaterialfv_p(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, 0.3, 0.3, 0.3, 1);
  654. glMaterialfv_p(GL_FRONT_AND_BACK, GL_SPECULAR, 1, 1, 1, 1);
  655. glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50);
  656. glMaterialfv_p(GL_FRONT_AND_BACK, GL_EMISSION, 0.1, 0.1, 0.1, 0.9);
  657. # A handy trick -- have surface material mirror the color.
  658. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
  659. glEnable(GL_COLOR_MATERIAL);
  660. glEnable(GL_MULTISAMPLE) if ($self->{can_multisample});
  661. }
  662. sub Render {
  663. my ($self, $dc) = @_;
  664. # prevent calling SetCurrent() when window is not shown yet
  665. return unless $self->IsShownOnScreen;
  666. return unless my $context = $self->GetContext;
  667. $self->SetCurrent($context);
  668. $self->InitGL;
  669. if($SOLID_BACKGROUNDCOLOR == 1){
  670. glClearColor(@BACKGROUND_COLOR, 0);
  671. } else {
  672. glClearColor(1, 1, 1, 1);
  673. }
  674. glClearDepth(1);
  675. glDepthFunc(GL_LESS);
  676. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  677. glMatrixMode(GL_MODELVIEW);
  678. glLoadIdentity();
  679. if (TURNTABLE_MODE) {
  680. glRotatef(-$self->_stheta, 1, 0, 0); # pitch
  681. glRotatef($self->_sphi, 0, 0, 1); # yaw
  682. } else {
  683. my @rotmat = quat_to_rotmatrix($self->quat);
  684. glMultMatrixd_p(@rotmat[0..15]);
  685. }
  686. glTranslatef(@{ $self->_camera_target->negative });
  687. # light from above
  688. glLightfv_p(GL_LIGHT0, GL_POSITION, -0.5, -0.5, 1, 0);
  689. glLightfv_p(GL_LIGHT0, GL_SPECULAR, 0.2, 0.2, 0.2, 1);
  690. glLightfv_p(GL_LIGHT0, GL_DIFFUSE, 0.5, 0.5, 0.5, 1);
  691. if ($self->enable_picking) {
  692. glDisable(GL_MULTISAMPLE) if ($self->{can_multisample});
  693. glDisable(GL_LIGHTING);
  694. $self->draw_volumes(1);
  695. glFlush();
  696. glFinish();
  697. if (my $pos = $self->_mouse_pos) {
  698. my $col = [ glReadPixels_p($pos->x, $self->GetSize->GetHeight - $pos->y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) ];
  699. my $volume_idx = $col->[0] + $col->[1]*256 + $col->[2]*256*256;
  700. $self->_hover_volume_idx(undef);
  701. $_->hover(0) for @{$self->volumes};
  702. $_->hover_face(-1) for @{$self->volumes};
  703. if ($volume_idx <= $#{$self->volumes}) {
  704. $self->_hover_volume_idx($volume_idx);
  705. $self->volumes->[$volume_idx]->hover(1);
  706. my $group_id = $self->volumes->[$volume_idx]->select_group_id;
  707. if ($group_id != -1) {
  708. $_->hover(1) for grep { $_->select_group_id == $group_id } @{$self->volumes};
  709. }
  710. $self->on_hover->($volume_idx) if $self->on_hover;
  711. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  712. glFlush();
  713. glFinish();
  714. if($self->enable_face_select){
  715. $self->draw_volumes(2, $volume_idx);
  716. my $color = [ glReadPixels_p($pos->x, $self->GetSize->GetHeight - $pos->y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) ];
  717. my $face_idx = $color->[0] + $color->[1]*256 + $color->[2]*256*256;
  718. $self->volumes->[$volume_idx]->hover_face($face_idx);
  719. }
  720. }
  721. }
  722. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  723. glFlush();
  724. glFinish();
  725. glEnable(GL_LIGHTING);
  726. }
  727. # draw fixed background
  728. if ($SOLID_BACKGROUNDCOLOR == 0 && $self->background) {
  729. glDisable(GL_LIGHTING);
  730. glPushMatrix();
  731. glLoadIdentity();
  732. glMatrixMode(GL_PROJECTION);
  733. glPushMatrix();
  734. glLoadIdentity();
  735. glBegin(GL_QUADS);
  736. glColor3f( @BOTTOM_COLOR ); # bottom color
  737. glVertex2f(-1.0,-1.0);
  738. glVertex2f(1,-1.0);
  739. glColor3f( @TOP_COLOR ); # top color
  740. glVertex2f(1, 1);
  741. glVertex2f(-1.0, 1);
  742. glEnd();
  743. glPopMatrix();
  744. glMatrixMode(GL_MODELVIEW);
  745. glPopMatrix();
  746. glEnable(GL_LIGHTING);
  747. }
  748. # draw ground and axes
  749. glDisable(GL_LIGHTING);
  750. # draw ground
  751. my $ground_z = GROUND_Z;
  752. if ($self->bed_triangles) {
  753. glDisable(GL_DEPTH_TEST);
  754. glEnable(GL_BLEND);
  755. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  756. glEnableClientState(GL_VERTEX_ARRAY);
  757. my $triangle_vertex;
  758. if (HAS_VBO) {
  759. ($triangle_vertex) =
  760. glGenBuffersARB_p(1);
  761. $self->bed_triangles->bind($triangle_vertex);
  762. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->bed_triangles, GL_STATIC_DRAW_ARB);
  763. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  764. } else {
  765. # fall back on old behavior
  766. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_triangles->ptr());
  767. }
  768. glColor4f( @GROUND_COLOR );
  769. glNormal3d(0,0,1);
  770. glDrawArrays(GL_TRIANGLES, 0, $self->bed_triangles->elements / 3);
  771. glDisableClientState(GL_VERTEX_ARRAY);
  772. # we need depth test for grid, otherwise it would disappear when looking
  773. # the object from below
  774. glEnable(GL_DEPTH_TEST);
  775. # draw grid
  776. glLineWidth(2);
  777. glEnableClientState(GL_VERTEX_ARRAY);
  778. my $grid_vertex;
  779. if (HAS_VBO) {
  780. ($grid_vertex) =
  781. glGenBuffersARB_p(1);
  782. $self->bed_grid_lines->bind($grid_vertex);
  783. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->bed_grid_lines, GL_STATIC_DRAW_ARB);
  784. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  785. } else {
  786. # fall back on old behavior
  787. glVertexPointer_c(3, GL_FLOAT, 0, $self->bed_grid_lines->ptr());
  788. }
  789. glColor4f( @GRID_COLOR );
  790. glNormal3d(0,0,1);
  791. glDrawArrays(GL_LINES, 0, $self->bed_grid_lines->elements / 3);
  792. glDisableClientState(GL_VERTEX_ARRAY);
  793. glDisable(GL_BLEND);
  794. if (HAS_VBO) {
  795. # Turn off buffer objects to let the rest of the draw code work.
  796. glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  797. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
  798. glDeleteBuffersARB_p($grid_vertex);
  799. glDeleteBuffersARB_p($triangle_vertex);
  800. }
  801. }
  802. my $volumes_bb = $self->volumes_bounding_box;
  803. {
  804. # draw axes
  805. # disable depth testing so that axes are not covered by ground
  806. glDisable(GL_DEPTH_TEST);
  807. my $origin = $self->origin;
  808. my $axis_len = max(
  809. max(@{ $self->bed_bounding_box->size }),
  810. 1.2 * max(@{ $volumes_bb->size }),
  811. );
  812. glLineWidth(2);
  813. glBegin(GL_LINES);
  814. # draw line for x axis
  815. glColor3f(1, 0, 0);
  816. glVertex3f(@$origin, $ground_z);
  817. glVertex3f($origin->x + $axis_len, $origin->y, $ground_z); #,,
  818. # draw line for y axis
  819. glColor3f(0, 1, 0);
  820. glVertex3f(@$origin, $ground_z);
  821. glVertex3f($origin->x, $origin->y + $axis_len, $ground_z); #++
  822. glEnd();
  823. # draw line for Z axis
  824. # (re-enable depth test so that axis is correctly shown when objects are behind it)
  825. glEnable(GL_DEPTH_TEST);
  826. glBegin(GL_LINES);
  827. glColor3f(0, 0, 1);
  828. glVertex3f(@$origin, $ground_z);
  829. glVertex3f(@$origin, $ground_z+$axis_len);
  830. glEnd();
  831. }
  832. glEnable(GL_LIGHTING);
  833. # draw objects
  834. $self->draw_volumes;
  835. # draw cutting plane
  836. if (defined $self->cutting_plane_z) {
  837. my $plane_z = $self->cutting_plane_z;
  838. my $bb = $volumes_bb;
  839. glDisable(GL_CULL_FACE);
  840. glDisable(GL_LIGHTING);
  841. glEnable(GL_BLEND);
  842. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  843. glBegin(GL_QUADS);
  844. glColor4f( @COLOR_CUTPLANE );
  845. if ($self->cutting_plane_axis == X) {
  846. glVertex3f($bb->x_min+$plane_z, $bb->y_min-20, $bb->z_min-20);
  847. glVertex3f($bb->x_min+$plane_z, $bb->y_max+20, $bb->z_min-20);
  848. glVertex3f($bb->x_min+$plane_z, $bb->y_max+20, $bb->z_max+20);
  849. glVertex3f($bb->x_min+$plane_z, $bb->y_min-20, $bb->z_max+20);
  850. } elsif ($self->cutting_plane_axis == Y) {
  851. glVertex3f($bb->x_min-20, $bb->y_min+$plane_z, $bb->z_min-20);
  852. glVertex3f($bb->x_max+20, $bb->y_min+$plane_z, $bb->z_min-20);
  853. glVertex3f($bb->x_max+20, $bb->y_min+$plane_z, $bb->z_max+20);
  854. glVertex3f($bb->x_min-20, $bb->y_min+$plane_z, $bb->z_max+20);
  855. } elsif ($self->cutting_plane_axis == Z) {
  856. glVertex3f($bb->x_min-20, $bb->y_min-20, $bb->z_min+$plane_z);
  857. glVertex3f($bb->x_max+20, $bb->y_min-20, $bb->z_min+$plane_z);
  858. glVertex3f($bb->x_max+20, $bb->y_max+20, $bb->z_min+$plane_z);
  859. glVertex3f($bb->x_min-20, $bb->y_max+20, $bb->z_min+$plane_z);
  860. }
  861. glEnd();
  862. glEnable(GL_CULL_FACE);
  863. glDisable(GL_BLEND);
  864. }
  865. if (defined $self->_drag_start_pos || defined $self->_drag_start_xy) {
  866. $self->draw_center_of_rotation($self->_camera_target->x, $self->_camera_target->y, $self->_camera_target->z);
  867. }
  868. glFlush();
  869. $self->SwapBuffers();
  870. # Calling glFinish has a performance penalty, but it seems to fix some OpenGL driver hang-up with extremely large scenes.
  871. glFinish();
  872. }
  873. sub draw_axes {
  874. my ($self, $x, $y, $z, $length, $width, $allways_visible) = @_;
  875. if ($allways_visible) {
  876. glDisable(GL_DEPTH_TEST);
  877. } else {
  878. glEnable(GL_DEPTH_TEST);
  879. }
  880. glLineWidth($width);
  881. glBegin(GL_LINES);
  882. # draw line for x axis
  883. glColor3f(1, 0, 0);
  884. glVertex3f($x, $y, $z);
  885. glVertex3f($x + $length, $y, $z);
  886. # draw line for y axis
  887. glColor3f(0, 1, 0);
  888. glVertex3f($x, $y, $z);
  889. glVertex3f($x, $y + $length, $z);
  890. # draw line for Z axis
  891. glColor3f(0, 0, 1);
  892. glVertex3f($x, $y, $z);
  893. glVertex3f($x, $y, $z + $length);
  894. glEnd();
  895. }
  896. sub draw_center_of_rotation {
  897. my ($self, $x, $y, $z) = @_;
  898. $self->draw_axes($x, $y, $z, 10, 1, 1);
  899. $self->draw_axes($x, $y, $z, 10, 4, 0);
  900. }
  901. sub draw_volumes {
  902. my ($self, $fakecolor, $volume_to_render) = @_;
  903. glEnable(GL_BLEND);
  904. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  905. glEnableClientState(GL_VERTEX_ARRAY);
  906. glEnableClientState(GL_NORMAL_ARRAY);
  907. my $upper = $volume_to_render // $#{$self->volumes};
  908. my $lower = $volume_to_render // 0;
  909. foreach my $volume_idx ($lower..$upper) {
  910. my $volume = $self->volumes->[$volume_idx];
  911. glPushMatrix();
  912. glTranslatef(@{$volume->origin});
  913. my @baseColor;
  914. if ($fakecolor) {
  915. my $r = ($volume_idx & 0x000000FF) >> 0;
  916. my $g = ($volume_idx & 0x0000FF00) >> 8;
  917. my $b = ($volume_idx & 0x00FF0000) >> 16;
  918. @baseColor = ($r/255.0, $g/255.0, $b/255.0, 1);
  919. } elsif ($self->enable_face_select){
  920. @baseColor = @{ $volume->color };
  921. } elsif ($volume->selected) {
  922. @baseColor = @SELECTED_COLOR;
  923. push(@baseColor, $volume->color->[3]);
  924. } elsif ($volume->hover) {
  925. @baseColor = @HOVER_COLOR;
  926. push(@baseColor, $volume->color->[3]);
  927. } else {
  928. @baseColor = @{ $volume->color };
  929. }
  930. my @sorted_z = ();
  931. my ($min_z, $max_z);
  932. if ($volume->range && $volume->offsets) {
  933. @sorted_z = sort { $a <=> $b } keys %{$volume->offsets};
  934. ($min_z, $max_z) = @{$volume->range};
  935. $min_z = first { $_ >= $min_z } @sorted_z;
  936. $max_z = first { $_ > $max_z } @sorted_z;
  937. }
  938. glCullFace(GL_BACK);
  939. if ($volume->qverts) {
  940. my ($min_offset, $max_offset);
  941. if (defined $min_z) {
  942. $min_offset = $volume->offsets->{$min_z}->[0];
  943. }
  944. if (defined $max_z) {
  945. $max_offset = $volume->offsets->{$max_z}->[0];
  946. }
  947. $min_offset //= 0;
  948. $max_offset //= $volume->qverts->size;
  949. glColor4f(@baseColor);
  950. glVertexPointer_c(3, GL_FLOAT, 0, $volume->qverts->verts_ptr);
  951. glNormalPointer_c(GL_FLOAT, 0, $volume->qverts->norms_ptr);
  952. glDrawArrays(GL_QUADS, $min_offset / 3, ($max_offset-$min_offset) / 3);
  953. }
  954. if ($volume->tverts) {
  955. my ($min_offset, $max_offset);
  956. if (defined $min_z) {
  957. $min_offset = $volume->offsets->{$min_z}->[1];
  958. }
  959. if (defined $max_z) {
  960. $max_offset = $volume->offsets->{$max_z}->[1];
  961. }
  962. $min_offset //= 0;
  963. $max_offset //= $volume->tverts->size;
  964. if($fakecolor && $fakecolor == 2){
  965. our @_cached_colors;
  966. our $_cached_ptr;
  967. my $pLen = @_cached_colors;
  968. my $toAdd = max($max_offset/3*4 - $pLen, 0);
  969. if($toAdd){
  970. # TODO: move this into CPP to reduce memory consumption and decrease time when new models are added
  971. my @colors = (@baseColor)x($toAdd);
  972. for my $i (0 .. ($#colors/12)){
  973. my $r = (($i+($pLen/12)) & 0x000000FF) >> 0;
  974. my $g = (($i+($pLen/12)) & 0x0000FF00) >> 8;
  975. my $b = (($i+($pLen/12)) & 0x00FF0000) >> 16;
  976. $colors[$i*4*3 + 0] = $r / 255.0;
  977. $colors[$i*4*3 + 1] = $g / 255.0;
  978. $colors[$i*4*3 + 2] = $b / 255.0;
  979. $colors[$i*4*3 + 3] = 1.0;
  980. $colors[$i*4*3 + 4] = $r / 255.0;
  981. $colors[$i*4*3 + 5] = $g / 255.0;
  982. $colors[$i*4*3 + 6] = $b / 255.0;
  983. $colors[$i*4*3 + 7] = 1.0;
  984. $colors[$i*4*3 + 8] = $r / 255.0;
  985. $colors[$i*4*3 + 9] = $g / 255.0;
  986. $colors[$i*4*3 + 10] = $b / 255.0;
  987. $colors[$i*4*3 + 11] = 1.0;
  988. }
  989. push(@_cached_colors, @colors);
  990. $_cached_ptr = OpenGL::Array->new_list(GL_FLOAT,@_cached_colors);
  991. }
  992. glEnableClientState(GL_COLOR_ARRAY);
  993. glColorPointer_c(4, GL_FLOAT, 0, $_cached_ptr->ptr());
  994. glVertexPointer_c(3, GL_FLOAT, 0, $volume->tverts->verts_ptr);
  995. glNormalPointer_c(GL_FLOAT, 0, $volume->tverts->norms_ptr);
  996. glDrawArrays(GL_TRIANGLES, $min_offset / 3, ($max_offset-$min_offset) / 3);
  997. glDisableClientState(GL_COLOR_ARRAY);
  998. } else {
  999. glVertexPointer_c(3, GL_FLOAT, 0, $volume->tverts->verts_ptr);
  1000. glNormalPointer_c(GL_FLOAT, 0, $volume->tverts->norms_ptr);
  1001. if ( (not $fakecolor) && $volume->selected && $volume->selected_face != -1 && $volume->selected_face <= $max_offset/3){
  1002. my $i = $volume->selected_face;
  1003. glColor4f(@SELECTED_COLOR,$volume->color->[3]);
  1004. glDrawArrays(GL_TRIANGLES, $i*3, 3);
  1005. }
  1006. if ( (not $fakecolor) && $volume->hover && $volume->hover_face != -1 && $volume->hover_face <= $max_offset/3){
  1007. my $i = $volume->hover_face;
  1008. glColor4f(@HOVER_COLOR,$volume->color->[3]);
  1009. glDrawArrays(GL_TRIANGLES, $i*3, 3);
  1010. }
  1011. glColor4f(@baseColor);
  1012. glDrawArrays(GL_TRIANGLES, $min_offset / 3, ($max_offset-$min_offset) / 3);
  1013. }
  1014. }
  1015. glPopMatrix();
  1016. }
  1017. glDisableClientState(GL_NORMAL_ARRAY);
  1018. glDisable(GL_BLEND);
  1019. my $cut_vertex;
  1020. if (defined $self->cutting_plane_z) {
  1021. if (HAS_VBO) {
  1022. # Use Vertex Buffer Object for cutting plane (previous method crashes on modern POGL).
  1023. ($cut_vertex) = glGenBuffersARB_p(1);
  1024. $self->cut_lines_vertices->bind($cut_vertex);
  1025. glBufferDataARB_p(GL_ARRAY_BUFFER_ARB, $self->cut_lines_vertices, GL_STATIC_DRAW_ARB);
  1026. glVertexPointer_c(3, GL_FLOAT, 0, 0);
  1027. } else {
  1028. # Use legacy method.
  1029. glVertexPointer_c(3, GL_FLOAT, 0, $self->cut_lines_vertices->ptr());
  1030. }
  1031. glLineWidth(2);
  1032. glColor3f(0, 0, 0);
  1033. glDrawArrays(GL_LINES, 0, $self->cut_lines_vertices->elements / 3);
  1034. if (HAS_VBO) {
  1035. # Turn off buffer objects to let the rest of the draw code work.
  1036. glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  1037. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
  1038. glDeleteBuffersARB_p($cut_vertex);
  1039. }
  1040. }
  1041. glDisableClientState(GL_VERTEX_ARRAY);
  1042. }
  1043. sub calculate_normal {
  1044. my $self = shift;
  1045. my ($volume_idx) = @_;
  1046. return undef if $volume_idx == -1;
  1047. my $volume = $self->volumes->[$volume_idx];
  1048. my $max_offset = $volume->tverts->size; # For now just assume this TODO: add the other checks
  1049. if ($volume->selected && $volume->selected_face != -1 && $volume->selected_face <= $max_offset/3){
  1050. my $i = $volume->selected_face;
  1051. my $p1 = $volume->tverts->get_point($i*3);
  1052. my $p2 = $volume->tverts->get_point($i*3+1);
  1053. my $p3 = $volume->tverts->get_point($i*3+2);
  1054. my $v1 = $p1->vector_to($p2);
  1055. my $v2 = $p1->vector_to($p3);
  1056. # Calculate the cross product
  1057. my $x = $v1->y() * $v2->z() - $v1->z() * $v2->y();
  1058. my $y = $v1->z() * $v2->x() - $v1->x() * $v2->z();
  1059. my $z = $v1->x() * $v2->y() - $v1->y() * $v2->x();
  1060. # Normalize it
  1061. my $d = sqrt($x*$x + $y*$y + $z*$z);
  1062. return Slic3r::Pointf3->new($x/$d,$y/$d,$z/$d);
  1063. }
  1064. return undef;
  1065. }
  1066. package Slic3r::GUI::3DScene::Volume;
  1067. use Moo;
  1068. has 'bounding_box' => (is => 'ro', required => 1);
  1069. has 'origin' => (is => 'rw', default => sub { Slic3r::Pointf3->new(0,0,0) });
  1070. has 'color' => (is => 'ro', required => 1);
  1071. has 'select_group_id' => (is => 'rw', default => sub { -1 });
  1072. has 'drag_group_id' => (is => 'rw', default => sub { -1 });
  1073. has 'selected' => (is => 'rw', default => sub { 0 });
  1074. has 'selected_face' => (is => 'rw', default => sub { -1 });
  1075. has 'hover' => (is => 'rw', default => sub { 0 });
  1076. has 'hover_face' => (is => 'rw', default => sub { -1 });
  1077. has 'range' => (is => 'rw');
  1078. # geometric data
  1079. has 'qverts' => (is => 'rw'); # GLVertexArray object
  1080. has 'tverts' => (is => 'rw'); # GLVertexArray object
  1081. has 'mesh' => (is => 'rw'); # only required for cut contours
  1082. has 'offsets' => (is => 'rw'); # [ z => [ qverts_idx, tverts_idx ] ]
  1083. sub transformed_bounding_box {
  1084. my ($self) = @_;
  1085. my $bb = $self->bounding_box;
  1086. $bb->translate(@{$self->origin});
  1087. return $bb;
  1088. }
  1089. package Slic3r::GUI::3DScene;
  1090. use base qw(Slic3r::GUI::3DScene::Base);
  1091. use OpenGL qw(:glconstants :gluconstants :glufunctions);
  1092. use List::Util qw(first min max);
  1093. use Slic3r::Geometry qw(scale unscale epsilon);
  1094. use Slic3r::Print::State ':steps';
  1095. use Slic3r::GUI::ColorScheme;
  1096. __PACKAGE__->mk_accessors(qw(
  1097. colors
  1098. color_by
  1099. color_toolpaths_by
  1100. select_by
  1101. drag_by
  1102. volumes_by_object
  1103. _objects_by_volumes
  1104. ));
  1105. sub default_colors { [@COLOR_PARTS], [@COLOR_INFILL], [@COLOR_SUPPORT], [@COLOR_UNKNOWN] }
  1106. sub new {
  1107. my $class = shift;
  1108. my $self = $class->SUPER::new(@_);
  1109. if ( ( defined $Slic3r::GUI::Settings->{_}{colorscheme} ) && ( Slic3r::GUI::ColorScheme->can($Slic3r::GUI::Settings->{_}{colorscheme}) ) ) {
  1110. my $myGetSchemeName = \&{"Slic3r::GUI::ColorScheme::$Slic3r::GUI::Settings->{_}{colorscheme}"};
  1111. $myGetSchemeName->();
  1112. } else {
  1113. Slic3r::GUI::ColorScheme->getDefault();
  1114. }
  1115. $self->colors([ $self->default_colors ]);
  1116. $self->color_by('volume'); # object | volume
  1117. $self->color_toolpaths_by('role'); # role | extruder
  1118. $self->select_by('object'); # object | volume | instance
  1119. $self->drag_by('instance'); # object | instance
  1120. $self->volumes_by_object({}); # obj_idx => [ volume_idx, volume_idx ... ]
  1121. $self->_objects_by_volumes({}); # volume_idx => [ obj_idx, instance_idx ]
  1122. return $self;
  1123. }
  1124. sub load_object {
  1125. my ($self, $model, $obj_idx, $instance_idxs) = @_;
  1126. my $model_object;
  1127. if ($model->isa('Slic3r::Model::Object')) {
  1128. $model_object = $model;
  1129. $model = $model_object->model;
  1130. $obj_idx = 0;
  1131. } else {
  1132. $model_object = $model->get_object($obj_idx);
  1133. }
  1134. $instance_idxs ||= [0..$#{$model_object->instances}];
  1135. my @volumes_idx = ();
  1136. foreach my $volume_idx (0..$#{$model_object->volumes}) {
  1137. my $volume = $model_object->volumes->[$volume_idx];
  1138. foreach my $instance_idx (@$instance_idxs) {
  1139. my $instance = $model_object->instances->[$instance_idx];
  1140. my $mesh = $volume->mesh->clone;
  1141. $instance->transform_mesh($mesh);
  1142. my $color_idx;
  1143. if ($self->color_by eq 'volume') {
  1144. $color_idx = $volume_idx;
  1145. } elsif ($self->color_by eq 'object') {
  1146. $color_idx = $obj_idx;
  1147. }
  1148. my $color = [ @{$self->colors->[ $color_idx % scalar(@{$self->colors}) ]} ];
  1149. $color->[3] = $volume->modifier ? 0.5 : 1;
  1150. push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
  1151. bounding_box => $mesh->bounding_box,
  1152. color => $color,
  1153. );
  1154. if ($self->select_by eq 'object') {
  1155. $v->select_group_id($obj_idx*1000000);
  1156. } elsif ($self->select_by eq 'volume') {
  1157. $v->select_group_id($obj_idx*1000000 + $volume_idx*1000);
  1158. } elsif ($self->select_by eq 'instance') {
  1159. $v->select_group_id($obj_idx*1000000 + $volume_idx*1000 + $instance_idx);
  1160. }
  1161. if ($self->drag_by eq 'object') {
  1162. $v->drag_group_id($obj_idx*1000);
  1163. } elsif ($self->drag_by eq 'instance') {
  1164. $v->drag_group_id($obj_idx*1000 + $instance_idx);
  1165. }
  1166. push @volumes_idx, my $scene_volume_idx = $#{$self->volumes};
  1167. $self->_objects_by_volumes->{$scene_volume_idx} = [ $obj_idx, $volume_idx, $instance_idx ];
  1168. my $verts = Slic3r::GUI::_3DScene::GLVertexArray->new;
  1169. $verts->load_mesh($mesh);
  1170. $v->tverts($verts);
  1171. }
  1172. }
  1173. $self->volumes_by_object->{$obj_idx} = [@volumes_idx];
  1174. return @volumes_idx;
  1175. }
  1176. sub load_print_object_slices {
  1177. my ($self, $object) = @_;
  1178. my @verts = ();
  1179. my @norms = ();
  1180. my @quad_verts = ();
  1181. my @quad_norms = ();
  1182. foreach my $layer (@{$object->layers}) {
  1183. my $gap = 0;
  1184. my $top_z = $layer->print_z;
  1185. my $bottom_z = $layer->print_z - $layer->height + $gap;
  1186. foreach my $copy (@{ $object->_shifted_copies }) {
  1187. {
  1188. my @expolygons = map $_->clone, @{$layer->slices};
  1189. $_->translate(@$copy) for @expolygons;
  1190. $self->_expolygons_to_verts(\@expolygons, $layer->print_z, \@verts, \@norms);
  1191. }
  1192. foreach my $slice (@{$layer->slices}) {
  1193. foreach my $polygon (@$slice) {
  1194. foreach my $line (@{$polygon->lines}) {
  1195. $line->translate(@$copy);
  1196. push @quad_norms, (0,0,-1), (0,0,-1);
  1197. push @quad_verts, (map unscale($_), @{$line->a}), $bottom_z;
  1198. push @quad_verts, (map unscale($_), @{$line->b}), $bottom_z;
  1199. push @quad_norms, (0,0,1), (0,0,1);
  1200. push @quad_verts, (map unscale($_), @{$line->b}), $top_z;
  1201. push @quad_verts, (map unscale($_), @{$line->a}), $top_z;
  1202. # We'll use this for the middle normal when using 4 quads:
  1203. #my $xy_normal = $line->normal;
  1204. #$_xynormal->scale(1/$line->length);
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. my $obb = $object->bounding_box;
  1211. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1212. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$obb->min_point}, 0));
  1213. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$obb->max_point}, $object->size->z));
  1214. push @{$self->volumes}, my $v = Slic3r::GUI::3DScene::Volume->new(
  1215. bounding_box => $bb,
  1216. color => $self->colors->[0],
  1217. verts => OpenGL::Array->new_list(GL_FLOAT, @verts),
  1218. norms => OpenGL::Array->new_list(GL_FLOAT, @norms),
  1219. quad_verts => OpenGL::Array->new_list(GL_FLOAT, @quad_verts),
  1220. quad_norms => OpenGL::Array->new_list(GL_FLOAT, @quad_norms),
  1221. );
  1222. }
  1223. sub load_print_toolpaths {
  1224. my ($self, $print) = @_;
  1225. return if !$print->step_done(STEP_SKIRT);
  1226. return if !$print->step_done(STEP_BRIM);
  1227. return if !$print->has_skirt
  1228. && $print->config->brim_width == 0
  1229. && $print->config->interior_brim_width == 0
  1230. && $print->config->brim_connections_width == 0;
  1231. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1232. {
  1233. my $pbb = $print->bounding_box;
  1234. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->min_point}));
  1235. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$pbb->max_point}));
  1236. }
  1237. my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
  1238. if (!$print->brim->empty) {
  1239. my $color = $color_by_extruder
  1240. ? $self->colors->[ ($print->brim_extruder-1) % @{$self->colors} ]
  1241. : $self->colors->[2];
  1242. push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
  1243. bounding_box => $bb,
  1244. color => $color,
  1245. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1246. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1247. offsets => {}, # print_z => [ qverts, tverts ]
  1248. );
  1249. my $top_z = $print->get_object(0)->get_layer(0)->print_z;
  1250. $volume->offsets->{$top_z} = [0, 0];
  1251. $self->_extrusionentity_to_verts($print->brim, $top_z, Slic3r::Point->new(0,0),
  1252. $volume->qverts, $volume->tverts);
  1253. }
  1254. if (!$print->skirt->empty) {
  1255. # TODO: it's a bit difficult to predict skirt extruders with the current skirt logic.
  1256. # We need to rewrite it anyway.
  1257. my $color = +($self->default_colors)[0];
  1258. push @{$self->volumes}, my $volume = Slic3r::GUI::3DScene::Volume->new(
  1259. bounding_box => $bb,
  1260. color => $color,
  1261. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1262. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1263. offsets => {}, # print_z => [ qverts, tverts ]
  1264. );
  1265. my $skirt_height = 0; # number of layers
  1266. if ($print->has_infinite_skirt) {
  1267. $skirt_height = $print->total_layer_count;
  1268. } else {
  1269. $skirt_height = min($print->config->skirt_height, $print->total_layer_count);
  1270. }
  1271. $skirt_height ||= 1 if $print->config->brim_width > 0 || $print->config->interior_brim_width;
  1272. # get first $skirt_height layers (maybe this should be moved to a PrintObject method?)
  1273. my $object0 = $print->get_object(0);
  1274. my @layers = ();
  1275. push @layers, map $object0->get_layer($_-1), 1..min($skirt_height, $object0->layer_count);
  1276. push @layers, map $object0->get_support_layer($_-1), 1..min($skirt_height, $object0->support_layer_count);
  1277. @layers = sort { $a->print_z <=> $b->print_z } @layers;
  1278. @layers = @layers[0..($skirt_height-1)];
  1279. foreach my $i (0..($skirt_height-1)) {
  1280. my $top_z = $layers[$i]->print_z;
  1281. $volume->offsets->{$top_z} = [$volume->qverts->size, $volume->tverts->size];
  1282. $self->_extrusionentity_to_verts($print->skirt, $top_z, Slic3r::Point->new(0,0),
  1283. $volume->qverts, $volume->tverts);
  1284. }
  1285. }
  1286. }
  1287. sub load_print_object_toolpaths {
  1288. my ($self, $object) = @_;
  1289. # order layers by print_z
  1290. my @layers = sort { $a->print_z <=> $b->print_z }
  1291. @{$object->layers}, @{$object->support_layers};
  1292. # Bounding box of the object and its copies.
  1293. my $bb = Slic3r::Geometry::BoundingBoxf3->new;
  1294. {
  1295. my $obb = $object->bounding_box;
  1296. foreach my $copy (@{ $object->_shifted_copies }) {
  1297. my $cbb = $obb->clone;
  1298. $cbb->translate(@$copy);
  1299. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$cbb->min_point}, 0));
  1300. $bb->merge_point(Slic3r::Pointf3->new_unscale(@{$cbb->max_point}, $object->size->z));
  1301. }
  1302. }
  1303. my %volumes = (); # color => Volume
  1304. # Maximum size of an allocation block: 32MB / sizeof(float)
  1305. my $alloc_size_max = 32 * 1048576 / 4;
  1306. my $add = sub {
  1307. my ($coll, $top_z, $copy, $color) = @_;
  1308. my $volume = $volumes{$color};
  1309. if (!$volume) {
  1310. push @{$self->volumes}, $volumes{$color} = $volume = Slic3r::GUI::3DScene::Volume->new(
  1311. bounding_box => $bb,
  1312. color => $color,
  1313. qverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1314. tverts => Slic3r::GUI::_3DScene::GLVertexArray->new,
  1315. offsets => {}, # print_z => [ qverts, tverts ]
  1316. );
  1317. }
  1318. $volume->offsets->{$top_z} //= [ $volume->qverts->size, $volume->tverts->size ];
  1319. $self->_extrusionentity_to_verts($coll, $top_z, $copy, $volume->qverts, $volume->tverts);
  1320. };
  1321. my $color_by_extruder = $self->color_toolpaths_by eq 'extruder';
  1322. foreach my $layer (@layers) {
  1323. my $top_z = $layer->print_z;
  1324. foreach my $copy (@{ $object->_shifted_copies }) {
  1325. foreach my $layerm (@{$layer->regions}) {
  1326. if ($object->step_done(STEP_PERIMETERS)) {
  1327. my $color = $color_by_extruder
  1328. ? $self->colors->[ ($layerm->region->config->perimeter_extruder-1) % @{$self->colors} ]
  1329. : $self->colors->[0];
  1330. $add->($layerm->perimeters, $top_z, $copy, $color);
  1331. }
  1332. if ($object->step_done(STEP_INFILL)) {
  1333. my $color = $color_by_extruder
  1334. ? $self->colors->[ ($layerm->region->config->infill_extruder-1) % @{$self->colors} ]
  1335. : $self->colors->[1];
  1336. if ($color_by_extruder && $layerm->region->config->infill_extruder != $layerm->region->config->solid_infill_extruder) {
  1337. # divide solid and non-solid infill
  1338. my $solid = Slic3r::ExtrusionPath::Collection->new;
  1339. my $non_solid = Slic3r::ExtrusionPath::Collection->new;
  1340. foreach my $fill (@{$layerm->fills}) {
  1341. if ($fill->[0]->is_solid_infill) {
  1342. $solid->append($fill);
  1343. } else {
  1344. $non_solid->append($fill);
  1345. }
  1346. }
  1347. $add->($non_solid, $top_z, $copy, $color);
  1348. $color = $self->colors->[ ($layerm->region->config->solid_infill_extruder-1) % @{$self->colors} ];
  1349. $add->($solid, $top_z, $copy, $color);
  1350. } else {
  1351. $add->($layerm->fills, $top_z, $copy, $color);
  1352. }
  1353. }
  1354. }
  1355. if ($layer->isa('Slic3r::Layer::Support') && $object->step_done(STEP_SUPPORTMATERIAL)) {
  1356. {
  1357. my $color = $color_by_extruder
  1358. ? $self->colors->[ ($layer->object->config->support_material_extruder-1) % @{$self->colors} ]
  1359. : $self->colors->[2];
  1360. $add->($layer->support_fills, $top_z, $copy, $color);
  1361. }
  1362. {
  1363. my $color = ($color_by_extruder)
  1364. ? $self->colors->[ ($layer->object->config->support_material_interface_extruder-1) % @{$self->colors} ]
  1365. : $self->colors->[2];
  1366. $add->($layer->support_interface_fills, $top_z, $copy, $color);
  1367. }
  1368. }
  1369. }
  1370. foreach my $color (keys %volumes) {
  1371. my $volume = $volumes{$color};
  1372. if ($volume->qverts->size() > $alloc_size_max || $volume->tverts->size() > $alloc_size_max) {
  1373. # stop appending to this volume; create a new one next time
  1374. delete $volumes{$color};
  1375. }
  1376. }
  1377. }
  1378. }
  1379. sub set_toolpaths_range {
  1380. my ($self, $min_z, $max_z) = @_;
  1381. foreach my $volume (@{$self->volumes}) {
  1382. $volume->range([ $min_z, $max_z ]);
  1383. }
  1384. }
  1385. sub _expolygons_to_verts {
  1386. my ($self, $expolygons, $z, $verts, $norms) = @_;
  1387. my $tess = gluNewTess();
  1388. gluTessCallback($tess, GLU_TESS_BEGIN, 'DEFAULT');
  1389. gluTessCallback($tess, GLU_TESS_END, 'DEFAULT');
  1390. gluTessCallback($tess, GLU_TESS_VERTEX, sub {
  1391. my ($x, $y, $z) = @_;
  1392. push @$verts, $x, $y, $z;
  1393. push @$norms, (0,0,1), (0,0,1), (0,0,1);
  1394. });
  1395. gluTessCallback($tess, GLU_TESS_COMBINE, 'DEFAULT');
  1396. gluTessCallback($tess, GLU_TESS_ERROR, 'DEFAULT');
  1397. gluTessCallback($tess, GLU_TESS_EDGE_FLAG, 'DEFAULT');
  1398. foreach my $expolygon (@$expolygons) {
  1399. gluTessBeginPolygon($tess);
  1400. foreach my $polygon (@$expolygon) {
  1401. gluTessBeginContour($tess);
  1402. gluTessVertex_p($tess, (map unscale($_), @$_), $z) for @$polygon;
  1403. gluTessEndContour($tess);
  1404. }
  1405. gluTessEndPolygon($tess);
  1406. }
  1407. gluDeleteTess($tess);
  1408. }
  1409. # Fill in the $qverts and $tverts with quads and triangles
  1410. # for the extrusion $entity.
  1411. sub _extrusionentity_to_verts {
  1412. my ($self, $entity, $top_z, $copy, $qverts, $tverts) = @_;
  1413. my ($lines, $widths, $heights, $closed);
  1414. if ($entity->isa('Slic3r::ExtrusionPath::Collection')) {
  1415. $self->_extrusionentity_to_verts($_, $top_z, $copy, $qverts, $tverts)
  1416. for @$entity;
  1417. return;
  1418. } elsif ($entity->isa('Slic3r::ExtrusionPath')) {
  1419. my $polyline = $entity->polyline->clone;
  1420. $polyline->remove_duplicate_points;
  1421. $polyline->translate(@$copy);
  1422. $lines = $polyline->lines;
  1423. $widths = [ map $entity->width, 0..$#$lines ];
  1424. $heights = [ map $entity->height, 0..$#$lines ];
  1425. $closed = 0;
  1426. } else {
  1427. $lines = [];
  1428. $widths = [];
  1429. $heights = [];
  1430. $closed = 1;
  1431. foreach my $path (@$entity) {
  1432. my $polyline = $path->polyline->clone;
  1433. $polyline->remove_duplicate_points;
  1434. $polyline->translate(@$copy);
  1435. my $path_lines = $polyline->lines;
  1436. push @$lines, @$path_lines;
  1437. push @$widths, map $path->width, 0..$#$path_lines;
  1438. push @$heights, map $path->height, 0..$#$path_lines;
  1439. }
  1440. }
  1441. # Calling the C++ implementation Slic3r::_3DScene::_extrusionentity_to_verts_do()
  1442. # This adds new vertices to the $qverts and $tverts.
  1443. Slic3r::GUI::_3DScene::_extrusionentity_to_verts_do($lines, $widths, $heights,
  1444. $closed,
  1445. # Top height of the extrusion.
  1446. $top_z,
  1447. # $copy is not used here.
  1448. $copy,
  1449. # GLVertexArray object: C++ class maintaining an std::vector<float> for coords and normals.
  1450. $qverts,
  1451. $tverts);
  1452. }
  1453. sub object_idx {
  1454. my ($self, $volume_idx) = @_;
  1455. return $self->_objects_by_volumes->{$volume_idx}[0];
  1456. }
  1457. sub volume_idx {
  1458. my ($self, $volume_idx) = @_;
  1459. return $self->_objects_by_volumes->{$volume_idx}[1];
  1460. }
  1461. sub instance_idx {
  1462. my ($self, $volume_idx) = @_;
  1463. return $self->_objects_by_volumes->{$volume_idx}[2];
  1464. }
  1465. 1;