KiCad PCB EDA Suite
Loading...
Searching...
No Matches
eda_3d_canvas.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2015-2016 Mario Luzeiro <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <kicad_gl/kiglu.h> // Must be included first
22#include <kicad_gl/gl_utils.h>
24
25#include <wx/tokenzr.h>
26
27#include <fmt/format.h>
28
29#include <api/api_utils.h>
30#include <api/common/commands/cross_probe_commands.pb.h>
31
33#include "eda_3d_canvas.h"
34
35#include <optional>
36
37#include <3d_math.h>
39#include <glm/gtc/type_ptr.hpp>
41#include <eda_3d_viewer_frame.h>
44#include <3d_viewer_id.h>
45#include <advanced_config.h>
46#include <math/util.h>
47#include <build_version.h>
49#include <board.h>
50#include <footprint.h>
51#include <pad.h>
52#include <pcb_field.h>
53#include <pcb_track.h>
54#include <reporter.h>
55#include <widgets/wx_infobar.h>
56#include <core/profile.h> // To use GetRunningMicroSecs or another profiling utility
57#include <bitmaps.h>
58#include <kiway_holder.h>
59#include <kiway.h>
60#include <macros.h>
61#include <pgm_base.h>
64#include <string_utils.h>
65#include <mail_type.h>
66#include <kiway_mail.h>
68#include <zone.h>
69#include <chrono>
70#include <cmath>
71#include <limits>
72#include <ratio>
73
74
82const wxChar* EDA_3D_CANVAS::m_logTrace = wxT( "KI_TRACE_EDA_3D_CANVAS" );
83
84
85// A custom event, used to call DoRePaint during an idle time
86wxDEFINE_EVENT( wxEVT_REFRESH_CUSTOM_COMMAND, wxCommandEvent );
87
88
89BEGIN_EVENT_TABLE( EDA_3D_CANVAS, HIDPI_GL_3D_CANVAS )
90 EVT_PAINT( EDA_3D_CANVAS::OnPaint )
91
92 // mouse events
93 EVT_LEFT_DOWN( EDA_3D_CANVAS::OnLeftDown )
94 EVT_LEFT_UP( EDA_3D_CANVAS::OnLeftUp )
95 EVT_MIDDLE_UP( EDA_3D_CANVAS::OnMiddleUp )
96 EVT_MIDDLE_DOWN( EDA_3D_CANVAS::OnMiddleDown)
97 EVT_RIGHT_DOWN( EDA_3D_CANVAS::OnRightDown )
98 EVT_RIGHT_UP( EDA_3D_CANVAS::OnRightUp )
99 EVT_MOUSEWHEEL( EDA_3D_CANVAS::OnMouseWheel )
100 EVT_MOTION( EDA_3D_CANVAS::OnMouseMove )
101 EVT_LEAVE_WINDOW( EDA_3D_CANVAS::OnMouseLeave )
102 EVT_MAGNIFY( EDA_3D_CANVAS::OnMagnify )
103
104 // touch gesture events
105 EVT_GESTURE_ZOOM( wxID_ANY, EDA_3D_CANVAS::OnZoomGesture )
106 EVT_GESTURE_PAN( wxID_ANY, EDA_3D_CANVAS::OnPanGesture )
107 EVT_GESTURE_ROTATE( wxID_ANY, EDA_3D_CANVAS::OnRotateGesture )
108
109 // other events
110 EVT_ERASE_BACKGROUND( EDA_3D_CANVAS::OnEraseBackground )
111 EVT_CUSTOM(wxEVT_REFRESH_CUSTOM_COMMAND, ID_CUSTOM_EVENT_1, EDA_3D_CANVAS::OnRefreshRequest )
112
114 EVT_SIZE( EDA_3D_CANVAS::OnResize )
115END_EVENT_TABLE()
116
117
118EDA_3D_CANVAS::EDA_3D_CANVAS( wxWindow* aParent, const wxGLAttributes& aGLAttribs,
119 BOARD_ADAPTER& aBoardAdapter, CAMERA& aCamera,
120 S3D_CACHE* a3DCachePointer ) :
121 HIDPI_GL_3D_CANVAS( EDA_DRAW_PANEL_GAL::GetVcSettings(), aCamera, aParent, aGLAttribs,
122 EDA_3D_CANVAS_ID, wxDefaultPosition,
123 wxDefaultSize, wxFULL_REPAINT_ON_RESIZE ),
124 m_editing_timeout_timer( this, wxID_HIGHEST + 1 ),
125 m_redraw_trigger_timer( this, wxID_HIGHEST + 2 ),
126 m_boardAdapter( aBoardAdapter )
127{
128 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::EDA_3D_CANVAS" ) );
129
130 m_editing_timeout_timer.SetOwner( this );
131 Connect( m_editing_timeout_timer.GetId(), wxEVT_TIMER,
132 wxTimerEventHandler( EDA_3D_CANVAS::OnTimerTimeout_Editing ), nullptr, this );
133
134 m_redraw_trigger_timer.SetOwner( this );
135 Connect( m_redraw_trigger_timer.GetId(), wxEVT_TIMER,
136 wxTimerEventHandler( EDA_3D_CANVAS::OnTimerTimeout_Redraw ), nullptr, this );
137
139
140 m_3d_render_raytracing = std::make_unique<RENDER_3D_RAYTRACE_GL>( this, m_boardAdapter, m_camera );
141 m_3d_render_opengl = std::make_unique<RENDER_3D_OPENGL>( this, m_boardAdapter, m_camera );
142
143 auto busy_indicator_factory =
144 []()
145 {
146 return std::make_unique<WX_BUSY_INDICATOR>();
147 };
148
149 m_3d_render_raytracing->SetBusyIndicatorFactory( busy_indicator_factory );
150 m_3d_render_opengl->SetBusyIndicatorFactory( busy_indicator_factory );
151
152 // We always start with the opengl engine (raytracing is avoided due to very
153 // long calculation time)
155
156 m_boardAdapter.ReloadColorSettings();
157
158 wxASSERT( a3DCachePointer != nullptr );
159 m_boardAdapter.Set3dCacheManager( a3DCachePointer );
160
161#if defined( __WXMSW__ )
162 EnableTouchEvents( wxTOUCH_ZOOM_GESTURE | wxTOUCH_ROTATE_GESTURE | wxTOUCH_PAN_GESTURES );
163#elif defined( __WXGTK__ )
164 EnableTouchEvents( wxTOUCH_ZOOM_GESTURE | wxTOUCH_ROTATE_GESTURE );
165#endif
166
167 const wxEventType events[] =
168 {
169 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
170 // especially special key like arrow keys, are handled by the GAL event dispatcher,
171 // and not sent to GUI without filtering, because they have a default action (scroll)
172 // that must not be called.
173 wxEVT_LEFT_UP, wxEVT_LEFT_DOWN, wxEVT_LEFT_DCLICK,
174 wxEVT_RIGHT_UP, wxEVT_RIGHT_DOWN, wxEVT_RIGHT_DCLICK,
175 wxEVT_MIDDLE_UP, wxEVT_MIDDLE_DOWN, wxEVT_MIDDLE_DCLICK,
176 wxEVT_MOTION, wxEVT_MOUSEWHEEL, wxEVT_CHAR, wxEVT_CHAR_HOOK,
177 wxEVT_MAGNIFY,
178 wxEVT_MENU_OPEN, wxEVT_MENU_CLOSE, wxEVT_MENU_HIGHLIGHT
179 };
180
181 for( wxEventType eventType : events )
182 Connect( eventType, wxEventHandler( EDA_3D_CANVAS::OnEvent ), nullptr, m_eventDispatcher );
183}
184
185
187{
188 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::~EDA_3D_CANVAS" ) );
189
190 // Detach UI reporters before joining/destroying renderers that may still report.
192 m_activityReporterSync->SetNullReporter();
193
195 m_warningReporterSync->SetNullReporter();
196
198 m_accelerator3DShapes = nullptr;
199
201}
202
203
205{
206 // Join the bg worker before taking the GL lock or destroying renderers. The worker
207 // may still be in ReloadRaytracingForHitTesting() and must not outlive either renderer.
209 m_3d_render_opengl->StopBgWorker();
210
211 if( m_glRC )
212 {
214 wxASSERT( gl_mgr );
215
216 if( gl_mgr )
217 {
218 // wxGTK destroys the native window before this runs, and our context cannot be
219 // made current without it. The renderers then have to come down without GL
220 std::optional<ORPHANED_GL_OBJECTS> orphaned;
221
222 if( !gl_mgr->LockCtx( m_glRC, this ) )
223 orphaned.emplace();
224
225 m_3d_render = nullptr;
226
227 // OpenGL dtor joins the bg worker; reset it before raytracing.
228 m_3d_render_opengl.reset();
230
231 gl_mgr->UnlockCtx( m_glRC );
232 gl_mgr->DestroyCtx( m_glRC );
233 }
234
235 m_glRC = nullptr;
236 }
237}
238
239
240void EDA_3D_CANVAS::OnCloseWindow( wxCloseEvent& event )
241{
243
244 event.Skip();
245}
246
247
248void EDA_3D_CANVAS::OnResize( wxSizeEvent& event )
249{
251}
252
253
255{
256 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::initializeOpenGL" ) );
257
259
260 const int glVersion = gladLoaderLoadGL();
261
262 if( glVersion == 0 )
263 {
264 wxLogMessage( wxT( "Failed to load OpenGL via loader" ) );
265
266 return false;
267 }
268 else
269 {
270 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::initializeOpenGL Using OpenGL version %s" ),
271 From_UTF8( (char*) glGetString( GL_VERSION ) ) );
272 }
273
274 SetOpenGLInfo( (const char*) glGetString( GL_VENDOR ), (const char*) glGetString( GL_RENDERER ),
275 (const char*) glGetString( GL_VERSION ) );
276
277 wxString version = From_UTF8( (char *) glGetString( GL_VERSION ) );
278
279 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL version string %s." ),
280 __WXFUNCTION__, version );
281
282 // Extract OpenGL version from string. This method is used because prior to OpenGL 2,
283 // getting the OpenGL major and minor version as integers didn't exist.
284 wxString tmp;
285
286 wxStringTokenizer tokenizer( version, " \t\r\n" );
287
288 if( tokenizer.HasMoreTokens() )
289 {
290 long major = 0;
291 long minor = 0;
292
293 tmp = tokenizer.GetNextToken();
294
295 tokenizer.SetString( tmp, wxString( wxT( "." ) ) );
296
297 if( tokenizer.HasMoreTokens() )
298 tokenizer.GetNextToken().ToLong( &major );
299
300 if( tokenizer.HasMoreTokens() )
301 tokenizer.GetNextToken().ToLong( &minor );
302
303 if( major < 2 || ( ( major == 2 ) && ( minor < 1 ) ) )
304 {
305 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL ray tracing not supported." ),
306 __WXFUNCTION__ );
307
308 if( GetParent() )
309 {
310 wxCommandEvent evt( wxEVT_MENU, ID_DISABLE_RAY_TRACING );
311 GetParent()->ProcessWindowEvent( evt );
312 }
313
315 }
316
317 if( ( major == 1 ) && ( minor < 5 ) )
318 {
319 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL not supported." ),
320 __WXFUNCTION__ );
321
323 }
324 }
325
326#if wxCHECK_VERSION( 3, 3, 3 )
327 wxGLCanvas::SetSwapInterval( -1 );
328#else
329 GL_UTILS::SetSwapInterval( this, -1 );
330#endif
331
333
334 return true;
335}
336
337
338void EDA_3D_CANVAS::GetScreenshot( wxImage& aDstImage )
339{
340 OglGetScreenshot( aDstImage );
341}
342
343
345{
346 if( m_3d_render )
347 m_3d_render->JoinBgWorker();
348}
349
350
351void EDA_3D_CANVAS::ReloadRequest( BOARD* aBoard , S3D_CACHE* aCachePointer )
352{
354 m_3d_render_opengl->StopBgWorker();
355
356 if( aCachePointer != nullptr )
357 m_boardAdapter.Set3dCacheManager( aCachePointer );
358
359 if( aBoard != nullptr )
360 m_boardAdapter.SetBoard( aBoard );
361
362 m_boardAdapter.ReloadColorSettings();
363
364 m_currentRollOverItem = nullptr;
365
367 m_3d_render_opengl->SetCurrentRollOverItem( nullptr );
368
369 if( m_3d_render )
370 m_3d_render->ReloadRequest();
371}
372
373
375{
377 m_3d_render_raytracing->Reload( true, aStop );
378}
379
380
386
387
389{
391
392 if( m_3d_render )
393 m_3d_render->ReloadRequest();
394
396
398}
399
400
402{
404 {
405 wxString msg;
406
407 msg.Printf( wxT( "dx %3.2f" ), m_camera.GetCameraPos().x );
408 m_parentStatusBar->SetStatusText( msg, static_cast<int>( EDA_3D_VIEWER_STATUSBAR::X_POS ) );
409
410 msg.Printf( wxT( "dy %3.2f" ), m_camera.GetCameraPos().y );
411 m_parentStatusBar->SetStatusText( msg, static_cast<int>( EDA_3D_VIEWER_STATUSBAR::Y_POS ) );
412
413 msg.Printf( wxT( "zoom %3.2f" ), 1 / m_camera.GetZoom() );
414 m_parentStatusBar->SetStatusText( msg,
415 static_cast<int>( EDA_3D_VIEWER_STATUSBAR::ZOOM_LEVEL ) );
416 }
417}
418
419
420void EDA_3D_CANVAS::OnPaint( wxPaintEvent& aEvent )
421{
422 // Please have a look at: https://lists.launchpad.net/kicad-developers/msg25149.html
423 DoRePaint();
424}
425
426
428{
429 if( m_is_currently_painting.test_and_set() )
430 return;
431
432 // SwapBuffer requires the window to be shown before calling
433 if( !IsShownOnScreen() )
434 {
435 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::DoRePaint !IsShown" ) );
437 return;
438 }
439
440 // Because the board to draw is handled by the parent viewer frame,
441 // ensure this parent is still alive. When it is closed before the viewer
442 // frame, a paint event can be generated after the parent is closed,
443 // therefore with invalid board.
444 // This is dependent of the platform.
445 // Especially on OSX, but also on Windows, it frequently happens
446 wxWindow* viewer = wxGetTopLevelParent( this );
447 wxWindow* owner = viewer ? viewer->GetParent() : nullptr;
448
449 if( owner && !owner->IsShownOnScreen() )
450 {
452 return; // The parent board editor frame is no more alive
453 }
454
456 {
457 m_statusBarReporter = std::make_unique<STATUSBAR_REPORTER>( m_parentStatusBar,
459 m_infoBarReporter = std::make_unique<INFOBAR_REPORTER>( m_parentInfoBar );
460
461 m_activityReporterSync = std::make_shared<SYNC_REPORTER>( *m_statusBarReporter );
462 m_warningReporterSync = std::make_shared<SYNC_REPORTER>( *m_infoBarReporter );
463
466
469 }
470
471 wxString err_messages;
472 auto start_time = std::chrono::steady_clock::now();
474
475 if( !gl_mgr )
476 {
478 return;
479 }
480
481 // "Makes the OpenGL state that is represented by the OpenGL rendering
482 // context context current, i.e. it will be used by all subsequent OpenGL calls.
483 // This function may only be called when the window is shown on screen"
484
485 // Explicitly create a new rendering context instance for this canvas.
486 if( m_glRC == nullptr )
487 m_glRC = gl_mgr->CreateCtx( this );
488
489 // CreateCtx could and does fail per sentry crash events, lets be graceful
490 if( m_glRC == nullptr )
491 {
492 m_warningReporterSync->Report( _( "OpenGL context creation error" ), RPT_SEVERITY_ERROR );
493 m_warningReporterSync->Finalize();
495 return;
496 }
497
498 gl_mgr->LockCtx( m_glRC, this );
499
500 // Set the OpenGL viewport according to the client size of this canvas.
501 // This is done here rather than in a wxSizeEvent handler because our
502 // OpenGL rendering context (and thus viewport setting) is used with
503 // multiple canvases: If we updated the viewport in the wxSizeEvent
504 // handler, changing the size of one canvas causes a viewport setting that
505 // is wrong when next another canvas is repainted.
506 wxSize clientSize = GetNativePixelSize();
507
508 const bool windows_size_changed = m_camera.SetCurWindowSize( clientSize );
509
510 // Initialize openGL if need
512 {
513 if( !initializeOpenGL() )
514 {
515 gl_mgr->UnlockCtx( m_glRC );
517
518 return;
519 }
520
522 {
523 m_warningReporterSync->Report( _( "Your OpenGL version is not supported. Minimum required is 1.5." ),
525
526 m_warningReporterSync->Finalize();
527 }
528 }
529
531 {
532 glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
533 glClear( GL_COLOR_BUFFER_BIT );
534
535 SwapBuffers();
536
537 gl_mgr->UnlockCtx( m_glRC );
539
540 return;
541 }
542
543 // Don't attempt to ray trace if OpenGL doesn't support it.
545 {
548
549 if( m_boardAdapter.m_Cfg )
550 m_boardAdapter.m_Cfg->m_Render.engine = RENDER_ENGINE::OPENGL;
551 }
552
553 // Check if a raytracing was requested and need to switch to raytracing mode
554 if( !m_boardAdapter.m_Cfg || m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
555 {
556 const bool was_camera_changed = m_camera.ParametersChanged();
557
558 // It reverts back to OpenGL mode if it was requested a raytracing
559 // render of the current scene. AND the mouse / camera is moving
560 if( ( m_mouse_is_moving || m_camera_is_moving || was_camera_changed || windows_size_changed )
562 {
565 }
566 }
567
568 float curtime_delta_s = 0.0f;
569
571 {
572 const int64_t curtime_delta = GetRunningMicroSecs() - m_strtime_camera_movement;
573 // Convert microseconds to seconds as float and apply speed multiplier
574 curtime_delta_s = static_cast<float>( static_cast<double>( curtime_delta ) / 1e6 ) * m_camera_moving_speed;
575 m_camera.Interpolate( curtime_delta_s );
576
577 if( curtime_delta_s > 1.0f )
578 {
579 m_render_pivot = false;
580 m_camera_is_moving = false;
581 m_mouse_was_moved = true;
582
585 }
586 else
587 {
589 }
590 }
591
592 // It will return true if the render request a new redraw
593 bool requested_redraw = false;
594
595 if( m_3d_render )
596 {
597 try
598 {
599 m_3d_render->SetCurWindowSize( clientSize );
600
601 requested_redraw = m_3d_render->Redraw( m_mouse_was_moved || m_camera_is_moving );
602 }
603 catch( std::runtime_error& )
604 {
608 gl_mgr->UnlockCtx( m_glRC );
610 return;
611 }
612 }
613
615
616 if( m_render_pivot )
617 {
618 const float scale = glm::min( m_camera.GetZoom(), 1.0f );
619 render_pivot( curtime_delta_s, scale );
620 }
621
622 // This will only be enabled by the 3d mouse plugin, so we can leave
623 // it as a simple if statement
625 {
626 const float scale = glm::min( m_camera.GetZoom(), 1.0f );
628 }
629
630 // "Swaps the double-buffer of this window, making the back-buffer the
631 // front-buffer and vice versa, so that the output of the previous OpenGL
632 // commands is displayed on the window."
633 SwapBuffers();
634
635 gl_mgr->UnlockCtx( m_glRC );
636
637 // Calculation time in milliseconds
638 const double calculation_time =
639 std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now() - start_time ).count();
640
642 {
643 m_parentStatusBar->SetStatusText( wxString::Format( _( "Last render time %.0f ms" ), calculation_time ),
645 }
646
647 // This will reset the flag of camera parameters changed
648 m_camera.ParametersChanged();
649
651 m_warningReporterSync->Finalize();
652
653 if( !err_messages.IsEmpty() )
654 wxLogMessage( err_messages );
655
656 if( ( !m_camera_is_moving ) && requested_redraw )
657 {
658 m_mouse_was_moved = false;
659 Request_refresh( false );
660 }
661
662 static constexpr std::array<VIEW3D_TYPE, static_cast<int>( SPHERES_GIZMO::GizmoSphereSelection::Count )>
665
666 SPHERES_GIZMO::GizmoSphereSelection selectedGizmoSphere = m_3d_render_opengl->getSelectedGizmoSphere();
667 int index = static_cast<int>( selectedGizmoSphere );
668 if( index >= 0 && index < static_cast<int>( viewTable.size() ) )
669 {
670 SetView3D( viewTable[index] );
671 }
672
673 m_3d_render_opengl->resetSelectedGizmoSphere();
674
676}
677
678
679void EDA_3D_CANVAS::RenderToFrameBuffer( unsigned char* buffer, int width, int height )
680{
681 if( m_is_currently_painting.test_and_set() )
682 return;
683
684 // Validate input parameters
685 if( !buffer || width <= 0 || height <= 0 )
686 {
688 return;
689 }
690
691 // Because the board to draw is handled by the parent viewer frame,
692 // ensure this parent is still alive
693 if( !GetParent() || !GetParent()->GetParent() || !GetParent()->GetParent()->IsShownOnScreen() )
694 {
696 return;
697 }
698
699 wxString err_messages;
700 int64_t start_time = GetRunningMicroSecs();
702
703 if( !gl_mgr )
704 {
706 return;
707 }
708
709 // Create OpenGL context if needed
710 if( m_glRC == nullptr )
711 m_glRC = gl_mgr->CreateCtx( this );
712
713 if( m_glRC == nullptr )
714 {
715 wxLogError( _( "OpenGL context creation error" ) );
717 return;
718 }
719
720 gl_mgr->LockCtx( m_glRC, this );
721
722 // Set up framebuffer objects for off-screen rendering
723 GLuint framebuffer = 0;
724 GLuint colorTexture = 0;
725 GLuint depthStencilBuffer = 0;
726 GLint oldFramebuffer = 0;
727 GLint oldViewport[4];
728
729 // Save current state
730 glGetIntegerv( GL_FRAMEBUFFER_BINDING, &oldFramebuffer );
731 glGetIntegerv( GL_VIEWPORT, oldViewport );
732
733 // Create and bind framebuffer
734 glGenFramebuffers( 1, &framebuffer );
735 glBindFramebuffer( GL_FRAMEBUFFER, framebuffer );
736
737 // Create color texture attachment
738 glGenTextures( 1, &colorTexture );
739 glBindTexture( GL_TEXTURE_2D, colorTexture );
740 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr );
741 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
742 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
743 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
744 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
745 glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0 );
746
747 // Create combined depth+stencil renderbuffer attachment. The stencil buffer is required
748 // because the OpenGL renderer uses stencil operations to cut holes in copper layers and
749 // the board body (see OPENGL_RENDER_LIST::DrawCulled).
750 glGenRenderbuffers( 1, &depthStencilBuffer );
751 glBindRenderbuffer( GL_RENDERBUFFER, depthStencilBuffer );
752 glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height );
753 glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER,
754 depthStencilBuffer );
755
756 auto resetState =
757 std::unique_ptr<void, std::function<void(void*)>>( reinterpret_cast<void*>(1),
758 [&](void*)
759 {
760 glBindFramebuffer( GL_FRAMEBUFFER, oldFramebuffer );
761 glViewport( oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3] );
762 glDeleteFramebuffers( 1, &framebuffer );
763 glDeleteTextures( 1, &colorTexture );
764 glDeleteRenderbuffers( 1, &depthStencilBuffer );
765 gl_mgr->UnlockCtx( m_glRC );
767 } );
768
769 // Check framebuffer completeness
770 GLenum framebufferStatus = glCheckFramebufferStatus( GL_FRAMEBUFFER );
771
772 if( framebufferStatus != GL_FRAMEBUFFER_COMPLETE )
773 {
774 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::RenderToFrameBuffer Framebuffer incomplete: 0x%04X" ),
775 framebufferStatus );
776
777 return;
778 }
779
780 // Set viewport for off-screen rendering
781 glViewport( 0, 0, width, height );
782
783 // Set window size for camera and rendering
784 wxSize clientSize( width, height );
785 const bool windows_size_changed = m_camera.SetCurWindowSize( clientSize );
786
787 // Initialize OpenGL if needed
789 {
790 if( !initializeOpenGL() )
791 {
792 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::RenderToFrameBuffer OpenGL initialization failed." ) );
793 return;
794 }
795
797 {
798 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::RenderToFrameBuffer OpenGL version not supported." ) );
799 }
800 }
801
803 {
804 glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
805 glClear( GL_COLOR_BUFFER_BIT );
806
807 // Read black screen to buffer
808 glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
809 return;
810 }
811
812 // Handle raytracing/OpenGL renderer selection
814 {
817 m_boardAdapter.m_Cfg->m_Render.engine = RENDER_ENGINE::OPENGL;
818 }
819
820 if( m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
821 {
822 const bool was_camera_changed = m_camera.ParametersChanged();
823
824 if( ( m_mouse_is_moving || m_camera_is_moving || was_camera_changed || windows_size_changed )
826 {
829 }
830 }
831
832 // Handle camera animation (simplified for off-screen rendering)
833 float curtime_delta_s = 0.0f;
835 {
836 const int64_t curtime_delta = GetRunningMicroSecs() - m_strtime_camera_movement;
837 curtime_delta_s = static_cast<float>( static_cast<double>( curtime_delta ) / 1e6 )
839 m_camera.Interpolate( curtime_delta_s );
840
841 if( curtime_delta_s > 1.0f )
842 {
843 m_render_pivot = false;
844 m_camera_is_moving = false;
845 m_mouse_was_moved = true;
846 }
847 }
848
849 // Perform the actual rendering. The first redraw may start background loading;
850 // wait for it to finish and redraw once more before reading pixels.
851 if( m_3d_render )
852 {
853 try
854 {
855 m_3d_render->SetCurWindowSize( clientSize );
856 m_3d_render->Redraw( false );
857
858 if( m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
859 {
860 m_3d_render->JoinBgWorker();
861 m_3d_render->Redraw( false );
862 }
863 }
864 catch( std::runtime_error& )
865 {
869 return;
870 }
871 }
872
873 glFinish();
874
875 // Read pixels from framebuffer to the provided buffer
876 glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
877
878 // Check for OpenGL errors
879 GLenum error = glGetError();
880 if( error != GL_NO_ERROR )
881 {
882 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::RenderToFrameBuffer OpenGL error: 0x%04X" ), error );
883 err_messages += wxString::Format( _( "OpenGL error during off-screen rendering: 0x%04X\n" ), error );
884 }
885
886 // Reset camera parameters changed flag
887 m_camera.ParametersChanged();
888
889 if( !err_messages.IsEmpty() )
890 wxLogMessage( err_messages );
891}
892
893
895{
896 m_eventDispatcher = aEventDispatcher;
897}
898
899
900void EDA_3D_CANVAS::OnEvent( wxEvent& aEvent )
901{
902 if( !m_eventDispatcher )
903 aEvent.Skip();
904 else
905 m_eventDispatcher->DispatchWxEvent( aEvent );
906
907 Refresh();
908}
909
910
911void EDA_3D_CANVAS::OnEraseBackground( wxEraseEvent& event )
912{
913 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::OnEraseBackground" ) );
914 // Do nothing, to avoid flashing.
915}
916
917
918void EDA_3D_CANVAS::OnMouseWheel( wxMouseEvent& event )
919{
920 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::OnMouseWheel" ) );
921
922 OnMouseWheelCamera( event, m_boardAdapter.m_MousewheelPanning );
923
925 {
929 }
930}
931
932
933void EDA_3D_CANVAS::OnMagnify( wxMouseEvent& event )
934{
935 SetFocus();
936
938 return;
939
940 //m_is_moving_mouse = true;
942
943 float magnification = ( event.GetMagnification() + 1.0f );
944
945 m_camera.Zoom( magnification );
946
949}
950
951
952void EDA_3D_CANVAS::OnZoomGesture( wxZoomGestureEvent& aEvent )
953{
954 SetFocus();
955
956 if( aEvent.IsGestureStart() )
957 {
959 m_camera.SetCurMousePosition( aEvent.GetPosition() );
960 }
961
963 return;
964
966
967 m_camera.Pan( aEvent.GetPosition() );
968 m_camera.SetCurMousePosition( aEvent.GetPosition() );
969
970 m_camera.Zoom( static_cast<float>( aEvent.GetZoomFactor() / m_gestureLastZoomFactor ) );
971
972 m_gestureLastZoomFactor = aEvent.GetZoomFactor();
973
976}
977
978
979void EDA_3D_CANVAS::OnPanGesture( wxPanGestureEvent& aEvent )
980{
981 SetFocus();
982
983 if( aEvent.IsGestureStart() )
984 m_camera.SetCurMousePosition( aEvent.GetPosition() );
985
987 return;
988
989 m_camera.Pan( aEvent.GetPosition() );
990 m_camera.SetCurMousePosition( aEvent.GetPosition() );
991
994}
995
996
997void EDA_3D_CANVAS::OnRotateGesture( wxRotateGestureEvent& aEvent )
998{
999 SetFocus();
1000
1001 if( aEvent.IsGestureStart() )
1002 {
1004 m_camera.SetCurMousePosition( aEvent.GetPosition() );
1005
1006 // We don't want to process the first angle
1007 return;
1008 }
1009
1010 if( m_camera_is_moving )
1011 return;
1012
1013 m_camera.RotateScreen( static_cast<float>( m_gestureLastAngle - aEvent.GetRotationAngle() ) );
1014 m_gestureLastAngle = aEvent.GetRotationAngle();
1015
1016 DisplayStatus();
1018}
1019
1020
1021void EDA_3D_CANVAS::OnMouseMove( wxMouseEvent& event )
1022{
1023 if( m_3d_render && m_3d_render->IsReloadRequestPending() )
1024 return; // Prevents using invalid m_3d_render_raytracing data
1025
1026 if( m_camera_is_moving )
1027 return;
1028
1029 OnMouseMoveCamera( event );
1030
1031 if( m_mouse_was_moved )
1032 {
1033 DisplayStatus();
1035 // *Do not* reactivate the timer here during the mouse move command:
1036 // OnMiddleUp() will do it at the end of mouse drag/move command
1037 }
1038
1039 // A pick handler owns the cursor: report the hover to it instead of rolling over board items.
1040 if( m_hoverHandler )
1041 {
1042 if( !event.Dragging() )
1044
1045 return;
1046 }
1047
1048 if( !event.Dragging() && m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
1049 {
1051 RAY mouseRay = getRayAtCurrentMousePosition();
1052 BOARD_ITEM* rollOverItem = m_3d_render_raytracing->IntersectBoardItem( mouseRay );
1053
1054 auto printNetInfo =
1055 []( BOARD_CONNECTED_ITEM* aItem )
1056 {
1057 return wxString::Format( _( "Net %s\tNet class %s" ),
1058 aItem->GetNet()->GetNetname(),
1059 aItem->GetNet()->GetNetClass()->GetHumanReadableName() );
1060 };
1061
1062 if( rollOverItem )
1063 {
1064 wxString msg;
1065
1066 if( rollOverItem != m_currentRollOverItem )
1067 {
1068 m_3d_render_opengl->SetCurrentRollOverItem( rollOverItem );
1069 m_currentRollOverItem = rollOverItem;
1070
1072 }
1073
1074 switch( rollOverItem->Type() )
1075 {
1076 case PCB_PAD_T:
1077 {
1078 PAD* pad = static_cast<PAD*>( rollOverItem );
1079
1080 if( !pad->GetNumber().IsEmpty() )
1081 msg += wxString::Format( _( "Pad %s\t" ), pad->GetNumber() );
1082
1083 if( pad->IsOnCopperLayer() )
1084 msg += printNetInfo( pad );
1085
1086 break;
1087 }
1088
1089 case PCB_FOOTPRINT_T:
1090 {
1091 FOOTPRINT* footprint = static_cast<FOOTPRINT*>( rollOverItem );
1092 msg += footprint->GetReference() + wxT( " " ) + footprint->GetValue();
1093 break;
1094 }
1095
1096 case PCB_TRACE_T:
1097 case PCB_VIA_T:
1098 case PCB_ARC_T:
1099 {
1100 PCB_TRACK* track = static_cast<PCB_TRACK*>( rollOverItem );
1101 msg += printNetInfo( track );
1102 break;
1103 }
1104
1105 case PCB_ZONE_T:
1106 {
1107 ZONE* zone = static_cast<ZONE*>( rollOverItem );
1108
1109 if( !zone->GetZoneName().IsEmpty() )
1110 {
1111 if( zone->GetIsRuleArea() )
1112 msg += wxString::Format( _( "Rule area %s\t" ), zone->GetZoneName() );
1113 else
1114 msg += wxString::Format( _( "Zone %s\t" ), zone->GetZoneName() );
1115 }
1116
1117 if( zone->IsOnCopperLayer() )
1118 msg += printNetInfo( zone );
1119
1120 break;
1121 }
1122
1123 default:
1124 break;
1125 }
1126
1127 reporter.Report( msg );
1128 }
1129 else
1130 {
1132 && m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
1133 {
1134 m_3d_render_opengl->SetCurrentRollOverItem( nullptr );
1136
1137 reporter.Report( wxEmptyString );
1138 }
1139
1140 m_currentRollOverItem = nullptr;
1141 }
1142 }
1143}
1144
1145
1146void EDA_3D_CANVAS::OnMouseLeave( wxMouseEvent& event )
1147{
1148 if( m_hoverHandler )
1149 m_hoverHandler( std::nullopt );
1150
1151 event.Skip();
1152}
1153
1154
1155void EDA_3D_CANVAS::OnLeftDown( wxMouseEvent& event )
1156{
1157 SetFocus();
1159
1160 // Ensure m_camera.m_lastPosition (current mouse position) is up to date for
1161 // future drag events (can be not the case when left clicking after
1162 // opening a context menu)
1163 OnMouseMoveCamera( event );
1164
1165 // Selection/deselection is handled on button release in OnLeftUp, so a click-drag
1166 // used to rotate the view does not change the current selection
1167}
1168
1169
1170void EDA_3D_CANVAS::OnLeftUp( wxMouseEvent& event )
1171{
1172 if( m_camera_is_moving )
1173 return;
1174
1175 bool wasRotating = m_mouse_is_moving;
1176
1177 if( m_mouse_is_moving )
1178 {
1179 m_mouse_is_moving = false;
1181 }
1182
1183 bool gizmoClicked = false;
1184
1185 if( m_boardAdapter.m_Cfg->m_Render.show_navigator
1186 && m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
1187 {
1188 wxSize logicalSize = GetClientSize();
1189 int logicalW = logicalSize.GetWidth();
1190 int logicalH = logicalSize.GetHeight();
1191
1192 int gizmo_x = 0, gizmo_y = 0, gizmo_width = 0, gizmo_height = 0;
1193 std::tie( gizmo_x, gizmo_y, gizmo_width, gizmo_height ) = m_3d_render_opengl->getGizmoViewport();
1194
1195 float scaleX = static_cast<float>( static_cast<double>( gizmo_width ) / static_cast<double>( logicalW ) );
1196 float scaleY = static_cast<float>( static_cast<double>( gizmo_height ) / static_cast<double>( logicalH ) );
1197
1198 int scaledMouseX = static_cast<int>( static_cast<float>( event.GetX() ) * scaleX );
1199 int scaledMouseY = static_cast<int>( static_cast<float>( logicalH - event.GetY() ) * scaleY );
1200
1201 m_3d_render_opengl->handleGizmoMouseInput( scaledMouseX, scaledMouseY );
1202 m_3d_render_opengl->updateGizmoSelection( m_camera.GetRotationMatrix() );
1203
1204 gizmoClicked = m_3d_render_opengl->getSelectedGizmoSphere() != SPHERES_GIZMO::GizmoSphereSelection::None;
1205 }
1206
1207 if( !wasRotating && !gizmoClicked && m_pickHandler )
1208 {
1209 // A completed pick can clear or replace the canvas handler.
1210 auto handler = m_pickHandler;
1211
1212 if( handler( getRayAtCurrentMousePosition() ) )
1213 {
1214 Refresh();
1215 return;
1216 }
1217 }
1218
1219 // A plain click that missed the orientation gizmo: cross-probe the clicked footprint,
1220 // or clear the selection when clicking empty space. A click-drag rotation or a click
1221 // on the gizmo leaves the current selection untouched.
1222 if( !wasRotating && !gizmoClicked && m_3d_render_raytracing != nullptr )
1223 {
1224 RAY mouseRay = getRayAtCurrentMousePosition();
1225 BOARD_ITEM* intersectedBoardItem = m_3d_render_raytracing->IntersectBoardItem( mouseRay );
1226 FOOTPRINT* footprint = nullptr;
1227
1228 if( intersectedBoardItem )
1229 {
1230 switch( intersectedBoardItem->Type() )
1231 {
1232 case PCB_FOOTPRINT_T: footprint = static_cast<FOOTPRINT*>( intersectedBoardItem ); break;
1233
1234 case PCB_PAD_T: footprint = static_cast<PAD*>( intersectedBoardItem )->GetParentFootprint(); break;
1235
1236 case PCB_FIELD_T: footprint = static_cast<PCB_FIELD*>( intersectedBoardItem )->GetParentFootprint(); break;
1237
1238 default: break;
1239 }
1240 }
1241
1242 // We send a message (by ExpressMail) to the board and schematic editor, but only
1243 // if the manager of this canvas is a EDA_3D_VIEWER_FRAME, because only this
1244 // kind of frame has ExpressMail stuff
1245 if( EDA_3D_VIEWER_FRAME* frame = dynamic_cast<EDA_3D_VIEWER_FRAME*>( wxGetTopLevelParent( this ) ) )
1246 {
1247 kiapi::common::commands::SyncSelection sync;
1248
1249 if( footprint )
1250 sync.add_items()->mutable_footprint()->set_reference( footprint->GetReference().ToUTF8() );
1251
1252 sync.set_mode( kiapi::common::commands::SyncSelectionMode::SSM_ITEMS_ONLY );
1253 sync.set_context( kiapi::common::commands::SyncSelectionContext::SSC_IMPLICIT );
1254
1255 std::string payload;
1256
1257 if( kiapi::common::PackKiwayApiMessage( sync, payload ) )
1258 {
1259 frame->Kiway().ExpressMail( FRAME_PCB_EDITOR, MAIL_SELECTION, payload, frame );
1260 frame->Kiway().ExpressMail( FRAME_SCH, MAIL_SELECTION, payload, frame );
1261 }
1262 }
1263 }
1264
1265 Refresh();
1266}
1267
1268
1269void EDA_3D_CANVAS::OnRightDown( wxMouseEvent& event )
1270{
1271 SetFocus();
1273
1274 // Ensure m_camera.m_lastPosition is up to date for future drag events.
1275 OnMouseMoveCamera( event );
1276}
1277
1278
1279void EDA_3D_CANVAS::OnRightUp( wxMouseEvent& event )
1280{
1281 if( m_camera_is_moving )
1282 return;
1283
1284 if( m_mouse_is_moving )
1285 {
1286 m_mouse_is_moving = false;
1288 }
1289}
1290
1291
1292void EDA_3D_CANVAS::OnMiddleDown( wxMouseEvent& event )
1293{
1294 SetFocus();
1296}
1297
1298
1299void EDA_3D_CANVAS::OnMiddleUp( wxMouseEvent& event )
1300{
1301 if( m_camera_is_moving )
1302 return;
1303
1304 if( m_mouse_is_moving )
1305 {
1306 m_mouse_is_moving = false;
1308 }
1309 else
1310 {
1312 }
1313}
1314
1315
1316void EDA_3D_CANVAS::OnTimerTimeout_Editing( wxTimerEvent& aEvent )
1317{
1318 if( aEvent.GetId() != m_editing_timeout_timer.GetId() )
1319 {
1320 aEvent.Skip();
1321 return;
1322 }
1323
1324 m_mouse_is_moving = false;
1325 m_mouse_was_moved = false;
1326
1328}
1329
1330
1335
1336
1338{
1339 if( m_3d_render )
1340 m_editing_timeout_timer.Start( m_3d_render->GetWaitForEditingTimeOut(), wxTIMER_ONE_SHOT );
1341}
1342
1343
1344void EDA_3D_CANVAS::OnTimerTimeout_Redraw( wxTimerEvent& aEvent )
1345{
1346 if( aEvent.GetId() != m_redraw_trigger_timer.GetId() )
1347 {
1348 aEvent.Skip();
1349 return;
1350 }
1351
1352 Request_refresh( true );
1353}
1354
1355
1356void EDA_3D_CANVAS::OnRefreshRequest( wxEvent& aEvent )
1357{
1358 Refresh();
1359}
1360
1361
1362void EDA_3D_CANVAS::Request_refresh( bool aRedrawImmediately )
1363{
1364 if( aRedrawImmediately )
1365 {
1366 // Just calling Refresh() does not work always
1367 // Using an event to call DoRepaint ensure the repaint code will be executed,
1368 // and PostEvent will take priority to other events like mouse movements, keys, etc.
1369 // and is executed during the next idle time
1370 wxCommandEvent redrawEvent( wxEVT_REFRESH_CUSTOM_COMMAND, ID_CUSTOM_EVENT_1 );
1371 wxPostEvent( this, redrawEvent );
1372 }
1373 else
1374 {
1375 // Schedule a timed redraw
1376 m_redraw_trigger_timer.Start( 10 , wxTIMER_ONE_SHOT );
1377 }
1378}
1379
1380
1381void EDA_3D_CANVAS::request_start_moving_camera( float aMovingSpeed, bool aRenderPivot )
1382{
1383 wxASSERT( aMovingSpeed > FLT_EPSILON );
1384
1385 // Fast forward the animation if the animation is disabled
1386 if( !m_animation_enabled )
1387 {
1388 m_camera.Interpolate( 1.0f );
1389 DisplayStatus();
1391 return;
1392 }
1393
1394 // Map speed multiplier option to actual multiplier value
1395 // [1,2,3,4,5] -> [0.25, 0.5, 1, 2, 4]
1396 aMovingSpeed *= static_cast<float>( ( 1 << m_moving_speed_multiplier ) ) / 8.0f;
1397
1398 m_render_pivot = aRenderPivot;
1399 m_camera_moving_speed = aMovingSpeed;
1400
1402
1403 DisplayStatus();
1405
1406 m_camera_is_moving = true;
1407
1409}
1410
1411
1413{
1414 RAY mouseRay = getRayAtCurrentMousePosition();
1415
1416 float hit_t = 0.0f;
1417
1418 // Test it with the board bounding box
1419 if( m_boardAdapter.GetBBox().Intersect( mouseRay, &hit_t ) )
1420 {
1421 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1422 m_camera.SetT0_and_T1_current_T();
1423 m_camera.SetLookAtPos_T1( mouseRay.at( hit_t ) );
1424 m_camera.ResetXYpos_T1();
1425
1427 }
1428}
1429
1430
1432{
1433 if( m_camera_is_moving )
1434 return false;
1435
1436 const float delta_move = m_delta_move_step_factor * m_camera.GetZoom();
1437 const float arrow_moving_time_speed = 8.0f;
1438
1439 switch( aRequestedView )
1440 {
1443 return true;
1444
1446 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
1447 m_camera.SetT0_and_T1_current_T();
1448 m_camera.Pan_T1( SFVEC3F( -delta_move, 0.0f, 0.0f ) );
1449 request_start_moving_camera( arrow_moving_time_speed, false );
1450 return true;
1451
1453 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
1454 m_camera.SetT0_and_T1_current_T();
1455 m_camera.Pan_T1( SFVEC3F( +delta_move, 0.0f, 0.0f ) );
1456 request_start_moving_camera( arrow_moving_time_speed, false );
1457 return true;
1458
1460 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
1461 m_camera.SetT0_and_T1_current_T();
1462 m_camera.Pan_T1( SFVEC3F( 0.0f, +delta_move, 0.0f ) );
1463 request_start_moving_camera( arrow_moving_time_speed, false );
1464 return true;
1465
1467 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
1468 m_camera.SetT0_and_T1_current_T();
1469 m_camera.Pan_T1( SFVEC3F( 0.0f, -delta_move, 0.0f ) );
1470 request_start_moving_camera( arrow_moving_time_speed, false );
1471 return true;
1472
1474 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1475 m_camera.SetT0_and_T1_current_T();
1476 m_camera.Reset_T1();
1477 request_start_moving_camera( glm::min( glm::max( m_camera.GetZoom(), 1 / 1.26f ), 1.26f ) );
1478 return true;
1479
1481 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1482 m_camera.SetT0_and_T1_current_T();
1483
1484 if( m_camera.Zoom_T1( 1.26f ) ) // 3 steps per doubling
1486
1487 return true;
1488
1490 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1491 m_camera.SetT0_and_T1_current_T();
1492
1493 if( m_camera.Zoom_T1( 1/1.26f ) ) // 3 steps per halving
1495
1496 return true;
1497
1503 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1504 m_camera.SetT0_and_T1_current_T();
1505 m_camera.ViewCommand_T1( aRequestedView );
1507 return true;
1508
1511 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1512 m_camera.SetT0_and_T1_current_T();
1513 m_camera.ViewCommand_T1( aRequestedView );
1514 request_start_moving_camera( glm::min( glm::max( m_camera.GetZoom(), 0.5f ), 1.125f ) );
1515 return true;
1516
1517 default:
1518 return false;
1519 }
1520}
1521
1522
1524{
1526 {
1527 switch( cfg->m_Render.engine )
1528 {
1531 default: m_3d_render = nullptr; break;
1532 }
1533 }
1534
1535 if( m_3d_render )
1536 m_3d_render->ReloadRequest();
1537
1538 m_mouse_was_moved = false;
1539
1541}
1542
1543
1545{
1546 if( m_overlays.empty() )
1547 return;
1548
1549 glMatrixMode( GL_PROJECTION );
1550 glLoadMatrixf( glm::value_ptr( m_camera.GetProjectionMatrix() ) );
1551
1552 glMatrixMode( GL_MODELVIEW );
1553 glLoadMatrixf( glm::value_ptr( m_camera.GetViewMatrix() ) );
1554
1555 glDisable( GL_LIGHTING );
1556 glDisable( GL_CULL_FACE );
1557 glEnable( GL_COLOR_MATERIAL );
1558 glEnable( GL_BLEND );
1559 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1560 glDepthMask( GL_FALSE );
1561 glEnable( GL_POLYGON_OFFSET_FILL );
1562 glPolygonOffset( -2.0f, -2.0f );
1563
1564 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1565 glDisableClientState( GL_COLOR_ARRAY );
1566 glDisableClientState( GL_NORMAL_ARRAY );
1567 glEnableClientState( GL_VERTEX_ARRAY );
1568
1569 // The raytracer paints a textured quad and leaves no usable depth buffer.
1570 const bool depthUsable = m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL;
1571
1572 for( const OVERLAY& overlay : m_overlays )
1573 {
1574 if( overlay.vertices.empty() )
1575 continue;
1576
1577 if( depthUsable && !overlay.alwaysVisible )
1578 glEnable( GL_DEPTH_TEST );
1579 else
1580 glDisable( GL_DEPTH_TEST );
1581
1582 glPushMatrix();
1583 glMultMatrixf( glm::value_ptr( overlay.transform ) );
1584 glColor4f( overlay.color.r, overlay.color.g, overlay.color.b, overlay.color.a );
1585 glVertexPointer( 3, GL_FLOAT, 0, overlay.vertices.data() );
1586 glDrawArrays( GL_TRIANGLES, 0, (GLsizei) overlay.vertices.size() );
1587 glPopMatrix();
1588 }
1589
1590 glDisableClientState( GL_VERTEX_ARRAY );
1591 glDisable( GL_POLYGON_OFFSET_FILL );
1592 glDepthMask( GL_TRUE );
1593 glDisable( GL_BLEND );
1594 glEnable( GL_DEPTH_TEST );
1595}
1596
1597
1598std::optional<EDA_3D_CANVAS::MODEL_HIT> EDA_3D_CANVAS::PickModel(
1599 const RAY& aRay, const S3DMODEL& aGeometry, const FP_3DMODEL& aModel,
1600 const FOOTPRINT& aFootprint ) const
1601{
1602 glm::mat4 world = m_boardAdapter.GetFootprintMatrix( aFootprint ) * CalcModelMatrix(
1603 SFVEC3F( aModel.m_Offset.x, aModel.m_Offset.y, aModel.m_Offset.z ),
1604 SFVEC3F( aModel.m_Rotation.x, aModel.m_Rotation.y, aModel.m_Rotation.z ),
1605 SFVEC3F( aModel.m_Scale.x, aModel.m_Scale.y, aModel.m_Scale.z ) );
1606 const double determinant = glm::determinant( glm::dmat4( world ) );
1607
1608 if( !aGeometry.m_Meshes || !std::isfinite( determinant ) || determinant == 0.0 )
1609 return std::nullopt;
1610
1611 const glm::dmat4 inverse = glm::inverse( glm::dmat4( world ) );
1612 const glm::dvec3 origin( inverse * glm::dvec4( aRay.m_Origin, 1.0 ) );
1613 const glm::dvec3 direction( inverse * glm::dvec4( aRay.m_Dir, 0.0 ) );
1614 double nearest = std::numeric_limits<double>::infinity();
1615 std::optional<MODEL_HIT> hit;
1616
1617 for( unsigned int i = 0; i < aGeometry.m_MeshesSize; ++i )
1618 {
1619 const SMESH& mesh = aGeometry.m_Meshes[i];
1620
1621 if( !mesh.m_Positions || !mesh.m_FaceIdx )
1622 continue;
1623
1624 for( unsigned int j = 0; j + 2 < mesh.m_FaceIdxSize; j += 3 )
1625 {
1626 if( !IsTriangleInRange( mesh.m_FaceIdx, j, mesh.m_VertexSize ) )
1627 continue;
1628
1629 const glm::dvec3 a( mesh.m_Positions[mesh.m_FaceIdx[j]] );
1630 const glm::dvec3 edge1 = glm::dvec3( mesh.m_Positions[mesh.m_FaceIdx[j + 1]] ) - a;
1631 const glm::dvec3 edge2 = glm::dvec3( mesh.m_Positions[mesh.m_FaceIdx[j + 2]] ) - a;
1632 const glm::dvec3 p = glm::cross( direction, edge2 );
1633 const double det = glm::dot( edge1, p );
1634 const double tolerance = 1e-12 * glm::length( edge1 ) * glm::length( p );
1635
1636 if( !std::isfinite( det ) || std::abs( det ) <= tolerance )
1637 continue;
1638
1639 const glm::dvec3 delta = origin - a;
1640 const double u = glm::dot( delta, p ) / det;
1641 const glm::dvec3 q = glm::cross( delta, edge1 );
1642 const double v = glm::dot( direction, q ) / det;
1643 const double distance = glm::dot( edge2, q ) / det;
1644
1645 if( u >= 0.0 && v >= 0.0 && u + v <= 1.0 && distance >= 0.0 && distance < nearest )
1646 {
1647 nearest = distance;
1648 hit = MODEL_HIT{ i, j };
1649 }
1650 }
1651 }
1652
1653 return hit;
1654}
1655
1656
1657PAD* EDA_3D_CANVAS::PickFootprintPad( const RAY& aRay, const FOOTPRINT& aFootprint ) const
1658{
1659 const double units = m_boardAdapter.BiuTo3dUnits();
1660
1661 if( units <= 0.0 || std::abs( aRay.m_Dir.z ) < 1e-9 )
1662 return nullptr;
1663
1664 const double z = m_boardAdapter.GetFootprintZPos( aFootprint.IsFlipped() );
1665 const double distance = ( z - aRay.m_Origin.z ) / aRay.m_Dir.z;
1666 const double x = ( aRay.m_Origin.x + distance * aRay.m_Dir.x ) / units;
1667 const double y = -( aRay.m_Origin.y + distance * aRay.m_Dir.y ) / units;
1668
1669 if( distance < 0.0 || !std::isfinite( x ) || !std::isfinite( y )
1670 || std::abs( x ) > std::numeric_limits<int>::max()
1671 || std::abs( y ) > std::numeric_limits<int>::max() )
1672 {
1673 return nullptr;
1674 }
1675
1676 const VECTOR2I point( KiROUND( x ), KiROUND( y ) );
1677 const PCB_LAYER_ID copper = aFootprint.IsFlipped() ? B_Cu : F_Cu;
1678
1679 for( PAD* pad : aFootprint.Pads() )
1680 {
1681 if( pad->HitTest( point, 0, copper ) )
1682 return pad;
1683 }
1684
1685 return nullptr;
1686}
1687
1688
1690{
1691 SFVEC3F rayOrigin;
1692 SFVEC3F rayDir;
1693
1694 // Generate a ray origin and direction based on current mouser position and camera
1695 m_camera.MakeRayAtCurrentMousePosition( rayOrigin, rayDir );
1696
1697 RAY mouseRay;
1698 mouseRay.Init( rayOrigin, rayDir );
1699
1700 return mouseRay;
1701}
VIEW3D_TYPE
Definition 3d_enums.h:81
@ VIEW3D_ZOOM_OUT
Definition 3d_enums.h:97
@ VIEW3D_PAN_LEFT
Definition 3d_enums.h:94
@ VIEW3D_FIT_SCREEN
Definition 3d_enums.h:101
@ VIEW3D_ZOOM_IN
Definition 3d_enums.h:96
@ VIEW3D_PIVOT_CENTER
Definition 3d_enums.h:98
@ VIEW3D_BOTTOM
Definition 3d_enums.h:84
@ VIEW3D_PAN_UP
Definition 3d_enums.h:92
@ VIEW3D_PAN_DOWN
Definition 3d_enums.h:93
@ VIEW3D_PAN_RIGHT
Definition 3d_enums.h:95
glm::mat4 CalcModelMatrix(const SFVEC3F &aOffset, const SFVEC3F &aRotation, const SFVEC3F &aScale)
Build the model-to-footprint transform used by rendering and picking.
Definition 3d_math.cpp:34
Defines math related functions.
@ ID_CUSTOM_EVENT_1
@ ID_DISABLE_RAY_TRACING
int index
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
void SetOpenGLInfo(const char *aVendor, const char *aRenderer, const char *aVersion)
A setter for OpenGL info when it's initialized.
void SetOpenGLBackendInfo(wxString aBackend)
A setter for OpenGL backend info after the canvas is created.
define an internal structure to be used by the 3D renders
bool IsTriangleInRange(const unsigned int *aFaceIdx, unsigned int aTriangleIdx, unsigned int aVertexCount)
Test whether the three face indices of a triangle all reference valid vertices.
Definition c3dmodel.h:100
Helper class to handle information needed to display 3D board.
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
A class used to derive camera objects from.
Definition camera.h:94
Implement a canvas based on a wxGLCanvas.
TOOL_DISPATCHER * m_eventDispatcher
void OnEvent(wxEvent &aEvent)
Used to forward events to the canvas from popups, etc.
void OnMagnify(wxMouseEvent &event)
void restart_editingTimeOut_Timer()
Reset the editing timer.
void RenderToFrameBuffer(unsigned char *aBuffer, int aWidth, int aHeight)
BOARD_ITEM * m_currentRollOverItem
RENDER_3D_BASE * m_3d_render
Non-owning pointer to the active renderer (one of the two below).
std::function< void(const std::optional< RAY > &)> m_hoverHandler
bool m_is_opengl_initialized
void OnResize(wxSizeEvent &event)
bool m_render3dmousePivot
void OnMouseWheel(wxMouseEvent &event)
WX_INFOBAR * m_parentInfoBar
wxTimer m_editing_timeout_timer
int64_t m_strtime_camera_movement
void render_overlays()
Draw the translucent overlays over the rendered scene.
void OnLeftDown(wxMouseEvent &event)
void OnPanGesture(wxPanGestureEvent &event)
void OnRightUp(wxMouseEvent &event)
wxGLContext * m_glRC
ACCELERATOR_3D * m_accelerator3DShapes
std::function< bool(const RAY &)> m_pickHandler
void OnTimerTimeout_Redraw(wxTimerEvent &event)
wxStatusBar * m_parentStatusBar
void DoRePaint()
The actual function to repaint the canvas.
std::shared_ptr< SYNC_REPORTER > m_warningReporterSync
void OnRightDown(wxMouseEvent &event)
void InvalidateRaytracingHitTesting()
Invalidate the hover hit-test BVH before board layers are rebuilt.
int m_moving_speed_multiplier
void JoinBgWorker()
Block until any in-progress OpenGL background loading has finished.
bool m_is_opengl_version_supported
wxTimer m_redraw_trigger_timer
BOARD_ADAPTER & m_boardAdapter
void DisplayStatus()
Update the status bar with the position information.
void render3dmousePivot(float aScale)
Render the 3dmouse pivot cursor.
void OnPaint(wxPaintEvent &aEvent)
std::vector< OVERLAY > m_overlays
void RenderRaytracingRequest()
Request to render the current view in Raytracing mode.
void SetEventDispatcher(TOOL_DISPATCHER *aEventDispatcher)
Set a dispatcher that processes events and forwards them to tools.
std::optional< MODEL_HIT > PickModel(const RAY &aRay, const S3DMODEL &aGeometry, const FP_3DMODEL &aModel, const FOOTPRINT &aFootprint) const
Pick current mesh geometry; independent of the renderer's cached hit-test scene.
bool m_render_raytracing_was_requested
float m_camera_moving_speed
void ReloadRaytracingForHitTesting(std::stop_token aStop)
Rebuild the auxiliary raytracing BVH used for hover hit-testing in OpenGL mode.
PAD * PickFootprintPad(const RAY &aRay, const FOOTPRINT &aFootprint) const
Project onto the footprint's seating plane and hit-test copper pads.
void OnLeftUp(wxMouseEvent &event)
void ReloadRequest(BOARD *aBoard=nullptr, S3D_CACHE *aCachePointer=nullptr)
RAY getRayAtCurrentMousePosition()
double m_gestureLastZoomFactor
Used to track gesture events.
void OnCloseWindow(wxCloseEvent &event)
bool SetView3D(VIEW3D_TYPE aRequestedView)
Select a specific 3D view or operation.
void OnMiddleDown(wxMouseEvent &event)
void GetScreenshot(wxImage &aDstImage)
Request a screenshot and output it to the aDstImage.
std::unique_ptr< INFOBAR_REPORTER > m_infoBarReporter
void OnZoomGesture(wxZoomGestureEvent &event)
std::unique_ptr< STATUSBAR_REPORTER > m_statusBarReporter
std::unique_ptr< RENDER_3D_OPENGL > m_3d_render_opengl
void OnMiddleUp(wxMouseEvent &event)
void render_pivot(float t, float aScale)
Render the pivot cursor.
void request_start_moving_camera(float aMovingSpeed=2.0f, bool aRenderPivot=true)
Start a camera movement.
void RenderEngineChanged()
Notify that the render engine was changed.
std::shared_ptr< SYNC_REPORTER > m_activityReporterSync
void OnMouseLeave(wxMouseEvent &event)
std::atomic_flag m_is_currently_painting
void OnRefreshRequest(wxEvent &aEvent)
void OnEraseBackground(wxEraseEvent &event)
void releaseOpenGL()
Free created targets and openGL context.
std::unique_ptr< RENDER_3D_RAYTRACE_GL > m_3d_render_raytracing
void Request_refresh(bool aRedrawImmediately=true)
Schedule a refresh update of the canvas.
bool m_opengl_supports_raytracing
~EDA_3D_CANVAS() override
void OnMouseMove(wxMouseEvent &event)
void OnRotateGesture(wxRotateGestureEvent &event)
EDA_3D_CANVAS(wxWindow *aParent, const wxGLAttributes &aGLAttribs, BOARD_ADAPTER &aSettings, CAMERA &aCamera, S3D_CACHE *a3DCachePointer)
Create a new 3D Canvas with an attribute list.
void move_pivot_based_on_cur_mouse_position()
This function hits a ray to the board and start a movement.
double m_gestureLastAngle
void OnTimerTimeout_Editing(wxTimerEvent &event)
void stop_editingTimeOut_Timer()
Stop the editing time so it will not timeout.
Create and handle a window for the 3d viewer connected to a Kiway and a pcbboard.
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
std::deque< PAD * > & Pads()
Definition footprint.h:355
bool IsFlipped() const
Definition footprint.h:620
const wxString & GetValue() const
Definition footprint.h:817
const wxString & GetReference() const
Definition footprint.h:793
VECTOR3D m_Offset
3D model offset (mm)
Definition footprint.h:134
VECTOR3D m_Rotation
3D model rotation (degrees)
Definition footprint.h:133
VECTOR3D m_Scale
3D model scaling factor (dimensionless)
Definition footprint.h:132
void UnlockCtx(wxGLContext *aContext)
Allow other canvases to bind an OpenGL context.
void DestroyCtx(wxGLContext *aContext)
Destroy a managed OpenGL context.
bool LockCtx(wxGLContext *aContext, wxGLCanvas *aCanvas)
Set a context as current and prevents other canvases from switching it.
wxGLContext * CreateCtx(wxGLCanvas *aCanvas, const wxGLContext *aOther=nullptr)
Create a managed OpenGL context.
static int SetSwapInterval(wxGLCanvas *aCanvas, int aVal)
Attempt to set the OpenGL swap interval.
Definition gl_utils.cpp:78
static wxString DetectGLBackend(wxGLCanvas *aCanvas)
Definition gl_utils.cpp:50
Provides basic 3D controls ( zoom, rotate, translate, ... )
static const float m_delta_move_step_factor
HIDPI_GL_3D_CANVAS(const KIGFX::VC_SETTINGS &aVcSettings, CAMERA &aCamera, wxWindow *parent, const wxGLAttributes &aGLAttribs, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=0, const wxString &name=wxGLCanvasName, const wxPalette &palette=wxNullPalette)
void OnMouseWheelCamera(wxMouseEvent &event, bool aPan)
void OnMouseMoveCamera(wxMouseEvent &event)
virtual wxSize GetNativePixelSize() const
Definition pad.h:61
GL_CONTEXT_MANAGER * GetGLContextManager()
Definition pgm_base.h:114
Cache for storing the 3D shapes.
Definition 3d_cache.h:53
GizmoSphereSelection
Enum to indicate which sphere (direction) is selected.
@ Count
Number of selectable spheres.
A wrapper for reporting to a specific text location in a statusbar.
Definition reporter.h:410
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
const wxString & GetZoneName() const
Definition zone.h:160
bool IsOnCopperLayer() const override
Definition zone.cpp:652
#define _(s)
wxDEFINE_EVENT(wxEVT_REFRESH_CUSTOM_COMMAND, wxCommandEvent)
#define EDA_3D_CANVAS_ID
Declaration of the eda_3d_viewer class.
@ ZOOM_LEVEL
@ HOVERED_ITEM
@ RENDER_TIME
@ FRAME_PCB_EDITOR
Definition frame_type.h:38
@ FRAME_SCH
Definition frame_type.h:30
static const wxChar * m_logTrace
Trace mask used to enable or disable the trace output of this class.
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ B_Cu
Definition layer_ids.h:61
@ F_Cu
Definition layer_ids.h:60
This file contains miscellaneous commonly used macros and functions.
@ MAIL_SELECTION
Definition mail_type.h:36
KICOMMON_API bool PackKiwayApiMessage(const google::protobuf::Message &aMessage, std::string &aBytes)
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
void OglGetScreenshot(wxImage &aDstImage)
Get the pixel data of current OpenGL image.
Definition ogl_utils.cpp:32
Define generic OpenGL functions that are common to any OpenGL target.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
std::shared_ptr< PNS_LOG_VIEWER_OVERLAY > overlay
int64_t GetRunningMicroSecs()
An alternate way to calculate an elapsed time (in microsecondes) to class PROF_COUNTER.
static float distance(const SFVEC2UI &a, const SFVEC2UI &b)
@ RPT_SEVERITY_ERROR
T * GetAppSettings(const char *aFilename)
const int scale
wxString From_UTF8(const char *cstring)
A translucent triangle soup drawn over the scene.
Definition ray.h:59
SFVEC3F m_Dir
Definition ray.h:63
void Init(const SFVEC3F &o, const SFVEC3F &d)
Definition ray.cpp:31
SFVEC3F m_Origin
Definition ray.h:60
SFVEC3F at(float t) const
Definition ray.h:80
Store the a model based on meshes and materials.
Definition c3dmodel.h:111
unsigned int m_MeshesSize
Number of meshes in the array.
Definition c3dmodel.h:112
SMESH * m_Meshes
The meshes list of this model.
Definition c3dmodel.h:113
Per-vertex normal/color/texcoors structure.
Definition c3dmodel.h:77
unsigned int * m_FaceIdx
Triangle Face Indexes.
Definition c3dmodel.h:84
unsigned int m_VertexSize
Number of vertex in the arrays.
Definition c3dmodel.h:78
unsigned int m_FaceIdxSize
Number of elements of the m_FaceIdx array.
Definition c3dmodel.h:83
SFVEC3F * m_Positions
Vertex position array.
Definition c3dmodel.h:79
IbisParser parser & reporter
int delta
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:82
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
unsigned int GLenum
Definition vrml_layer.h:43
glm::vec3 SFVEC3F
Definition xv3d_types.h:40