1 /**************************************************************************
3 * Copyright 2013-2014 RAD Game Tools and Valve Software
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 **************************************************************************/
26 #include <QFileDialog>
27 #include <QHBoxLayout>
28 #include <QItemSelection>
30 #include <QSortFilterProxyModel>
31 #include <QSpacerItem>
32 #include <QToolButton>
33 #include <QMessageBox>
35 #include "ui_vogleditor.h"
36 #include "vogleditor.h"
38 #include "vogleditor_qapicalltreemodel.h"
39 #include "vogleditor_apicalltimelinemodel.h"
41 #include "vogl_platform.h"
42 #include "vogl_assert.h"
43 #include "vogl_file_utils.h"
44 #include "vogl_find_files.h"
46 #include "vogl_texture_format.h"
47 #include "vogl_trace_file_reader.h"
48 #include "vogl_trace_file_writer.h"
49 #include "vogleditor_qstatetreemodel.h"
50 #include "vogleditor_statetreetextureitem.h"
51 #include "vogleditor_statetreeprogramitem.h"
52 #include "vogleditor_statetreeshaderitem.h"
53 #include "vogleditor_statetreeframebufferitem.h"
54 #include "vogleditor_qtextureexplorer.h"
56 #define VOGLEDITOR_DISABLE_TAB(tab) ui->tabWidget->setTabEnabled(ui->tabWidget->indexOf(tab), false);
57 #define VOGLEDITOR_ENABLE_TAB(tab) ui->tabWidget->setTabEnabled(ui->tabWidget->indexOf(tab), true);
59 //----------------------------------------------------------------------------------------------------------------------
61 //----------------------------------------------------------------------------------------------------------------------
62 static void *g_actual_libgl_module_handle;
63 static QString g_PROJECT_NAME = "Vogl Editor";
65 //----------------------------------------------------------------------------------------------------------------------
66 // vogl_get_proc_address_helper
67 //----------------------------------------------------------------------------------------------------------------------
68 static vogl_void_func_ptr_t vogl_get_proc_address_helper(const char *pName)
72 vogl_void_func_ptr_t pFunc = g_actual_libgl_module_handle ? reinterpret_cast<vogl_void_func_ptr_t>(dlsym(g_actual_libgl_module_handle, pName)) : NULL;
74 if ((!pFunc) && (GL_ENTRYPOINT(glXGetProcAddress)))
75 pFunc = reinterpret_cast<vogl_void_func_ptr_t>( GL_ENTRYPOINT(glXGetProcAddress)(reinterpret_cast<const GLubyte*>(pName)) );
81 //----------------------------------------------------------------------------------------------------------------------
83 //----------------------------------------------------------------------------------------------------------------------
88 g_actual_libgl_module_handle = dlopen("libGL.so.1", RTLD_LAZY);
89 if (!g_actual_libgl_module_handle)
91 vogl_error_printf("%s: Failed loading libGL.so.1!\n", VOGL_FUNCTION_NAME);
95 GL_ENTRYPOINT(glXGetProcAddress) = reinterpret_cast<glXGetProcAddress_func_ptr_t>(dlsym(g_actual_libgl_module_handle, "glXGetProcAddress"));
96 if (!GL_ENTRYPOINT(glXGetProcAddress))
98 vogl_error_printf("%s: Failed getting address of glXGetProcAddress() from libGL.so.1!\n", VOGL_FUNCTION_NAME);
105 VoglEditor::VoglEditor(QWidget *parent) :
107 ui(new Ui::VoglEditor),
109 m_framebufferExplorer(NULL),
110 m_textureExplorer(NULL),
111 m_renderbufferExplorer(NULL),
112 m_programExplorer(NULL),
113 m_shaderExplorer(NULL),
115 m_currentSnapshot(NULL),
116 m_pCurrentCallTreeItem(NULL),
118 m_pPauseButton(NULL),
121 m_pTraceReader(NULL),
122 m_pApicallTreeModel(NULL)
128 vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper);
131 m_statusLabel = new QLabel(ui->statusBar);
132 m_statusLabel->setBaseSize(150, 12);
133 ui->statusBar->addWidget(m_statusLabel, 1);
135 // setup framebuffer tab
136 QGridLayout* framebufferTab_layout = new QGridLayout;
137 m_framebufferExplorer = new vogleditor_QFramebufferExplorer(ui->framebufferTab);
138 framebufferTab_layout->addWidget(m_framebufferExplorer, 0, 0);
139 ui->framebufferTab->setLayout(framebufferTab_layout);
142 QGridLayout* textureTab_layout = new QGridLayout;
143 m_textureExplorer = new vogleditor_QTextureExplorer(ui->textureTab);
144 textureTab_layout->addWidget(m_textureExplorer, 0, 0);
145 ui->textureTab->setLayout(textureTab_layout);
147 // setup renderbuffer tab
148 QGridLayout* rbTab_layout = new QGridLayout;
149 m_renderbufferExplorer = new vogleditor_QTextureExplorer(ui->renderbufferTab);
150 rbTab_layout->addWidget(m_renderbufferExplorer, 0, 0);
151 ui->renderbufferTab->setLayout(rbTab_layout);
154 QGridLayout* programTab_layout = new QGridLayout;
155 m_programExplorer = new vogleditor_QProgramExplorer(ui->programTab);
156 programTab_layout->addWidget(m_programExplorer, 0, 0);
157 ui->programTab->setLayout(programTab_layout);
160 QGridLayout* shaderTab_layout = new QGridLayout;
161 m_shaderExplorer = new vogleditor_QShaderExplorer(ui->shaderTab);
162 shaderTab_layout->addWidget(m_shaderExplorer, 0, 0);
163 ui->shaderTab->setLayout(shaderTab_layout);
166 m_timeline = new vogleditor_QTimelineView();
167 m_timeline->setMinimumHeight(100);
168 ui->verticalLayout->addWidget(m_timeline);
169 ui->verticalLayout->removeWidget(ui->timelineViewPlaceholder);
171 // add buttons to toolbar
172 m_pPlayButton = new QToolButton(ui->mainToolBar);
173 m_pPlayButton->setText("Play trace");
174 m_pPlayButton->setEnabled(false);
176 m_pPauseButton = new QToolButton(ui->mainToolBar);
177 m_pPauseButton->setText("Pause");
178 m_pPauseButton->setEnabled(false);
180 m_pTrimButton = new QToolButton(ui->mainToolBar);
181 m_pTrimButton->setText("Trim");
182 m_pTrimButton->setEnabled(false);
184 m_pStopButton = new QToolButton(ui->mainToolBar);
185 m_pStopButton->setText("Stop");
186 m_pStopButton->setEnabled(false);
188 // Temporarily hide the other buttons (until asyncronous playback is supported)
189 m_pPauseButton->setVisible(false);
190 m_pTrimButton->setVisible(false);
191 m_pStopButton->setVisible(false);
193 ui->mainToolBar->addWidget(m_pPlayButton);
194 ui->mainToolBar->addWidget(m_pPauseButton);
195 ui->mainToolBar->addWidget(m_pTrimButton);
196 ui->mainToolBar->addWidget(m_pStopButton);
198 connect(m_pPlayButton, SIGNAL(clicked()), this, SLOT(playCurrentTraceFile()));
199 connect(m_pPauseButton, SIGNAL(clicked()), this, SLOT(pauseCurrentTraceFile()));
200 connect(m_pTrimButton, SIGNAL(clicked()), this, SLOT(trimCurrentTraceFile()));
201 connect(m_pStopButton, SIGNAL(clicked()), this, SLOT(stopCurrentTraceFile()));
203 connect(m_programExplorer, SIGNAL(program_edited(vogl_program_state*)), this, SLOT(on_program_edited(vogl_program_state*)));
205 reset_tracefile_ui();
208 VoglEditor::~VoglEditor()
213 if (m_textureExplorer != NULL)
215 delete m_textureExplorer;
216 m_textureExplorer = NULL;
219 if (m_renderbufferExplorer != NULL)
221 delete m_renderbufferExplorer;
222 m_renderbufferExplorer = NULL;
225 if (m_programExplorer != NULL)
227 delete m_programExplorer;
228 m_programExplorer = NULL;
231 if (m_shaderExplorer != NULL)
233 delete m_shaderExplorer;
234 m_shaderExplorer = NULL;
238 void VoglEditor::playCurrentTraceFile()
240 QCursor origCursor = cursor();
241 setCursor(Qt::WaitCursor);
244 m_pPlayButton->setEnabled(false);
245 m_pPauseButton->setEnabled(true);
246 m_pTrimButton->setEnabled(true);
247 m_pStopButton->setEnabled(true);
248 m_statusLabel->clear();
250 if (m_traceReplayer.replay(m_pTraceReader, m_pApicallTreeModel->root(), NULL, 0, true))
252 // replay was successful
253 m_pPlayButton->setEnabled(true);
254 m_pPauseButton->setEnabled(false);
255 m_pTrimButton->setEnabled(false);
256 m_pStopButton->setEnabled(false);
260 m_statusLabel->setText("Failed to replay the trace.");
263 setCursor(origCursor);
266 void VoglEditor::pauseCurrentTraceFile()
268 if (m_traceReplayer.pause())
271 m_pPlayButton->setEnabled(true);
272 m_pPauseButton->setEnabled(false);
273 m_pTrimButton->setEnabled(true);
274 m_pStopButton->setEnabled(true);
275 m_statusLabel->clear();
279 m_statusLabel->setText("Failed to pause the trace replay.");
283 void VoglEditor::trimCurrentTraceFile()
285 if (m_traceReplayer.trim())
287 m_statusLabel->clear();
291 m_statusLabel->setText("Failed to trim the trace replay.");
295 void VoglEditor::stopCurrentTraceFile()
297 if (m_traceReplayer.stop())
300 m_pPlayButton->setEnabled(true);
301 m_pPauseButton->setEnabled(false);
302 m_pTrimButton->setEnabled(false);
303 m_pStopButton->setEnabled(false);
304 m_statusLabel->clear();
308 m_statusLabel->setText("Failed to stop the trace replay.");
312 void VoglEditor::on_actionE_xit_triggered()
317 void VoglEditor::on_action_Open_triggered()
319 QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(),
320 tr("GLI Binary Files (*.bin);;JSON Files (*.json)"));
322 if (!fileName.isEmpty()) {
323 vogl::dynamic_string filename;
324 filename.set(fileName.toStdString().c_str());
326 if (open_trace_file(filename) == false) {
327 QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
333 void VoglEditor::on_action_Close_triggered()
338 void VoglEditor::close_trace_file()
340 if (m_pTraceReader != NULL)
342 m_pTraceReader->close();
343 vogl_delete(m_pTraceReader);
344 m_pTraceReader = NULL;
346 setWindowTitle(g_PROJECT_NAME);
348 m_openFilename.clear();
349 m_backtraceToJsonMap.clear();
350 m_backtraceDoc.clear();
351 m_searchApicallResults.clear();
353 reset_tracefile_ui();
355 ui->treeView->setModel(NULL);
356 ui->machineInfoText->clear();
357 ui->backtraceText->clear();
358 m_timeline->setModel(NULL);
359 m_timeline->repaint();
361 if (m_pTimelineModel != NULL)
363 delete m_pTimelineModel;
364 m_pTimelineModel = NULL;
369 void VoglEditor::write_child_api_calls(vogleditor_apiCallTreeItem* pItem, FILE* pFile)
371 QString string = pItem->columnData(VOGL_ACTC_APICALL, Qt::DisplayRole).toString();
372 vogl_fwrite(string.toStdString().c_str(), 1, string.size(), pFile);
373 vogl_fwrite("\r\n", 1, 2, pFile);
375 for (int i = 0; i < pItem->childCount(); i++)
377 write_child_api_calls(pItem->child(i), pFile);
381 void VoglEditor::on_actionExport_API_Calls_triggered()
383 QString suggestedName = m_openFilename;
385 int lastIndex = suggestedName.lastIndexOf('-');
388 suggestedName = suggestedName.remove(lastIndex, suggestedName.size() - lastIndex);
390 suggestedName += "-ApiCalls.txt";
392 QString fileName = QFileDialog::getSaveFileName(this, tr("Export API Calls"), suggestedName, tr("Text (*.txt)"));
394 if (!fileName.isEmpty())
396 vogl::dynamic_string filename;
397 filename.set(fileName.toStdString().c_str());
399 FILE* pFile = vogl_fopen(filename.c_str(), "w");
400 vogleditor_QApiCallTreeModel* pModel = static_cast<vogleditor_QApiCallTreeModel*>(ui->treeView->model());
401 vogleditor_apiCallTreeItem* pRoot = pModel->root();
402 for (int i = 0; i < pRoot->childCount(); i++)
404 write_child_api_calls(pRoot->child(i), pFile);
410 static const unsigned int VOGLEDITOR_SESSION_FILE_FORMAT_VERSION_1 = 1;
411 static const unsigned int VOGLEDITOR_SESSION_FILE_FORMAT_VERSION = VOGLEDITOR_SESSION_FILE_FORMAT_VERSION_1;
413 bool VoglEditor::load_session_from_disk(QString sessionFile)
416 json_document sessionDoc;
417 if (!sessionDoc.deserialize_file(sessionFile.toStdString().c_str()))
422 // look for expected metadata
423 json_node* pMetadata = sessionDoc.get_root()->find_child_object("metadata");
424 if (pMetadata == NULL)
429 const json_value& rFormatVersion = pMetadata->find_value("session_file_format_version");
430 if (!rFormatVersion.is_valid())
435 if (rFormatVersion.as_uint32() != VOGLEDITOR_SESSION_FILE_FORMAT_VERSION_1)
440 // load base trace file
441 json_node* pBaseTraceFile = sessionDoc.get_root()->find_child_object("base_trace_file");
442 if (pBaseTraceFile == NULL)
447 const json_value& rBaseTraceFilePath = pBaseTraceFile->find_value("rel_path");
448 const json_value& rBaseTraceFileUuid = pBaseTraceFile->find_value("uuid");
450 if (!rBaseTraceFilePath.is_valid() || !rBaseTraceFileUuid.is_valid())
455 dynamic_string sessionPathName;
456 dynamic_string sessionFileName;
457 file_utils::split_path(sessionFile.toStdString().c_str(), sessionPathName, sessionFileName);
459 dynamic_string traceFilePath = sessionPathName;
460 traceFilePath.append(rBaseTraceFilePath.as_string());
462 if (!open_trace_file(traceFilePath))
467 // TODO: verify UUID of the loaded trace file
469 // load session data if it is available
470 json_node* pSessionData = sessionDoc.get_root()->find_child_object("session_data");
471 if (pSessionData != NULL)
473 const json_value& rSessionPath = pSessionData->find_value("rel_path");
474 if (!rSessionPath.is_valid())
479 dynamic_string sessionDataPath = sessionPathName;
480 sessionDataPath.append(rSessionPath.as_string());
482 vogl_loose_file_blob_manager file_blob_manager;
483 file_blob_manager.init(cBMFReadWrite, sessionDataPath.c_str());
484 vogl_blob_manager* pBlob_manager = static_cast<vogl_blob_manager*>(&file_blob_manager);
487 const json_node* pSnapshots = pSessionData->find_child_array("snapshots");
488 for (unsigned int i = 0; i < pSnapshots->size(); i++)
490 const json_node* pSnapshotNode = pSnapshots->get_value_as_object(i);
492 const json_value& uuid = pSnapshotNode->find_value("uuid");
493 const json_value& isValid = pSnapshotNode->find_value("is_valid");
494 const json_value& isEdited = pSnapshotNode->find_value("is_edited");
495 const json_value& isOutdated = pSnapshotNode->find_value("is_outdated");
496 const json_value& frameNumber = pSnapshotNode->find_value("frame_number");
497 const json_value& callIndex = pSnapshotNode->find_value("call_index");
498 const json_value& path = pSnapshotNode->find_value("rel_path");
500 // make sure expected nodes are valid
501 if (!isValid.is_valid() || !isEdited.is_valid() || !isOutdated.is_valid())
506 vogl_gl_state_snapshot* pSnapshot = NULL;
508 if (path.is_valid() && isValid.as_bool() && uuid.is_valid())
510 dynamic_string snapshotPath = sessionDataPath;
511 snapshotPath.append(path.as_string());
514 json_document snapshotDoc;
515 if (!snapshotDoc.deserialize_file(snapshotPath.c_str()))
520 // attempt to verify the snapshot file
521 json_node* pSnapshotRoot = snapshotDoc.get_root();
522 if (pSnapshotRoot == NULL)
524 vogl_warning_printf("Invalid snapshot file at %s.", path.as_string_ptr());
528 const json_value& snapshotUuid = pSnapshotRoot->find_value("uuid");
529 if (!snapshotUuid.is_valid())
531 vogl_warning_printf("Invalid 'uuid' in snapshot file at %s.", path.as_string_ptr());
535 if (snapshotUuid.as_string() != uuid.as_string())
537 vogl_warning_printf("Mismatching 'uuid' between snapshot file at %s and that stored in the session file at %s.", path.as_string_ptr(), sessionFile.toStdString().c_str());
541 vogl_ctypes trace_gl_ctypes(m_pTraceReader->get_sof_packet().m_pointer_sizes);
542 pSnapshot = vogl_new(vogl_gl_state_snapshot);
543 if (!pSnapshot->deserialize(*snapshotDoc.get_root(), *pBlob_manager, &trace_gl_ctypes))
545 vogl_delete(pSnapshot);
547 vogl_warning_printf("Unable to deserialize the snapshot with uuid %s.", uuid.as_string_ptr());
552 vogleditor_gl_state_snapshot* pContainer = vogl_new(vogleditor_gl_state_snapshot, pSnapshot);
553 pContainer->set_edited(isEdited.as_bool());
554 pContainer->set_outdated(isOutdated.as_bool());
556 if (callIndex.is_valid())
558 // the snapshot is associated with an api call
559 vogleditor_apiCallTreeItem* pItem = m_pApicallTreeModel->find_call_number(callIndex.as_uint64());
562 pItem->set_snapshot(pContainer);
566 vogl_warning_printf("Unable to find API call index %" PRIu64 " to load the snapshot into.", callIndex.as_uint64());
567 if (pSnapshot != NULL) { vogl_delete(pSnapshot); pSnapshot = NULL; }
568 if (pContainer != NULL) { vogl_delete(pContainer); pContainer = NULL; }
571 else if (frameNumber.is_valid())
573 // the snapshot is associated with a frame.
574 // frame snapshots have the additional requirement that the snapshot itself MUST exist since
575 // we only save a frame snapshot if it is the inital frame and it has been edited.
576 // If we allow NULL snapshots, that we could accidently remove the initial snapshot that was loaded with the trace file.
577 if (pSnapshot != NULL)
579 vogleditor_apiCallTreeItem* pItem = m_pApicallTreeModel->find_frame_number(frameNumber.as_uint64());
582 pItem->set_snapshot(pContainer);
586 vogl_warning_printf("Unable to find frame number %" PRIu64 " to load the snapshot into.", frameNumber.as_uint64());
587 if (pSnapshot != NULL) { vogl_delete(pSnapshot); pSnapshot = NULL; }
588 if (pContainer != NULL) { vogl_delete(pContainer); pContainer = NULL; }
594 vogl_warning_printf("Session file contains invalid call or frame number for snapshot with uuid %s", uuid.as_string_ptr());
595 if (pSnapshot != NULL) { vogl_delete(pSnapshot); pSnapshot = NULL; }
596 if (pContainer != NULL) { vogl_delete(pContainer); pContainer = NULL; }
605 * Below is a summary of the information that needs to be saved out in a session's json file so that we can reload the session and be fully-featured.
606 * Note that not all of this information is currently supported (either by VoglEditor or the save/load functionality).
608 * sample data structure for version 1:
611 "session_file_format_version" : "0x1" <- would need to be updated when organization of existing data is changed
613 "base_trace_file" : {
614 "path" : "../traces/trimmed4.bin",
615 "uuid" : [ 2761638124, 1361789091, 2623121922, 1789156619 ]
618 "path" : "/home/peterl/voglproj/vogl_build/traces/trimmed4-vogleditor-sessiondata/",
621 "uuid" : "B346B680801ED2F5144E421DEA5EFDCC",
624 "is_outdated" : false,
628 "uuid" : "BC261B884088DBEADF376A03A489F2B9",
631 "is_outdated" : false,
632 "call_index" : 881069,
633 "path" : "/home/peterl/voglproj/vogl_build/traces/trimmed4-vogleditor-sessiondata/snapshot_call_881069.json"
636 "uuid" : "176DE3DEAA437B871FE122C84D5432E3",
639 "is_outdated" : false,
640 "call_index" : 881075,
641 "path" : "/home/peterl/voglproj/vogl_build/traces/trimmed4-vogleditor-sessiondata/snapshot_call_881075.json"
646 "is_outdated" : true,
647 "call_index" : 881080
653 bool VoglEditor::save_session_to_disk(QString sessionFile)
655 dynamic_string sessionPathName;
656 dynamic_string sessionFileName;
657 file_utils::split_path(sessionFile.toStdString().c_str(), sessionPathName, sessionFileName);
659 // modify the session file name to make a sessiondata folder
660 QString sessionDataFolder(sessionFileName.c_str());
661 int lastIndex = sessionDataFolder.lastIndexOf('.');
664 sessionDataFolder = sessionDataFolder.remove(lastIndex, sessionDataFolder.size() - lastIndex);
666 sessionDataFolder += "-sessiondata/";
668 dynamic_string sessionDataPath = sessionPathName;
669 sessionDataPath.append(sessionDataFolder.toStdString().c_str());
670 file_utils::create_directories(sessionDataPath, false);
672 vogl_loose_file_blob_manager file_blob_manager;
673 file_blob_manager.init(cBMFReadWrite, sessionDataPath.c_str());
674 vogl_blob_manager* pBlob_manager = static_cast<vogl_blob_manager*>(&file_blob_manager);
676 QCursor origCursor = this->cursor();
677 setCursor(Qt::WaitCursor);
679 json_document sessionDoc;
680 json_node& metadata = sessionDoc.get_root()->add_object("metadata");
681 metadata.add_key_value("session_file_format_version", to_hex_string(VOGLEDITOR_SESSION_FILE_FORMAT_VERSION));
683 // find relative path from session file to trace file
685 QString absoluteTracePath = relativeAppDir.absoluteFilePath(m_openFilename.toStdString().c_str());
686 QDir absoluteSessionFileDir(sessionPathName.c_str());
687 QString tracePathRelativeToSessionFile = absoluteSessionFileDir.relativeFilePath(absoluteTracePath);
689 json_node& baseTraceFile = sessionDoc.get_root()->add_object("base_trace_file");
690 baseTraceFile.add_key_value("rel_path", tracePathRelativeToSessionFile.toStdString().c_str());
691 json_node &uuid_array = baseTraceFile.add_array("uuid");
692 for (uint i = 0; i < VOGL_ARRAY_SIZE(m_pTraceReader->get_sof_packet().m_uuid); i++)
694 uuid_array.add_value(m_pTraceReader->get_sof_packet().m_uuid[i]);
697 json_node& sessionDataNode = sessionDoc.get_root()->add_object("session_data");
698 sessionDataNode.add_key_value("rel_path", sessionDataFolder.toStdString().c_str());
699 json_node& snapshotArray = sessionDataNode.add_array("snapshots");
701 vogleditor_apiCallTreeItem* pItem = m_pApicallTreeModel->find_next_snapshot(NULL);
702 vogleditor_apiCallTreeItem* pLastItem = NULL;
703 bool bSavedSuccessfully = true;
704 while (pItem != pLastItem && pItem != NULL)
706 dynamic_string filename;
708 json_node& snapshotNode = snapshotArray.add_object();
709 if (pItem->get_snapshot()->get_snapshot() != NULL)
711 dynamic_string strUUID;
712 snapshotNode.add_key_value("uuid", pItem->get_snapshot()->get_snapshot()->get_uuid().get_string(strUUID));
714 snapshotNode.add_key_value("is_valid", pItem->get_snapshot()->is_valid());
715 snapshotNode.add_key_value("is_edited", pItem->get_snapshot()->is_edited());
716 snapshotNode.add_key_value("is_outdated", pItem->get_snapshot()->is_outdated());
718 if (pItem->apiCallItem() != NULL)
720 uint64_t callIndex = pItem->apiCallItem()->globalCallIndex();
721 snapshotNode.add_key_value("call_index", callIndex);
722 if (pItem->get_snapshot()->get_snapshot() != NULL)
724 filename = filename.format("snapshot_call_%" PRIu64 ".json", callIndex);
725 snapshotNode.add_key_value("rel_path", filename);
726 dynamic_string filepath = sessionDataPath;
727 filepath.append(filename);
728 if (!save_snapshot_to_disk(pItem->get_snapshot()->get_snapshot(), filepath, pBlob_manager))
730 bSavedSuccessfully = false;
735 else if (pItem->frameItem() != NULL)
737 // the first frame of a trim will have a snapshot.
738 // this should only be saved out if the snapshot has been edited
739 uint64_t frameNumber = pItem->frameItem()->frameNumber();
740 snapshotNode.add_key_value("frame_number", frameNumber);
741 if (pItem->get_snapshot()->is_edited())
743 filename = filename.format("snapshot_frame_%" PRIu64 ".json", frameNumber);
744 snapshotNode.add_key_value("rel_path", filename);
745 dynamic_string filepath = sessionDataPath;
746 filepath.append(filename);
747 if (!save_snapshot_to_disk(pItem->get_snapshot()->get_snapshot(), filepath, pBlob_manager))
749 bSavedSuccessfully = false;
756 pItem = m_pApicallTreeModel->find_next_snapshot(pLastItem);
759 if (bSavedSuccessfully)
761 bSavedSuccessfully = sessionDoc.serialize_to_file(sessionFile.toStdString().c_str());
764 setCursor(origCursor);
766 return bSavedSuccessfully;
769 bool VoglEditor::save_snapshot_to_disk(vogl_gl_state_snapshot *pSnapshot, dynamic_string filename, vogl_blob_manager *pBlob_manager)
771 if (pSnapshot == NULL)
778 vogl_ctypes trace_gl_ctypes(m_pTraceReader->get_sof_packet().m_pointer_sizes);
780 if (!pSnapshot->serialize(*doc.get_root(), *pBlob_manager, &trace_gl_ctypes))
782 vogl_error_printf("Failed serializing state snapshot document!\n");
785 else if (!doc.serialize_to_file(filename.get_ptr(), true))
787 vogl_error_printf("Failed writing state snapshot to file \"%s\"!\n", filename.get_ptr());
792 vogl_printf("Successfully wrote JSON snapshot to file \"%s\"\n", filename.get_ptr());
798 //----------------------------------------------------------------------------------------------------------------------
799 // read_state_snapshot_from_trace
800 //----------------------------------------------------------------------------------------------------------------------
801 vogl_gl_state_snapshot* VoglEditor::read_state_snapshot_from_trace(vogl_trace_file_reader* pTrace_reader)
803 vogl_ctypes trace_gl_ctypes(pTrace_reader->get_sof_packet().m_pointer_sizes);
805 vogl_trace_packet keyframe_trace_packet(&trace_gl_ctypes);
807 pTrace_reader->seek_to_frame(0);
809 vogl_gl_state_snapshot *pSnapshot = NULL;
810 bool found_snapshot = false;
813 vogl_trace_file_reader::trace_file_reader_status_t read_status = pTrace_reader->read_next_packet();
815 if ((read_status != vogl_trace_file_reader::cOK) && (read_status != vogl_trace_file_reader::cEOF))
817 vogl_error_printf("%s: Failed reading from keyframe trace file!\n", VOGL_FUNCTION_NAME);
821 if ((read_status == vogl_trace_file_reader::cEOF) || (pTrace_reader->get_packet_type() == cTSPTEOF))
823 vogl_error_printf("%s: Failed finding state snapshot in keyframe file!\n", VOGL_FUNCTION_NAME);
827 if (pTrace_reader->get_packet_type() != cTSPTGLEntrypoint)
830 if (!keyframe_trace_packet.deserialize(pTrace_reader->get_packet_buf().get_ptr(), pTrace_reader->get_packet_buf().size(), false))
832 vogl_error_printf("%s: Failed parsing GL entrypoint packet in keyframe file\n", VOGL_FUNCTION_NAME);
836 const vogl_trace_gl_entrypoint_packet *pGL_packet = &pTrace_reader->get_packet<vogl_trace_gl_entrypoint_packet>();
837 gl_entrypoint_id_t entrypoint_id = static_cast<gl_entrypoint_id_t>(pGL_packet->m_entrypoint_id);
839 if (vogl_is_swap_buffers_entrypoint(entrypoint_id) || vogl_is_draw_entrypoint(entrypoint_id) || vogl_is_make_current_entrypoint(entrypoint_id))
841 vogl_error_printf("Failed finding state snapshot in keyframe file!\n");
845 switch (entrypoint_id)
847 case VOGL_ENTRYPOINT_glInternalTraceCommandRAD:
849 GLuint cmd = keyframe_trace_packet.get_param_value<GLuint>(0);
850 GLuint size = keyframe_trace_packet.get_param_value<GLuint>(1); VOGL_NOTE_UNUSED(size);
852 if (cmd == cITCRKeyValueMap)
854 key_value_map &kvm = keyframe_trace_packet.get_key_value_map();
856 dynamic_string cmd_type(kvm.get_string("command_type"));
857 if (cmd_type == "state_snapshot")
859 dynamic_string id(kvm.get_string("binary_id"));
862 vogl_error_printf("%s: Missing binary_id field in glInternalTraceCommandRAD key_valye_map command type: \"%s\"\n", VOGL_FUNCTION_NAME, cmd_type.get_ptr());
866 uint8_vec snapshot_data;
868 timed_scope ts("get_multi_blob_manager().get");
869 if (!pTrace_reader->get_multi_blob_manager().get(id, snapshot_data) || (snapshot_data.is_empty()))
871 vogl_error_printf("%s: Failed reading snapshot blob data \"%s\"!\n", VOGL_FUNCTION_NAME, id.get_ptr());
876 vogl_message_printf("%s: Deserializing state snapshot \"%s\", %u bytes\n", VOGL_FUNCTION_NAME, id.get_ptr(), snapshot_data.size());
880 timed_scope ts("doc.binary_deserialize");
881 if (!doc.binary_deserialize(snapshot_data) || (!doc.get_root()))
883 vogl_error_printf("%s: Failed deserializing JSON snapshot blob data \"%s\"!\n", VOGL_FUNCTION_NAME, id.get_ptr());
888 pSnapshot = vogl_new(vogl_gl_state_snapshot);
890 timed_scope ts("pSnapshot->deserialize");
891 if (!pSnapshot->deserialize(*doc.get_root(), pTrace_reader->get_multi_blob_manager(), &trace_gl_ctypes))
893 vogl_delete(pSnapshot);
896 vogl_error_printf("%s: Failed deserializing snapshot blob data \"%s\"!\n", VOGL_FUNCTION_NAME, id.get_ptr());
900 found_snapshot = true;
909 } while (!found_snapshot);
915 bool VoglEditor::open_trace_file(dynamic_string filename)
917 QCursor origCursor = this->cursor();
918 this->setCursor(Qt::WaitCursor);
920 vogl_loose_file_blob_manager file_blob_manager;
921 dynamic_string keyframe_trace_path(file_utils::get_pathname(filename.get_ptr()));
922 file_blob_manager.init(cBMFReadable, keyframe_trace_path.get_ptr());
924 dynamic_string actual_keyframe_filename;
926 vogl_trace_file_reader* tmpReader = vogl_open_trace_file(filename, actual_keyframe_filename, NULL);
928 if (tmpReader == NULL)
930 m_statusLabel->setText("Failed to open: ");
931 m_statusLabel->setText(m_statusLabel->text().append(filename.c_str()));
932 this->setCursor(origCursor);
937 m_statusLabel->clear();
940 // now that we know the new trace file can be opened,
941 // close the old one, and update the trace reader
943 m_pTraceReader = tmpReader;
945 vogl_ctypes trace_ctypes;
946 trace_ctypes.init(m_pTraceReader->get_sof_packet().m_pointer_sizes);
948 m_pApicallTreeModel = new vogleditor_QApiCallTreeModel(m_pTraceReader);
949 ui->treeView->setModel(m_pApicallTreeModel);
951 if (ui->treeView->selectionModel() != NULL)
953 //connect(ui->treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(on_treeView_selectionChanged(const QItemSelection&, const QItemSelection&)));
954 connect(ui->treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(on_treeView_currentChanged(const QModelIndex &, const QModelIndex &)));
957 if (m_pApicallTreeModel->hasChildren())
959 ui->treeView->setExpanded(m_pApicallTreeModel->index(0,0), true);
960 ui->treeView->setCurrentIndex(m_pApicallTreeModel->index(0,0));
963 int flagsColumnWidth = 30;
964 ui->treeView->header()->setMinimumSectionSize(flagsColumnWidth);
965 ui->treeView->header()->moveSection(VOGL_ACTC_FLAGS, 0);
966 ui->treeView->setColumnWidth(VOGL_ACTC_FLAGS, flagsColumnWidth);
968 int width = ui->treeView->width() - flagsColumnWidth - 30; // subtract a little extra for the scrollbar width
969 ui->treeView->setColumnWidth(VOGL_ACTC_APICALL, width * 0.7);
970 ui->treeView->setColumnWidth(VOGL_ACTC_INDEX, width * 0.15);
971 ui->treeView->setColumnWidth(VOGL_ACTC_DURATION, width * 0.15);
973 ui->searchTextBox->setEnabled(true);
974 ui->searchPrevButton->setEnabled(true);
975 ui->searchNextButton->setEnabled(true);
977 ui->action_Close->setEnabled(true);
978 ui->actionSave_Session->setEnabled(true);
979 ui->actionExport_API_Calls->setEnabled(true);
981 ui->prevSnapshotButton->setEnabled(true);
982 ui->nextSnapshotButton->setEnabled(true);
983 ui->prevDrawcallButton->setEnabled(true);
984 ui->nextDrawcallButton->setEnabled(true);
986 m_backtraceToJsonMap.clear();
987 m_backtraceDoc.clear();
989 // Extract backtrace map and machine info from trace archive
990 if (m_pTraceReader->get_archive_blob_manager().is_initialized())
993 uint8_vec backtrace_data;
994 bool bBacktraceVisible = false;
995 if (m_pTraceReader->get_archive_blob_manager().does_exist(VOGL_TRACE_ARCHIVE_BACKTRACE_MAP_ADDRS_FILENAME))
997 //$ TODO mikesart: read MAP_SYMS data here when symbols have been resolved.
998 if (m_pTraceReader->get_archive_blob_manager().get(VOGL_TRACE_ARCHIVE_BACKTRACE_MAP_ADDRS_FILENAME, backtrace_data))
1000 json_node* pRoot = m_backtraceDoc.get_root();
1001 if (m_backtraceDoc.deserialize((const char*)backtrace_data.get_ptr(), backtrace_data.size()))
1003 bBacktraceVisible = pRoot->size() > 0;
1004 for (uint i = 0; i < pRoot->size(); i++)
1006 json_node* pChild = pRoot->get_child(i);
1008 VOGL_ASSERT("Backtrace node does not have an 'index' child" && pChild != NULL && pChild->get_value_as_uint32("index", index));
1009 if (pChild != NULL && pChild->get_value_as_uint32("index", index))
1011 m_backtraceToJsonMap.insert(index, pChild);
1018 QList<int> backtraceSplitterSizes = ui->splitter_3->sizes();
1019 int backtraceSplitterTotalSize = backtraceSplitterSizes[0] + backtraceSplitterSizes[1];
1020 QList<int> newBacktraceSplitterSizes;
1021 if (!bBacktraceVisible)
1023 newBacktraceSplitterSizes.append(backtraceSplitterTotalSize);
1024 newBacktraceSplitterSizes.append(0);
1025 ui->splitter_3->setSizes(newBacktraceSplitterSizes);
1029 newBacktraceSplitterSizes << (backtraceSplitterTotalSize * 0.75)
1030 << (backtraceSplitterTotalSize * 0.25);
1031 ui->splitter_3->setSizes(newBacktraceSplitterSizes);
1035 displayMachineInfo();
1038 m_openFilename = filename.c_str();
1040 setWindowTitle(m_openFilename + " - " + g_PROJECT_NAME);
1042 ui->tabWidget->setCurrentWidget(ui->framebufferTab);
1045 m_pPlayButton->setEnabled(true);
1046 m_pPauseButton->setEnabled(false);
1047 m_pTrimButton->setEnabled(false);
1048 m_pStopButton->setEnabled(false);
1051 m_pTimelineModel = new vogleditor_apiCallTimelineModel(m_pApicallTreeModel->root());
1052 m_timeline->setModel(m_pTimelineModel);
1053 m_timeline->repaint();
1055 this->setCursor(origCursor);
1059 void VoglEditor::displayMachineInfoHelper(QString prefix, const QString& sectionKeyStr, const vogl::json_value& value, QString& rMachineInfoStr)
1061 if (value.is_array())
1063 const json_node* pNode = value.get_node_ptr();
1064 for (uint element = 0; element < pNode->size(); element++)
1066 dynamic_string elementStr = pNode->get_value(element).as_string();
1068 elementStr = elementStr.replace("\n", "\n\t");
1070 rMachineInfoStr += "\t";
1071 rMachineInfoStr += elementStr.get_ptr();
1072 rMachineInfoStr += "\n";
1075 rMachineInfoStr += "\n";
1077 else if (value.is_node())
1079 // Check if this is the modoule list.
1080 bool is_module_list = (sectionKeyStr == "module_list");
1081 const json_node* pNode = value.get_node_ptr();
1083 for (uint i = 0; i < pNode->size(); i++)
1085 dynamic_string key = pNode->get_key(i);
1086 const json_value &value2 = pNode->get_value(i);
1088 rMachineInfoStr += prefix;
1089 // If it's the module list, then the key is the filename and we want to display that last.
1090 if (!is_module_list)
1091 rMachineInfoStr += key.c_str();
1093 if (value2.is_array())
1095 const json_node* pNode2 = value2.get_node_ptr();
1097 // If this it module_list, then we get these items: base address, address size, uuid
1098 // Check in btrace_get_machine_info() to see what's written there.
1099 for (uint element = 0; element < pNode2->size(); element++)
1101 const json_value &json_val = pNode2->get_value(element);
1103 if (json_val.is_string())
1105 dynamic_string str = pNode2->get_value(element).as_string();
1106 rMachineInfoStr += str.c_str();
1111 buf.format("%" PRIx64, json_val.as_uint64());
1112 rMachineInfoStr += buf.c_str();
1115 rMachineInfoStr += "\t";
1120 rMachineInfoStr += ": ";
1121 rMachineInfoStr += value2.as_string_ptr();
1124 // Display the filename if this is the module_list.
1126 rMachineInfoStr += key.c_str();
1127 rMachineInfoStr += "\n";
1130 rMachineInfoStr += "\n";
1132 else if (value.is_string())
1134 rMachineInfoStr += value.as_string_ptr();
1138 rMachineInfoStr += value.as_string_ptr();
1142 void VoglEditor::displayMachineInfo()
1144 VOGL_ASSERT(m_pTraceReader != NULL);
1146 bool bMachineInfoVisible = false;
1147 if (m_pTraceReader->get_archive_blob_manager().does_exist(VOGL_TRACE_ARCHIVE_MACHINE_INFO_FILENAME))
1149 uint8_vec machine_info_data;
1150 if (m_pTraceReader->get_archive_blob_manager().get(VOGL_TRACE_ARCHIVE_MACHINE_INFO_FILENAME, machine_info_data))
1152 bMachineInfoVisible = true;
1154 json_node *pRoot = doc.get_root();
1155 if (doc.deserialize((const char*)machine_info_data.get_ptr(), machine_info_data.size()))
1158 for (uint i = 0; i < pRoot->size(); i++)
1160 dynamic_string sectionKeyStr = pRoot->get_key(i);
1161 text += pRoot->get_key(i).c_str();
1164 QString keyStr = sectionKeyStr.c_str();
1165 displayMachineInfoHelper("\t", keyStr, pRoot->get_value(i), text);
1168 ui->machineInfoText->setText(text);
1173 if (bMachineInfoVisible)
1175 if (ui->tabWidget->indexOf(ui->machineInfoTab) == -1)
1178 ui->tabWidget->insertTab(0, ui->machineInfoTab, "Machine Info");
1182 VOGLEDITOR_ENABLE_TAB(ui->machineInfoTab);
1187 ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->machineInfoTab));
1191 void VoglEditor::reset_tracefile_ui()
1193 ui->action_Close->setEnabled(false);
1194 ui->actionExport_API_Calls->setEnabled(false);
1195 ui->actionSave_Session->setEnabled(false);
1197 ui->prevSnapshotButton->setEnabled(false);
1198 ui->nextSnapshotButton->setEnabled(false);
1199 ui->prevDrawcallButton->setEnabled(false);
1200 ui->nextDrawcallButton->setEnabled(false);
1201 ui->searchTextBox->clear();
1202 ui->searchTextBox->setEnabled(false);
1203 ui->searchPrevButton->setEnabled(false);
1204 ui->searchNextButton->setEnabled(false);
1206 m_statusLabel->clear();
1207 m_pPlayButton->setEnabled(false);
1208 m_pPauseButton->setEnabled(false);
1209 m_pTrimButton->setEnabled(false);
1210 m_pStopButton->setEnabled(false);
1212 VOGLEDITOR_DISABLE_TAB(ui->machineInfoTab);
1214 reset_snapshot_ui();
1217 void VoglEditor::reset_snapshot_ui()
1219 m_currentSnapshot = NULL;
1221 m_framebufferExplorer->clear();
1222 m_textureExplorer->clear();
1223 m_renderbufferExplorer->clear();
1224 m_programExplorer->clear();
1225 m_shaderExplorer->clear();
1227 ui->stateTreeView->setModel(NULL);
1229 QWidget* pCurrentTab = ui->tabWidget->currentWidget();
1231 VOGLEDITOR_DISABLE_TAB(ui->stateTab);
1232 VOGLEDITOR_DISABLE_TAB(ui->framebufferTab);
1233 VOGLEDITOR_DISABLE_TAB(ui->programTab);
1234 VOGLEDITOR_DISABLE_TAB(ui->shaderTab);
1235 VOGLEDITOR_DISABLE_TAB(ui->textureTab);
1236 VOGLEDITOR_DISABLE_TAB(ui->renderbufferTab);
1238 ui->tabWidget->setCurrentWidget(pCurrentTab);
1241 /// This helper will most often return a pointer equal to the pCurSnapshot that is passed in, or NULL if the node does not have a snapshot
1242 /// and also has no children. The pMostRecentSnapshot parameter will be updated to point to the desired snapshot.
1243 /// This function does not follow a traditional DFS search because we need to find the desired snapshot then return the one before it.
1244 /// An alternative approach would be to keep a stack of the found snapshots, or even to build up that stack / list as the user
1245 /// generates new snapshots.
1246 vogleditor_gl_state_snapshot* VoglEditor::findMostRecentSnapshot_helper(vogleditor_apiCallTreeItem* pItem, vogleditor_gl_state_snapshot*& pMostRecentSnapshot, const vogleditor_gl_state_snapshot* pCurSnapshot)
1248 // check if this item has a snapshot shot
1249 if (pItem->has_snapshot() && pItem->get_snapshot()->is_valid())
1251 vogleditor_gl_state_snapshot* pTmp = pItem->get_snapshot();
1252 if (pTmp == pCurSnapshot)
1254 // if we've reached the item with the current snapshot, we want to return the previous snapshot.
1259 // update most recent snapshot
1260 pMostRecentSnapshot = pTmp;
1264 for (int i = 0; i < pItem->childCount(); i++)
1266 vogleditor_gl_state_snapshot* pTmp = findMostRecentSnapshot_helper(pItem->child(i), pMostRecentSnapshot, pCurSnapshot);
1269 if (pTmp == pCurSnapshot)
1271 // if we've reached the item with the current snapshot, we want to return the previous snapshot.
1276 // update most recent snapshot
1277 pMostRecentSnapshot = pTmp;
1285 /// This function exists just to simplify the interaction with the helper, so that there no confusion between
1286 /// whether the returned value, or passed in reference parameter should be used as the most recent snapshot.
1287 /// It will either return NULL if there is no recent snapshot (which should only happen for the very first snapshot
1288 /// in a trace), or a pointer to a valid snapshot.
1289 vogleditor_gl_state_snapshot* VoglEditor::findMostRecentSnapshot(vogleditor_apiCallTreeItem* pItem, const vogleditor_gl_state_snapshot* pCurSnapshot)
1291 vogleditor_gl_state_snapshot* pMostRecentSnapshot = NULL;
1292 findMostRecentSnapshot_helper(pItem, pMostRecentSnapshot, pCurSnapshot);
1293 return pMostRecentSnapshot;
1296 void VoglEditor::update_ui_for_snapshot(vogleditor_gl_state_snapshot* pStateSnapshot)
1298 if (pStateSnapshot == NULL)
1300 reset_snapshot_ui();
1304 if (pStateSnapshot->is_valid() == false)
1306 reset_snapshot_ui();
1310 if (m_currentSnapshot == pStateSnapshot)
1312 // no need to update if it is the same snapshot
1316 m_currentSnapshot = pStateSnapshot;
1318 if (ui->stateTreeView->model() != NULL)
1320 if (static_cast<vogleditor_QStateTreeModel*>(ui->stateTreeView->model())->get_snapshot() == m_currentSnapshot)
1322 // displaying the same snapshot, return
1327 QCursor origCursor = this->cursor();
1328 this->setCursor(Qt::WaitCursor);
1331 vogleditor_QStateTreeModel* pStateModel = new vogleditor_QStateTreeModel(NULL);
1333 vogleditor_gl_state_snapshot* pBaseSnapshot = findMostRecentSnapshot(m_pApicallTreeModel->root(), m_currentSnapshot);
1334 pStateModel->set_diff_base_snapshot(pBaseSnapshot);
1336 pStateModel->set_snapshot(pStateSnapshot);
1338 ui->stateTreeView->setModel(pStateModel);
1339 ui->stateTreeView->expandToDepth(1);
1340 ui->stateTreeView->setColumnWidth(0, ui->stateTreeView->width() * 0.5);
1342 VOGLEDITOR_ENABLE_TAB(ui->stateTab);
1344 if (pStateSnapshot->get_contexts().size() > 0)
1346 vogl_trace_ptr_value curContextHandle = pStateSnapshot->get_cur_trace_context();
1347 if (curContextHandle != 0)
1349 vogl_context_snapshot* pContext = pStateSnapshot->get_context(curContextHandle);
1352 vogl_gl_object_state_ptr_vec textureObjects;
1353 pContext->get_all_objects_of_category(cGLSTTexture, textureObjects);
1354 m_textureExplorer->set_texture_objects(textureObjects);
1356 GLuint curActiveTextureUnit = pContext->get_general_state().get_value<GLuint>(GL_ACTIVE_TEXTURE);
1357 if (curActiveTextureUnit >= GL_TEXTURE0 && curActiveTextureUnit < (GL_TEXTURE0 + pContext->get_context_info().get_max_texture_image_units()))
1359 GLuint cur2DBinding = pContext->get_general_state().get_value<GLuint>(GL_TEXTURE_2D_BINDING_EXT, curActiveTextureUnit - GL_TEXTURE0);
1360 displayTexture(cur2DBinding, false);
1364 vogl_gl_object_state_ptr_vec renderbufferObjects;
1365 pContext->get_all_objects_of_category(cGLSTRenderbuffer, renderbufferObjects);
1366 m_renderbufferExplorer->set_texture_objects(renderbufferObjects);
1367 if (renderbufferObjects.size() > 0) { VOGLEDITOR_ENABLE_TAB(ui->renderbufferTab); }
1370 vogl_gl_object_state_ptr_vec framebufferObjects;
1371 pContext->get_all_objects_of_category(cGLSTFramebuffer, framebufferObjects);
1372 m_framebufferExplorer->set_framebuffer_objects(framebufferObjects, *pContext, pStateSnapshot->get_default_framebuffer());
1373 GLuint64 curDrawFramebuffer = pContext->get_general_state().get_value<GLuint64>(GL_DRAW_FRAMEBUFFER_BINDING);
1374 displayFramebuffer(curDrawFramebuffer, false);
1377 vogl_gl_object_state_ptr_vec programObjects;
1378 pContext->get_all_objects_of_category(cGLSTProgram, programObjects);
1379 m_programExplorer->set_program_objects(programObjects);
1380 GLuint64 curProgram = pContext->get_general_state().get_value<GLuint64>(GL_CURRENT_PROGRAM);
1381 m_programExplorer->set_active_program(curProgram);
1382 if (programObjects.size() > 0) { VOGLEDITOR_ENABLE_TAB(ui->programTab); }
1385 vogl_gl_object_state_ptr_vec shaderObjects;
1386 pContext->get_all_objects_of_category(cGLSTShader, shaderObjects);
1387 m_shaderExplorer->set_shader_objects(shaderObjects);
1388 if (curProgram != 0)
1390 for (vogl_gl_object_state_ptr_vec::iterator iter = programObjects.begin(); iter != programObjects.end(); iter++)
1392 if ((*iter)->get_snapshot_handle() == curProgram)
1394 vogl_program_state* pProgramState = static_cast<vogl_program_state*>(*iter);
1395 if (pProgramState->get_attached_shaders().size() > 0)
1397 uint curShader = pProgramState->get_attached_shaders()[0];
1398 m_shaderExplorer->set_active_shader(curShader);
1404 if (shaderObjects.size() > 0) { VOGLEDITOR_ENABLE_TAB(ui->shaderTab); }
1408 this->setCursor(origCursor);
1411 void VoglEditor::on_stateTreeView_clicked(const QModelIndex &index)
1413 vogleditor_stateTreeItem* pStateItem = static_cast<vogleditor_stateTreeItem*>(index.internalPointer());
1414 if (pStateItem == NULL)
1419 switch(pStateItem->getStateType())
1421 case vogleditor_stateTreeItem::cTEXTURE:
1423 vogleditor_stateTreeTextureItem* pTextureItem = static_cast<vogleditor_stateTreeTextureItem*>(pStateItem);
1424 if (pTextureItem == NULL)
1429 displayTexture(pTextureItem->get_texture_state()->get_snapshot_handle(), true);
1433 case vogleditor_stateTreeItem::cPROGRAM:
1435 vogleditor_stateTreeProgramItem* pProgramItem = static_cast<vogleditor_stateTreeProgramItem*>(pStateItem);
1436 if (pProgramItem == NULL)
1441 displayProgram(pProgramItem->get_current_state()->get_snapshot_handle(), true);
1445 case vogleditor_stateTreeItem::cSHADER:
1447 vogleditor_stateTreeShaderItem* pShaderItem = static_cast<vogleditor_stateTreeShaderItem*>(pStateItem);
1448 if (pShaderItem == NULL)
1453 displayShader(pShaderItem->get_current_state()->get_snapshot_handle(), true);
1457 case vogleditor_stateTreeItem::cFRAMEBUFFER:
1459 vogleditor_stateTreeFramebufferItem* pFramebufferItem = static_cast<vogleditor_stateTreeFramebufferItem*>(pStateItem);
1460 if (pFramebufferItem == NULL)
1465 displayFramebuffer(pFramebufferItem->get_framebuffer_state()->get_snapshot_handle(), true);
1469 case vogleditor_stateTreeItem::cDEFAULT:
1476 bool VoglEditor::displayShader(GLuint64 shaderHandle, bool bBringTabToFront)
1478 bool bDisplayed = false;
1479 if (m_shaderExplorer->set_active_shader(shaderHandle))
1481 if (bBringTabToFront)
1483 ui->tabWidget->setCurrentWidget(ui->shaderTab);
1490 void VoglEditor::displayProgram(GLuint64 programHandle, bool bBringTabToFront)
1492 if (m_programExplorer->set_active_program(programHandle))
1494 if (bBringTabToFront)
1496 ui->tabWidget->setCurrentWidget(ui->programTab);
1501 void VoglEditor::displayFramebuffer(GLuint64 framebufferHandle, bool bBringTabToFront)
1503 bool bDisplayedFBO = m_framebufferExplorer->set_active_framebuffer(framebufferHandle);
1507 VOGLEDITOR_ENABLE_TAB(ui->framebufferTab);
1508 if (bBringTabToFront)
1510 ui->tabWidget->setCurrentWidget(ui->framebufferTab);
1515 bool VoglEditor::displayTexture(GLuint64 textureHandle, bool bBringTabToFront)
1517 bool bDisplayedTexture = m_textureExplorer->set_active_texture(textureHandle);
1519 if (bDisplayedTexture)
1521 VOGLEDITOR_ENABLE_TAB(ui->textureTab);
1522 if (bBringTabToFront)
1524 ui->tabWidget->setCurrentWidget(ui->textureTab);
1528 return bDisplayedTexture;
1531 void VoglEditor::on_treeView_currentChanged(const QModelIndex & current, const QModelIndex & previous)
1533 VOGL_NOTE_UNUSED(previous);
1534 onApiCallSelected(current, false);
1537 void VoglEditor::on_treeView_clicked(const QModelIndex &index)
1539 onApiCallSelected(index, true);
1542 void VoglEditor::onApiCallSelected(const QModelIndex &index, bool bAllowStateSnapshot)
1544 vogleditor_apiCallTreeItem* pCallTreeItem = static_cast<vogleditor_apiCallTreeItem*>(index.internalPointer());
1545 if (pCallTreeItem == NULL)
1550 vogleditor_frameItem* pFrameItem = pCallTreeItem->frameItem();
1551 vogleditor_apiCallItem* pApiCallItem = pCallTreeItem->apiCallItem();
1553 if (bAllowStateSnapshot && pCallTreeItem == m_pCurrentCallTreeItem)
1555 // we can only get snapshots for specific API calls
1556 if (pApiCallItem != NULL && pApiCallItem->needs_snapshot())
1558 // get the snapshot after the current api call
1559 vogleditor_gl_state_snapshot* pNewSnapshot = NULL;
1560 QCursor origCursor = cursor();
1561 setCursor(Qt::WaitCursor);
1562 m_traceReplayer.replay(m_pTraceReader, m_pApicallTreeModel->root(), &pNewSnapshot, pApiCallItem->globalCallIndex(), false);
1563 setCursor(origCursor);
1564 pCallTreeItem->set_snapshot(pNewSnapshot);
1568 update_ui_for_snapshot(pCallTreeItem->get_snapshot());
1570 if (pApiCallItem != NULL && m_pCurrentCallTreeItem != pCallTreeItem)
1572 if (m_backtraceToJsonMap.size() > 0)
1575 json_node* pBacktraceNode = m_backtraceToJsonMap[(uint)pApiCallItem->backtraceHashIndex()];
1576 if (pBacktraceNode != NULL)
1578 json_node* pAddrs = pBacktraceNode->find_child_array("addrs");
1579 json_node* pSyms = pBacktraceNode->find_child_array("syms");
1581 for (uint i = 0; i < pAddrs->size(); i++)
1583 tmp += pAddrs->get_value(i).as_string_ptr();
1587 tmp += pSyms->get_value(i).as_string_ptr();
1592 ui->backtraceText->setText(tmp);
1596 if (pApiCallItem != NULL)
1598 m_timeline->setCurrentApiCall(pApiCallItem->globalCallIndex());
1601 if (pFrameItem != NULL)
1603 m_timeline->setCurrentFrame(pFrameItem->frameNumber());
1606 m_timeline->repaint();
1608 m_pCurrentCallTreeItem = pCallTreeItem;
1611 void VoglEditor::selectApicallModelIndex(QModelIndex index, bool scrollTo, bool select)
1613 // make sure the index is visible
1614 QModelIndex parentIndex = index.parent();
1615 while (parentIndex.isValid())
1617 if (ui->treeView->isExpanded(parentIndex) == false)
1619 ui->treeView->expand(parentIndex);
1621 parentIndex = parentIndex.parent();
1624 // scroll to the index
1627 ui->treeView->scrollTo(index);
1633 ui->treeView->setCurrentIndex(index);
1636 if (m_searchApicallResults.size() > 0 && !ui->searchTextBox->text().isEmpty())
1638 QItemSelectionModel* pSelection = ui->treeView->selectionModel();
1639 for (int i = 0; i < m_searchApicallResults.size(); i++)
1641 pSelection->select(m_searchApicallResults[i], QItemSelectionModel::Select | QItemSelectionModel::Rows);
1643 ui->treeView->setSelectionModel(pSelection);
1647 void VoglEditor::on_searchTextBox_textChanged(const QString &searchText)
1649 QModelIndex curSearchIndex = ui->treeView->currentIndex();
1650 if (curSearchIndex.isValid() == false)
1655 // store original background color of the search text box so that it can be turned to red and later restored.
1656 static const QColor sOriginalTextBoxBackground = ui->searchTextBox->palette().base().color();
1658 // clear previous items
1659 QItemSelectionModel* pSelection = ui->treeView->selectionModel();
1660 if (pSelection != NULL)
1662 for (int i = 0; i < m_searchApicallResults.size(); i++)
1664 pSelection->select(m_searchApicallResults[i], QItemSelectionModel::Clear | QItemSelectionModel::Rows);
1666 ui->treeView->setSelectionModel(pSelection);
1670 m_searchApicallResults.clear();
1671 if (m_pApicallTreeModel != NULL)
1673 m_searchApicallResults = m_pApicallTreeModel->find_search_matches(searchText);
1676 // if there are matches, restore the textbox background to its original color
1677 if (m_searchApicallResults.size() > 0)
1679 QPalette palette(ui->searchTextBox->palette());
1680 palette.setColor(QPalette::Base, sOriginalTextBoxBackground);
1681 ui->searchTextBox->setPalette(palette);
1685 if (!searchText.isEmpty())
1687 if (m_searchApicallResults.size() > 0)
1689 // scroll to the first result, but don't select it
1690 selectApicallModelIndex(m_searchApicallResults[0], true, false);
1694 // no items were found, so set the textbox background to red
1695 QPalette palette(ui->searchTextBox->palette());
1696 palette.setColor(QPalette::Base, Qt::red);
1697 ui->searchTextBox->setPalette(palette);
1702 void VoglEditor::on_searchNextButton_clicked()
1704 if (m_pApicallTreeModel != NULL)
1706 QModelIndex index = m_pApicallTreeModel->find_next_search_result(m_pCurrentCallTreeItem, ui->searchTextBox->text());
1707 selectApicallModelIndex(index, true, true);
1711 void VoglEditor::on_searchPrevButton_clicked()
1713 if (m_pApicallTreeModel != NULL)
1715 QModelIndex index = m_pApicallTreeModel->find_prev_search_result(m_pCurrentCallTreeItem, ui->searchTextBox->text());
1716 selectApicallModelIndex(index, true, true);
1720 void VoglEditor::on_prevSnapshotButton_clicked()
1722 if (m_pApicallTreeModel != NULL)
1724 vogleditor_apiCallTreeItem* pPrevItemWithSnapshot = m_pApicallTreeModel->find_prev_snapshot(m_pCurrentCallTreeItem);
1725 selectApicallModelIndex(m_pApicallTreeModel->indexOf(pPrevItemWithSnapshot), true, true);
1726 ui->treeView->setFocus();
1730 void VoglEditor::on_nextSnapshotButton_clicked()
1732 if (m_pApicallTreeModel != NULL)
1734 vogleditor_apiCallTreeItem* pNextItemWithSnapshot = m_pApicallTreeModel->find_next_snapshot(m_pCurrentCallTreeItem);
1735 selectApicallModelIndex(m_pApicallTreeModel->indexOf(pNextItemWithSnapshot), true, true);
1736 ui->treeView->setFocus();
1740 void VoglEditor::on_prevDrawcallButton_clicked()
1742 if (m_pApicallTreeModel != NULL)
1744 vogleditor_apiCallTreeItem* pPrevItem = m_pApicallTreeModel->find_prev_drawcall(m_pCurrentCallTreeItem);
1745 selectApicallModelIndex(m_pApicallTreeModel->indexOf(pPrevItem), true, true);
1746 ui->treeView->setFocus();
1750 void VoglEditor::on_nextDrawcallButton_clicked()
1752 if (m_pApicallTreeModel != NULL)
1754 vogleditor_apiCallTreeItem* pNextItem = m_pApicallTreeModel->find_next_drawcall(m_pCurrentCallTreeItem);
1755 selectApicallModelIndex(m_pApicallTreeModel->indexOf(pNextItem), true, true);
1756 ui->treeView->setFocus();
1761 void VoglEditor::on_program_edited(vogl_program_state* pNewProgramState)
1763 VOGL_NOTE_UNUSED(pNewProgramState);
1765 m_currentSnapshot->set_edited(true);
1767 // update all the snapshot flags
1768 bool bFoundEditedSnapshot = false;
1769 recursive_update_snapshot_flags(m_pApicallTreeModel->root(), bFoundEditedSnapshot);
1771 // give the tree view focus so that it redraws. This is something of a hack, we don't really want to be changing around which control has focus,
1772 // but right now I don't see it being a major issue. It may be an issue later on depending on how we implement more state editing (ie, if arrow
1773 // keys are used to cycle through options in a drop-down, and the tree view gets focus, the arrow keys would then start changing the selected
1774 // API call instead of cycling through state options).
1775 ui->treeView->setFocus();
1778 // if an edited snapshot has already been found, mark the node (and all children) as dirty.
1779 void VoglEditor::recursive_update_snapshot_flags(vogleditor_apiCallTreeItem* pItem, bool& bFoundEditedSnapshot)
1781 // check if this item has a snapshot shot
1782 if (pItem->has_snapshot())
1784 if (!bFoundEditedSnapshot)
1786 if (pItem->get_snapshot()->is_edited())
1788 bFoundEditedSnapshot = true;
1792 pItem->get_snapshot()->set_outdated(false);
1797 pItem->get_snapshot()->set_outdated(true);
1801 for (int i = 0; i < pItem->childCount(); i++)
1803 recursive_update_snapshot_flags(pItem->child(i), bFoundEditedSnapshot);
1807 #undef VOGLEDITOR_DISABLE_TAB
1808 #undef VOGLEDITOR_ENABLE_TAB
1810 void VoglEditor::on_actionSave_Session_triggered()
1812 QString baseName = m_openFilename;
1814 int lastIndex = baseName.lastIndexOf('.');
1815 if (lastIndex != -1)
1817 baseName = baseName.remove(lastIndex, baseName.size() - lastIndex);
1820 QString suggestedName = baseName + "-vogleditor.json";
1822 QString sessionFilename = QFileDialog::getSaveFileName(this, tr("Save Debug Session"), suggestedName, tr("JSON (*.json)"));
1824 if (!save_session_to_disk(sessionFilename))
1826 m_statusLabel->setText("ERROR: Failed to save session");
1830 void VoglEditor::on_actionOpen_Session_triggered()
1832 QString sessionFilename = QFileDialog::getOpenFileName(this, tr("Load Debug Session"), QString(), tr("JSON (*.json)"));
1834 QCursor origCursor = this->cursor();
1835 setCursor(Qt::WaitCursor);
1837 if (!load_session_from_disk(sessionFilename))
1839 m_statusLabel->setText("ERROR: Failed to load session");
1842 setCursor(origCursor);