25#include <wx/tokenzr.h>
27#include <fmt/format.h>
30#include <api/common/commands/cross_probe_commands.pb.h>
112 wxDefaultSize, wxFULL_REPAINT_ON_RESIZE ),
117 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::EDA_3D_CANVAS" ) );
132 auto busy_indicator_factory =
135 return std::make_unique<WX_BUSY_INDICATOR>();
147 wxASSERT( a3DCachePointer !=
nullptr );
150#if defined( __WXMSW__ )
151 EnableTouchEvents( wxTOUCH_ZOOM_GESTURE | wxTOUCH_ROTATE_GESTURE | wxTOUCH_PAN_GESTURES );
152#elif defined( __WXGTK__ )
153 EnableTouchEvents( wxTOUCH_ZOOM_GESTURE | wxTOUCH_ROTATE_GESTURE );
156 const wxEventType events[] =
162 wxEVT_LEFT_UP, wxEVT_LEFT_DOWN, wxEVT_LEFT_DCLICK,
163 wxEVT_RIGHT_UP, wxEVT_RIGHT_DOWN, wxEVT_RIGHT_DCLICK,
164 wxEVT_MIDDLE_UP, wxEVT_MIDDLE_DOWN, wxEVT_MIDDLE_DCLICK,
165 wxEVT_MOTION, wxEVT_MOUSEWHEEL, wxEVT_CHAR, wxEVT_CHAR_HOOK,
167 wxEVT_MENU_OPEN, wxEVT_MENU_CLOSE, wxEVT_MENU_HIGHLIGHT
170 for( wxEventType eventType : events )
177 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::~EDA_3D_CANVAS" ) );
240 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::initializeOpenGL" ) );
244 const int glVersion = gladLoaderLoadGL();
248 wxLogMessage( wxT(
"Failed to load OpenGL via loader" ) );
254 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::initializeOpenGL Using OpenGL version %s" ),
255 From_UTF8( (
char*) glGetString( GL_VERSION ) ) );
258 SetOpenGLInfo( (
const char*) glGetString( GL_VENDOR ), (
const char*) glGetString( GL_RENDERER ),
259 (
const char*) glGetString( GL_VERSION ) );
261 wxString version =
From_UTF8( (
char *) glGetString( GL_VERSION ) );
263 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::%s OpenGL version string %s." ),
264 __WXFUNCTION__, version );
270 wxStringTokenizer tokenizer( version,
" \t\r\n" );
272 if( tokenizer.HasMoreTokens() )
277 tmp = tokenizer.GetNextToken();
279 tokenizer.SetString( tmp, wxString( wxT(
"." ) ) );
281 if( tokenizer.HasMoreTokens() )
282 tokenizer.GetNextToken().ToLong( &major );
284 if( tokenizer.HasMoreTokens() )
285 tokenizer.GetNextToken().ToLong( &minor );
287 if( major < 2 || ( ( major == 2 ) && ( minor < 1 ) ) )
289 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::%s OpenGL ray tracing not supported." ),
295 GetParent()->ProcessWindowEvent( evt );
301 if( ( major == 1 ) && ( minor < 5 ) )
303 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::%s OpenGL not supported." ),
310#if wxCHECK_VERSION( 3, 3, 3 )
311 wxGLCanvas::SetSwapInterval( -1 );
340 if( aCachePointer !=
nullptr )
343 if( aBoard !=
nullptr )
386 msg.Printf( wxT(
"dx %3.2f" ),
m_camera.GetCameraPos().x );
389 msg.Printf( wxT(
"dy %3.2f" ),
m_camera.GetCameraPos().y );
392 msg.Printf( wxT(
"zoom %3.2f" ), 1 /
m_camera.GetZoom() );
412 if( !IsShownOnScreen() )
414 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::DoRePaint !IsShown" ) );
425 wxWindow* viewer = wxGetTopLevelParent(
this );
426 wxWindow* owner = viewer ? viewer->GetParent() :
nullptr;
428 if( owner && !owner->IsShownOnScreen() )
450 wxString err_messages;
451 auto start_time = std::chrono::steady_clock::now();
487 const bool windows_size_changed =
m_camera.SetCurWindowSize( clientSize );
511 glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
512 glClear( GL_COLOR_BUFFER_BIT );
533 const bool was_camera_changed =
m_camera.ParametersChanged();
538 || windows_size_changed )
546 float curtime_delta_s = 0.0f;
552 curtime_delta_s =
static_cast<float>(
static_cast<double>( curtime_delta ) / 1e6 )
554 m_camera.Interpolate( curtime_delta_s );
556 if( curtime_delta_s > 1.0f )
572 bool requested_redraw =
false;
582 catch( std::runtime_error& )
615 const double calculation_time =
616 std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now() - start_time ).count();
620 m_parentStatusBar->SetStatusText( wxString::Format(
_(
"Last render time %.0f ms" ), calculation_time ),
630 if( !err_messages.IsEmpty() )
631 wxLogMessage( err_messages );
644 int index =
static_cast<int>( selectedGizmoSphere );
645 if(
index >= 0 &&
index <
static_cast<int>( viewTable.size() ) )
662 if( !buffer || width <= 0 || height <= 0 )
670 if( !GetParent() || !GetParent()->GetParent() || !GetParent()->GetParent()->IsShownOnScreen() )
676 wxString err_messages;
692 wxLogError(
_(
"OpenGL context creation error" ) );
700 GLuint framebuffer = 0;
701 GLuint colorTexture = 0;
702 GLuint depthStencilBuffer = 0;
703 GLint oldFramebuffer = 0;
704 GLint oldViewport[4];
707 glGetIntegerv( GL_FRAMEBUFFER_BINDING, &oldFramebuffer );
708 glGetIntegerv( GL_VIEWPORT, oldViewport );
711 glGenFramebuffers( 1, &framebuffer );
712 glBindFramebuffer( GL_FRAMEBUFFER, framebuffer );
715 glGenTextures( 1, &colorTexture );
716 glBindTexture( GL_TEXTURE_2D, colorTexture );
717 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
nullptr );
718 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
719 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
720 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
721 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
722 glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0 );
727 glGenRenderbuffers( 1, &depthStencilBuffer );
728 glBindRenderbuffer( GL_RENDERBUFFER, depthStencilBuffer );
729 glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height );
730 glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER,
731 depthStencilBuffer );
733 auto resetState = std::unique_ptr<void, std::function<void(
void*)>>(
734 reinterpret_cast<void*
>(1),
736 glBindFramebuffer( GL_FRAMEBUFFER, oldFramebuffer );
737 glViewport( oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3] );
738 glDeleteFramebuffers( 1, &framebuffer );
739 glDeleteTextures( 1, &colorTexture );
740 glDeleteRenderbuffers( 1, &depthStencilBuffer );
747 GLenum framebufferStatus = glCheckFramebufferStatus( GL_FRAMEBUFFER );
749 if( framebufferStatus != GL_FRAMEBUFFER_COMPLETE )
751 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::RenderToFrameBuffer Framebuffer incomplete: 0x%04X" ),
758 glViewport( 0, 0, width, height );
761 wxSize clientSize( width, height );
762 const bool windows_size_changed =
m_camera.SetCurWindowSize( clientSize );
769 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::RenderToFrameBuffer OpenGL initialization failed." ) );
775 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::RenderToFrameBuffer OpenGL version not supported." ) );
781 glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
782 glClear( GL_COLOR_BUFFER_BIT );
785 glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
799 const bool was_camera_changed =
m_camera.ParametersChanged();
810 float curtime_delta_s = 0.0f;
814 curtime_delta_s =
static_cast<float>(
static_cast<double>( curtime_delta ) / 1e6 )
816 m_camera.Interpolate( curtime_delta_s );
818 if( curtime_delta_s > 1.0f )
841 catch( std::runtime_error& )
853 glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
856 GLenum error = glGetError();
857 if( error != GL_NO_ERROR )
859 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::RenderToFrameBuffer OpenGL error: 0x%04X" ), error );
860 err_messages += wxString::Format(
_(
"OpenGL error during off-screen rendering: 0x%04X\n" ), error );
866 if( !err_messages.IsEmpty() )
867 wxLogMessage( err_messages );
890 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::OnEraseBackground" ) );
897 wxLogTrace(
m_logTrace, wxT(
"EDA_3D_CANVAS::OnMouseWheel" ) );
920 float magnification = (
event.GetMagnification() + 1.0f );
933 if( aEvent.IsGestureStart() )
936 m_camera.SetCurMousePosition( aEvent.GetPosition() );
944 m_camera.Pan( aEvent.GetPosition() );
945 m_camera.SetCurMousePosition( aEvent.GetPosition() );
960 if( aEvent.IsGestureStart() )
961 m_camera.SetCurMousePosition( aEvent.GetPosition() );
966 m_camera.Pan( aEvent.GetPosition() );
967 m_camera.SetCurMousePosition( aEvent.GetPosition() );
978 if( aEvent.IsGestureStart() )
981 m_camera.SetCurMousePosition( aEvent.GetPosition() );
1025 return wxString::Format(
_(
"Net %s\tNet class %s" ), aItem->GetNet()->GetNetname(),
1026 aItem->GetNet()->GetNetClass()->GetHumanReadableName() );
1041 switch( rollOverItem->
Type() )
1045 PAD*
pad =
static_cast<PAD*
>( rollOverItem );
1047 if( !
pad->GetNumber().IsEmpty() )
1048 msg += wxString::Format(
_(
"Pad %s\t" ),
pad->GetNumber() );
1050 if(
pad->IsOnCopperLayer() )
1051 msg += printNetInfo(
pad );
1068 msg += printNetInfo( track );
1074 ZONE* zone =
static_cast<ZONE*
>( rollOverItem );
1079 msg += wxString::Format(
_(
"Rule area %s\t" ), zone->
GetZoneName() );
1081 msg += wxString::Format(
_(
"Zone %s\t" ), zone->
GetZoneName() );
1085 msg += printNetInfo( zone );
1141 bool gizmoClicked =
false;
1146 wxSize logicalSize = GetClientSize();
1147 int logicalW = logicalSize.GetWidth();
1148 int logicalH = logicalSize.GetHeight();
1150 int gizmo_x = 0, gizmo_y = 0, gizmo_width = 0, gizmo_height = 0;
1151 std::tie( gizmo_x, gizmo_y, gizmo_width, gizmo_height ) =
m_3d_render_opengl->getGizmoViewport();
1153 float scaleX =
static_cast<float>(
static_cast<double>( gizmo_width ) /
static_cast<double>( logicalW ) );
1154 float scaleY =
static_cast<float>(
static_cast<double>( gizmo_height ) /
static_cast<double>( logicalH ) );
1156 int scaledMouseX =
static_cast<int>(
static_cast<float>(
event.GetX() ) * scaleX );
1157 int scaledMouseY =
static_cast<int>(
static_cast<float>( logicalH -
event.GetY() ) * scaleY );
1174 if( intersectedBoardItem )
1176 switch( intersectedBoardItem->
Type() )
1180 case PCB_PAD_T: footprint =
static_cast<PAD*
>( intersectedBoardItem )->GetParentFootprint();
break;
1182 case PCB_FIELD_T: footprint =
static_cast<PCB_FIELD*
>( intersectedBoardItem )->GetParentFootprint();
break;
1193 kiapi::common::commands::SyncSelection sync;
1196 sync.add_items()->mutable_footprint()->set_reference( footprint->
GetReference().ToUTF8() );
1198 sync.set_mode( kiapi::common::commands::SyncSelectionMode::SSM_ITEMS_ONLY );
1199 sync.set_context( kiapi::common::commands::SyncSelectionContext::SSC_IMPLICIT );
1201 std::string payload;
1308 if( aRedrawImmediately )
1315 wxPostEvent(
this, redrawEvent );
1327 wxASSERT( aMovingSpeed > FLT_EPSILON );
1367 m_camera.SetLookAtPos_T1( mouseRay.
at( hit_t ) );
1381 const float arrow_moving_time_speed = 8.0f;
1383 switch( aRequestedView )
1449 m_camera.ViewCommand_T1( aRequestedView );
1457 m_camera.ViewCommand_T1( aRequestedView );
1471 switch( cfg->m_Render.engine )
1494 m_camera.MakeRayAtCurrentMousePosition( rayOrigin, rayDir );
1497 mouseRay.
Init( rayOrigin, rayDir );
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.
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...
Information pertinent to a Pcbnew printed circuit board.
A class used to derive camera objects from.
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).
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 OnLeftDown(wxMouseEvent &event)
void OnPanGesture(wxPanGestureEvent &event)
void OnRightUp(wxMouseEvent &event)
ACCELERATOR_3D * m_accelerator3DShapes
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)
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.
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.
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
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.
void UnlockCtx(wxGLContext *aContext)
Allow other canvases to bind an OpenGL context.
void DestroyCtx(wxGLContext *aContext)
Destroy a managed OpenGL context.
void 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.
static wxString DetectGLBackend(wxGLCanvas *aCanvas)
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
GL_CONTEXT_MANAGER * GetGLContextManager()
Cache for storing the 3D shapes.
GizmoSphereSelection
Enum to indicate which sphere (direction) is selected.
@ None
No sphere selected.
@ Count
Number of selectable spheres.
A wrapper for reporting to a specific text location in a statusbar.
Handle a list of polygons defining a copper zone.
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
const wxString & GetZoneName() const
bool IsOnCopperLayer() const override
wxDEFINE_EVENT(wxEVT_REFRESH_CUSTOM_COMMAND, wxCommandEvent)
Declaration of the eda_3d_viewer class.
static const wxChar * m_logTrace
Trace mask used to enable or disable the trace output of this class.
This file contains miscellaneous commonly used macros and functions.
KICOMMON_API bool PackKiwayApiMessage(const google::protobuf::Message &aMessage, std::string &aBytes)
void OglGetScreenshot(wxImage &aDstImage)
Get the pixel data of current OpenGL image.
Define generic OpenGL functions that are common to any OpenGL target.
PGM_BASE & Pgm()
The global program "get" accessor.
int64_t GetRunningMicroSecs()
An alternate way to calculate an elapsed time (in microsecondes) to class PROF_COUNTER.
T * GetAppSettings(const char *aFilename)
wxString From_UTF8(const char *cstring)
void Init(const SFVEC3F &o, const SFVEC3F &d)
SFVEC3F at(float t) const
IbisParser parser & reporter
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
@ PCB_ZONE_T
class ZONE, a copper pour area
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
@ PCB_PAD_T
class PAD, a pad in a footprint
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)